From af0f937df01e2b1ee84b8f436bc5ed050a7a42e7 Mon Sep 17 00:00:00 2001 From: Bibhas Date: Fri, 31 Jan 2020 00:34:08 +0530 Subject: [PATCH 1/7] 2to3 changes + misc fixes --- boxoffice/__init__.py | 4 +- boxoffice/extapi/razorpay.py | 2 +- boxoffice/forms/discount.py | 4 +- boxoffice/forms/order.py | 2 +- boxoffice/forms/price.py | 2 +- boxoffice/models/invoice.py | 4 +- boxoffice/models/item.py | 12 +- boxoffice/models/item_collection.py | 4 +- boxoffice/models/line_item.py | 8 +- boxoffice/models/order.py | 14 +- boxoffice/models/payment.py | 4 +- boxoffice/models/user.py | 4 +- boxoffice/views/admin.py | 14 +- boxoffice/views/admin_category.py | 12 +- boxoffice/views/admin_discount.py | 28 ++-- boxoffice/views/admin_item.py | 30 ++-- boxoffice/views/admin_item_collection.py | 12 +- boxoffice/views/admin_order.py | 4 +- boxoffice/views/admin_report.py | 2 +- boxoffice/views/custom_exceptions.py | 2 +- boxoffice/views/item_collection.py | 2 +- boxoffice/views/login.py | 10 +- boxoffice/views/order.py | 70 ++++----- boxoffice/views/participant.py | 8 +- boxoffice/views/utils.py | 24 +-- manage.py | 2 +- migrations/env.py | 2 +- .../versions/1a22f5035244_create_invoice.py | 4 +- .../versions/1ea1e8070ac8_add_assignee.py | 8 +- .../versions/253e7b76eb8e_modify_assignee.py | 10 +- .../32abb3608d9a_simplify_discounts.py | 4 +- ...58047cfd_update_index_on_discount_title.py | 6 +- .../versions/4ffee334e82e_init_models.py | 10 +- ..._retroactively_migrate_previous_id_for_.py | 4 +- .../829f42c03de3_add_fy_to_invoice.py | 6 +- .../dadc5748932_rm_quantity_available.py | 4 +- rqinit.py | 2 +- scripts/razorpay_settlement.py | 8 +- scripts/razorpay_settlement_old.py | 6 +- scripts/settled_order.py | 8 +- scripts/settlement.py | 20 +-- scripts/settlement1.py | 6 +- scripts/sync_razorpay_refunds.py | 2 +- tests/__init__.py | 2 +- tests/fixtures.py | 76 +++++----- tests/integration/test_items.py | 8 +- tests/test_item_collection.py | 18 +-- tests/test_kharcha.py | 116 +++++++------- tests/test_order.py | 142 +++++++++--------- 49 files changed, 378 insertions(+), 378 deletions(-) diff --git a/boxoffice/__init__.py b/boxoffice/__init__.py index 7d2feae4..84eaf38d 100644 --- a/boxoffice/__init__.py +++ b/boxoffice/__init__.py @@ -29,7 +29,7 @@ from . import extapi, views # NOQA from boxoffice.models import db, User, Item, Price, DiscountPolicy, DiscountCoupon, ItemCollection, Organization, Category, Invoice # noqa -from siteadmin import OrganizationModelView, DiscountCouponModelView, InvoiceModelView # noqa +from .siteadmin import OrganizationModelView, DiscountCouponModelView, InvoiceModelView # noqa # Configure the app @@ -51,7 +51,7 @@ # This is a temporary solution for an admin interface, only # to be used until the native admin interface is ready. try: - admin = Admin(app, name=u"Boxoffice Admin", template_mode='bootstrap3', url='/siteadmin') + admin = Admin(app, name="Boxoffice Admin", template_mode='bootstrap3', url='/siteadmin') admin.add_view(OrganizationModelView(Organization, db.session)) admin.add_view(DiscountCouponModelView(DiscountCoupon, db.session)) admin.add_view(InvoiceModelView(Invoice, db.session)) diff --git a/boxoffice/extapi/razorpay.py b/boxoffice/extapi/razorpay.py index 7b45a0ac..d0d4bb35 100644 --- a/boxoffice/extapi/razorpay.py +++ b/boxoffice/extapi/razorpay.py @@ -50,7 +50,7 @@ def get_settled_transactions(date_range, tz=None): 'receivable_amount', 'settlement_amount', 'buyer_fullname'] # Nested list of dictionaries consisting of transaction details rows = [] - external_transaction_msg = u"Transaction external to Boxoffice. Credited directly to Razorpay?" + external_transaction_msg = "Transaction external to Boxoffice. Credited directly to Razorpay?" for settled_transaction in settled_transactions: if settled_transaction['type'] == 'settlement': diff --git a/boxoffice/forms/discount.py b/boxoffice/forms/discount.py index 1486284e..219627d5 100644 --- a/boxoffice/forms/discount.py +++ b/boxoffice/forms/discount.py @@ -28,7 +28,7 @@ class DiscountPolicyForm(forms.Form): validators=[forms.validators.DataRequired(__("Please specify a discount title")), forms.validators.Length(max=250)], filters=[forms.filters.strip()]) discount_type = forms.RadioField(__("Discount type"), - choices=DISCOUNT_TYPE.items(), coerce=int, default=DISCOUNT_TYPE.COUPON) + choices=list(DISCOUNT_TYPE.items()), coerce=int, default=DISCOUNT_TYPE.COUPON) is_price_based = forms.RadioField(__("Price based discount"), coerce=getbool, default=1, choices=[ (1, __("Special price discount")), @@ -79,7 +79,7 @@ class DiscountPriceForm(forms.Form): validators=[forms.validators.DataRequired(__("Please specify an amount"))]) currency = forms.RadioField(__("Currency"), validators=[forms.validators.DataRequired(__("Please select the currency"))], - choices=CURRENCY.items(), default=CURRENCY.INR) + choices=list(CURRENCY.items()), default=CURRENCY.INR) start_at = forms.DateTimeField(__("Price start date"), validators=[forms.validators.DataRequired(__("Please specify a start date and time"))], naive=False) diff --git a/boxoffice/forms/order.py b/boxoffice/forms/order.py index 87c6f70a..62ef1e4c 100644 --- a/boxoffice/forms/order.py +++ b/boxoffice/forms/order.py @@ -14,7 +14,7 @@ def trim(length): field = forms.StringField(__("Some field"), filters=[trim(25)]) """ def _inner(data): - return unicode(data[0:length]) + return data[0:length] return _inner diff --git a/boxoffice/forms/price.py b/boxoffice/forms/price.py index 99687661..48e6b3bd 100644 --- a/boxoffice/forms/price.py +++ b/boxoffice/forms/price.py @@ -19,6 +19,6 @@ class PriceForm(forms.Form): end_at = forms.DateTimeField(__("End date & time"), validators=[ forms.validators.DataRequired(__("Please specify an end date & time")), - forms.validators.GreaterThan('start_at', __(u"The price can’t end before it starts")) + forms.validators.GreaterThan('start_at', __("The price can’t end before it starts")) ], naive=False) diff --git a/boxoffice/models/invoice.py b/boxoffice/models/invoice.py index b7636918..423ffcca 100644 --- a/boxoffice/models/invoice.py +++ b/boxoffice/models/invoice.py @@ -84,9 +84,9 @@ def __init__(self, *args, **kwargs): country_code = kwargs.get('country_code') if not country_code: # Default to India - country_code = u'IN' + country_code = 'IN' if not organization: - raise ValueError(u"Invoice MUST be initialized with an organization") + raise ValueError("Invoice MUST be initialized with an organization") self.invoiced_at = utcnow() self.fy_start_at, self.fy_end_at = get_fiscal_year(country_code, self.invoiced_at) self.invoice_no = gen_invoice_no(organization, country_code, self.invoiced_at) diff --git a/boxoffice/models/item.py b/boxoffice/models/item.py index e8e44274..e4bdf891 100644 --- a/boxoffice/models/item.py +++ b/boxoffice/models/item.py @@ -23,7 +23,7 @@ class Item(BaseScopedNameMixin, db.Model): __uuid_primary_key__ = True __table_args__ = (db.UniqueConstraint('item_collection_id', 'name'),) - description = MarkdownColumn('description', default=u'', nullable=False) + description = MarkdownColumn('description', default='', nullable=False) seq = db.Column(db.Integer, nullable=False) item_collection_id = db.Column(None, db.ForeignKey('item_collection.id'), nullable=False) @@ -154,7 +154,7 @@ def get_availability(cls, item_ids): item_tups = db.session.query(cls.id, cls.title, cls.quantity_total, db.func.count(cls.id)).join(LineItem).filter( LineItem.item_id.in_(item_ids), LineItem.status == LINE_ITEM_STATUS.CONFIRMED).group_by(cls.id).all() for item_tup in item_tups: - items_dict[unicode(item_tup[0])] = item_tup[1:] + items_dict[item_tup[0]] = item_tup[1:] return items_dict def demand_curve(self): @@ -190,7 +190,7 @@ class Price(BaseScopedNameMixin, db.Model): end_at = db.Column(db.TIMESTAMP(timezone=True), nullable=False) amount = db.Column(db.Numeric, default=Decimal(0), nullable=False) - currency = db.Column(db.Unicode(3), nullable=False, default=u'INR') + currency = db.Column(db.Unicode(3), nullable=False, default='INR') __roles__ = { 'price_owner': { @@ -212,8 +212,8 @@ def discount_policy_title(self): def tense(self): now = utcnow() if self.end_at < now: - return u"past" + return "past" elif self.start_at > now: - return u"upcoming" + return "upcoming" else: - return u"current" + return "current" diff --git a/boxoffice/models/item_collection.py b/boxoffice/models/item_collection.py index 9330525c..4f79fc58 100644 --- a/boxoffice/models/item_collection.py +++ b/boxoffice/models/item_collection.py @@ -13,12 +13,12 @@ class ItemCollection(BaseScopedNameMixin, db.Model): __uuid_primary_key__ = True __table_args__ = (db.UniqueConstraint('organization_id', 'name'),) - description = MarkdownColumn('description', default=u'', nullable=False) + description = MarkdownColumn('description', default='', nullable=False) organization_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable=False) organization = db.relationship(Organization, backref=db.backref('item_collections', cascade='all, delete-orphan')) parent = db.synonym('organization') - tax_type = db.Column(db.Unicode(80), nullable=True, default=u'GST') + tax_type = db.Column(db.Unicode(80), nullable=True, default='GST') # ISO 3166-2 code. Eg: KA for Karnataka place_supply_state_code = db.Column(db.Unicode(3), nullable=True) # ISO country code diff --git a/boxoffice/models/line_item.py b/boxoffice/models/line_item.py index 46999f62..2e1fbd0c 100644 --- a/boxoffice/models/line_item.py +++ b/boxoffice/models/line_item.py @@ -137,9 +137,9 @@ def calculate(cls, line_items, recalculate=False, coupons=[]): base_amount = item.current_price().amount if item.is_available else None line_item_id = None - if not item_line_items.get(unicode(item.id)): - item_line_items[unicode(item.id)] = [] - item_line_items[unicode(item.id)].append(make_ntuple(item_id=item.id, + if not item_line_items.get(str(item.id)): + item_line_items[str(item.id)] = [] + item_line_items[str(item.id)].append(make_ntuple(item_id=item.id, base_amount=base_amount, line_item_id=line_item_id)) for item_id in item_line_items.keys(): @@ -241,7 +241,7 @@ def counts_per_date_per_item(item_collection, user_tz): """ date_item_counts = {} for item in item_collection.items: - item_id = unicode(item.id) + item_id = str(item.id) item_results = db.session.query('date', 'count').from_statement( db.text('''SELECT DATE_TRUNC('day', line_item.ordered_at AT TIME ZONE :timezone)::date as date, count(line_item.id) AS count FROM line_item WHERE item_id = :item_id AND status = :status diff --git a/boxoffice/models/order.py b/boxoffice/models/order.py index dfd0dac2..535541f7 100644 --- a/boxoffice/models/order.py +++ b/boxoffice/models/order.py @@ -133,11 +133,11 @@ class OrderSession(BaseMixin, db.Model): host = db.Column(db.UnicodeText, nullable=True) # Google Analytics parameters - utm_source = db.Column(db.Unicode(250), nullable=False, default=u'', index=True) - utm_medium = db.Column(db.Unicode(250), nullable=False, default=u'', index=True) - utm_term = db.Column(db.Unicode(250), nullable=False, default=u'') - utm_content = db.Column(db.Unicode(250), nullable=False, default=u'') - utm_id = db.Column(db.Unicode(250), nullable=False, default=u'', index=True) - utm_campaign = db.Column(db.Unicode(250), nullable=False, default=u'', index=True) + utm_source = db.Column(db.Unicode(250), nullable=False, default='', index=True) + utm_medium = db.Column(db.Unicode(250), nullable=False, default='', index=True) + utm_term = db.Column(db.Unicode(250), nullable=False, default='') + utm_content = db.Column(db.Unicode(250), nullable=False, default='') + utm_id = db.Column(db.Unicode(250), nullable=False, default='', index=True) + utm_campaign = db.Column(db.Unicode(250), nullable=False, default='', index=True) # Google click id (for AdWords) - gclid = db.Column(db.Unicode(250), nullable=False, default=u'', index=True) + gclid = db.Column(db.Unicode(250), nullable=False, default='', index=True) diff --git a/boxoffice/models/payment.py b/boxoffice/models/payment.py index 4db2e81e..053cc6dd 100644 --- a/boxoffice/models/payment.py +++ b/boxoffice/models/payment.py @@ -139,11 +139,11 @@ def item_collection_net_sales(self): class CURRENCY(LabeledEnum): - INR = (u"INR", __("INR")) + INR = ("INR", __("INR")) class CURRENCY_SYMBOL(LabeledEnum): - INR = (u'INR', u'₹') + INR = ('INR', '₹') def calculate_weekly_refunds(item_collection_ids, user_tz, year): diff --git a/boxoffice/models/user.py b/boxoffice/models/user.py index 76a49872..f6fee15a 100644 --- a/boxoffice/models/user.py +++ b/boxoffice/models/user.py @@ -75,7 +75,7 @@ def get_fiscal_year(jurisdiction, dt): Example:: get_fiscal_year('IN', utcnow()) """ - if jurisdiction.lower() == u'in': + if jurisdiction.lower() == 'in': if dt.month < 4: start_year = dt.year - 1 else: @@ -84,6 +84,6 @@ def get_fiscal_year(jurisdiction, dt): fy_start = datetime(start_year, 4, 1) # ends on April 1 XXXX + 1 fy_end = datetime(start_year + 1, 4, 1) - timezone = u'Asia/Kolkata' + timezone = 'Asia/Kolkata' return (naive_to_utc(fy_start, timezone), naive_to_utc(fy_end, timezone)) return (naive_to_utc(datetime(dt.year, 1, 1)), naive_to_utc(datetime(dt.year + 1, 1, 1))) diff --git a/boxoffice/views/admin.py b/boxoffice/views/admin.py index 0d473b35..c2fe68e2 100644 --- a/boxoffice/views/admin.py +++ b/boxoffice/views/admin.py @@ -50,23 +50,23 @@ def org_revenue(organization): check_api_access(organization.details.get('access_token')) if not request.args.get('year'): - return api_error(message=_(u"Missing year"), status_code=400) + return api_error(message=_("Missing year"), status_code=400) if not request.args.get('timezone'): - return api_error(message=_(u"Missing timezone"), status_code=400) + return api_error(message=_("Missing timezone"), status_code=400) if request.args.get('timezone') not in pytz.common_timezones: - return api_error(message=_(u"Unknown timezone. Timezone is case-sensitive"), status_code=400) + return api_error(message=_("Unknown timezone. Timezone is case-sensitive"), status_code=400) item_collection_ids = [item_collection.id for item_collection in organization.item_collections] year = int(request.args.get('year')) user_timezone = request.args.get('timezone') if getbool(request.args.get('refund')): - result = calculate_weekly_refunds(item_collection_ids, user_timezone, year).items() - doc = _(u"Refunds per week for {year}".format(year=year)) + result = list(calculate_weekly_refunds(item_collection_ids, user_timezone, year).items()) + doc = _("Refunds per week for {year}".format(year=year)) else: # sales includes confirmed and cancelled line items - result = calculate_weekly_sales(item_collection_ids, user_timezone, year).items() - doc = _(u"Revenue per week for {year}".format(year=year)) + result = list(calculate_weekly_sales(item_collection_ids, user_timezone, year).items()) + doc = _("Revenue per week for {year}".format(year=year)) return api_success(result=result, doc=doc, status_code=200) diff --git a/boxoffice/views/admin_category.py b/boxoffice/views/admin_category.py index c6ef9c32..91ac3b6f 100644 --- a/boxoffice/views/admin_category.py +++ b/boxoffice/views/admin_category.py @@ -14,7 +14,7 @@ def jsonify_new_category(data_dict): item_collection = data_dict['item_collection'] category_form = CategoryForm(parent=item_collection) if request.method == 'GET': - return jsonify(form_template=render_form(form=category_form, title=u"New item", submit=u"Create", with_chrome=False)) + return jsonify(form_template=render_form(form=category_form, title="New item", submit="Create", with_chrome=False)) if category_form.validate_on_submit(): category = Category(item_collection=item_collection) category_form.populate_obj(category) @@ -22,8 +22,8 @@ def jsonify_new_category(data_dict): category.make_name() db.session.add(category) db.session.commit() - return api_success(result={'category': dict(category.current_access())}, doc=_(u"New category created"), status_code=201) - return api_error(message=_(u"There was a problem with creating the item"), errors=category_form.errors, status_code=400) + return api_success(result={'category': dict(category.current_access())}, doc=_("New category created"), status_code=201) + return api_error(message=_("There was a problem with creating the item"), errors=category_form.errors, status_code=400) @app.route('/admin/ic//category/new', methods=['GET', 'POST']) @@ -41,12 +41,12 @@ def jsonify_edit_category(data_dict): category = data_dict['category'] category_form = CategoryForm(obj=category) if request.method == 'GET': - return jsonify(form_template=render_form(form=category_form, title=u"Edit category", submit=u"Update", with_chrome=False)) + return jsonify(form_template=render_form(form=category_form, title="Edit category", submit="Update", with_chrome=False)) if category_form.validate_on_submit(): category_form.populate_obj(category) db.session.commit() - return api_success(result={'category': dict(category.current_access())}, doc=_(u"Category was updated"), status_code=201) - return api_error(message=_(u"There was a problem with updating the category"), errors=category_form.errors, status_code=400) + return api_success(result={'category': dict(category.current_access())}, doc=_("Category was updated"), status_code=201) + return api_error(message=_("There was a problem with updating the category"), errors=category_form.errors, status_code=400) @app.route('/admin/ic//category//edit', methods=['GET', 'POST']) diff --git a/boxoffice/views/admin_discount.py b/boxoffice/views/admin_discount.py index c10d82bd..721a7aec 100644 --- a/boxoffice/views/admin_discount.py +++ b/boxoffice/views/admin_discount.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import division + from flask import jsonify, request from .. import app, lastuser from baseframe import _ @@ -10,7 +10,7 @@ from ..models import db from boxoffice.models import Organization, DiscountPolicy, DiscountCoupon, Price, CURRENCY from ..forms import DiscountPolicyForm, DiscountCouponForm, DiscountPriceForm, CouponBasedDiscountPolicyForm, AutomaticDiscountPolicyForm, PriceBasedDiscountPolicyForm -from utils import xhr_only, api_error, api_success +from .utils import xhr_only, api_error, api_success def jsonify_discount_policy(discount_policy): @@ -73,7 +73,7 @@ def admin_new_discount_policy(organization): discount_policy = DiscountPolicy(organization=organization) discount_policy_form = DiscountPolicyForm(model=DiscountPolicy) discount_policy_form.populate_obj(discount_policy) - discount_policy_error_msg = _(u"The discount could not be created. Please rectify the indicated issues") + discount_policy_error_msg = _("The discount could not be created. Please rectify the indicated issues") if discount_policy.is_price_based: discount_policy_form = PriceBasedDiscountPolicyForm(model=DiscountPolicy, parent=discount_policy.organization) @@ -86,7 +86,7 @@ def admin_new_discount_policy(organization): discount_policy.make_name() discount_price_form = DiscountPriceForm(model=Price, parent=discount_policy) if not discount_price_form.validate_on_submit(): - return api_error(message=_(u"There was an issue with the price. Please rectify the indicated issues"), + return api_error(message=_("There was an issue with the price. Please rectify the indicated issues"), status_code=400, errors=discount_price_form.errors) discount_price = Price(discount_policy=discount_policy) @@ -109,12 +109,12 @@ def admin_new_discount_policy(organization): discount_policy_form.populate_obj(discount_policy) discount_policy.make_name() else: - return api_error(message=_(u"Incorrect discount type"), status_code=400) + return api_error(message=_("Incorrect discount type"), status_code=400) db.session.add(discount_policy) db.session.commit() return api_success(result={'discount_policy': jsonify_discount_policy(discount_policy)}, - doc=_(u"New discount policy created"), status_code=201) + doc=_("New discount policy created"), status_code=201) @app.route('/admin/discount_policy//edit', methods=['POST']) @@ -125,13 +125,13 @@ def admin_new_discount_policy(organization): permission='org_admin' ) def admin_edit_discount_policy(discount_policy): - discount_policy_error_msg = _(u"The discount could not be updated. Please rectify the indicated issues") + discount_policy_error_msg = _("The discount could not be updated. Please rectify the indicated issues") if discount_policy.is_price_based and discount_policy.items: discount_policy_form = PriceBasedDiscountPolicyForm(obj=discount_policy, model=DiscountPolicy) discount_price = Price.query.filter_by(item=discount_policy.items[0], discount_policy=discount_policy).one() discount_price_form = DiscountPriceForm(obj=discount_price, model=Price, parent=discount_policy) if not discount_price_form.validate_on_submit(): - return api_error(message=_(u"There was an issue with the price. Please rectify the indicated issues"), + return api_error(message=_("There was an issue with the price. Please rectify the indicated issues"), status_code=400, errors=discount_price_form.errors) discount_price_form.populate_obj(discount_price) @@ -144,7 +144,7 @@ def admin_edit_discount_policy(discount_policy): elif discount_policy.is_automatic: discount_policy_form = AutomaticDiscountPolicyForm(obj=discount_policy, model=DiscountPolicy) else: - return api_error(message=_(u"Incorrect discount type"), status_code=400) + return api_error(message=_("Incorrect discount type"), status_code=400) if discount_policy_form.validate_on_submit(): discount_policy_form.populate_obj(discount_policy) @@ -166,10 +166,10 @@ def admin_edit_discount_policy(discount_policy): def admin_delete_discount_policy(discount_policy): form = forms.Form() if request.method == 'GET': - return jsonify(form_template=render_form(form=form, title=u"Delete discount policy", submit=u"Delete", with_chrome=False)) + return jsonify(form_template=render_form(form=form, title="Delete discount policy", submit="Delete", with_chrome=False)) if not form.validate_on_submit(): - return api_error(message=_(u"The discount policy could not be deleted."), + return api_error(message=_("The discount policy could not be deleted."), status_code=400, errors=form.errors) @@ -189,7 +189,7 @@ def admin_new_coupon(discount_policy): coupon_form = DiscountCouponForm(parent=discount_policy) coupons = [] if not coupon_form.validate_on_submit(): - return api_error(message=_(u"The coupon could not be created. Please rectify the indicated issues"), + return api_error(message=_("The coupon could not be created. Please rectify the indicated issues"), status_code=400, errors=coupon_form.errors) if coupon_form.count.data > 1: # Create a signed discount coupon code @@ -202,7 +202,7 @@ def admin_new_coupon(discount_policy): db.session.add(coupon) db.session.commit() coupons.append(coupon.code) - return api_success(result={'coupons': coupons}, doc=_(u"Discount coupon created"), status_code=201) + return api_success(result={'coupons': coupons}, doc=_("Discount coupon created"), status_code=201) @app.route('/admin/discount_policy//coupons') @@ -214,4 +214,4 @@ def admin_new_coupon(discount_policy): ) def admin_discount_coupons(discount_policy): coupons_list = [{'code': coupon.code, 'usage_limit': coupon.usage_limit, 'available': coupon.usage_limit - coupon.used_count} for coupon in discount_policy.discount_coupons] - return api_success(result={'coupons': coupons_list}, doc=_(u"List of discount coupons"), status_code=200) + return api_success(result={'coupons': coupons_list}, doc=_("List of discount coupons"), status_code=200) diff --git a/boxoffice/views/admin_item.py b/boxoffice/views/admin_item.py index 574eda64..b3f7d3c9 100644 --- a/boxoffice/views/admin_item.py +++ b/boxoffice/views/admin_item.py @@ -9,7 +9,7 @@ from boxoffice.models import db, Organization, ItemCollection, Item, Price from boxoffice.views.utils import api_error, api_success, json_date_format from boxoffice.forms import ItemForm, PriceForm -from utils import xhr_only +from .utils import xhr_only @app.route('/admin/o//items') @@ -34,7 +34,7 @@ def items(organization, search=None): 'title': "{ic_title}: {title}".format(ic_title=item_tuple[1].title, title=item_tuple[0].title) } for item_tuple in filtered_items]}, doc="Filtered items", status_code=200) else: - return api_error(message=_(u"Missing search query"), status_code=400) + return api_error(message=_("Missing search query"), status_code=400) def jsonify_price(price): @@ -103,7 +103,7 @@ def jsonify_new_item(data_dict): item_collection = data_dict['item_collection'] item_form = ItemForm(parent=item_collection) if request.method == 'GET': - return jsonify(form_template=render_form(form=item_form, title=u"New item", submit=u"Create", with_chrome=False)) + return jsonify(form_template=render_form(form=item_form, title="New item", submit="Create", with_chrome=False)) if item_form.validate_on_submit(): item = Item(item_collection=item_collection) item_form.populate_obj(item) @@ -111,8 +111,8 @@ def jsonify_new_item(data_dict): item.make_name() db.session.add(item) db.session.commit() - return api_success(result={'item': dict(item.current_access())}, doc=_(u"New item created"), status_code=201) - return api_error(message=_(u"There was a problem with creating the item"), errors=item_form.errors, status_code=400) + return api_success(result={'item': dict(item.current_access())}, doc=_("New item created"), status_code=201) + return api_error(message=_("There was a problem with creating the item"), errors=item_form.errors, status_code=400) @app.route('/admin/ic//item/new', methods=['GET', 'POST']) @@ -130,12 +130,12 @@ def jsonify_edit_item(data_dict): item = data_dict['item'] item_form = ItemForm(obj=item) if request.method == 'GET': - return jsonify(form_template=render_form(form=item_form, title=u"Update item", submit=u"Update", with_chrome=False)) + return jsonify(form_template=render_form(form=item_form, title="Update item", submit="Update", with_chrome=False)) if item_form.validate_on_submit(): item_form.populate_obj(item) db.session.commit() - return api_success(result={'item': dict(item.current_access())}, doc=_(u"Item updated"), status_code=200) - return api_error(message=_(u"There was a problem with updating the item"), status_code=400, errors=item_form.errors) + return api_success(result={'item': dict(item.current_access())}, doc=_("Item updated"), status_code=200) + return api_error(message=_("There was a problem with updating the item"), status_code=400, errors=item_form.errors) @app.route('/admin/item//edit', methods=['GET', 'POST']) @@ -153,18 +153,18 @@ def jsonify_new_price(data_dict): item = data_dict['item'] price_form = PriceForm(parent=item) if request.method == 'GET': - return jsonify(form_template=render_form(form=price_form, title=u"New price", submit=u"Save", with_chrome=False)) + return jsonify(form_template=render_form(form=price_form, title="New price", submit="Save", with_chrome=False)) if price_form.validate_on_submit(): price = Price(item=item) price_form.populate_obj(price) - price.title = u"{item_name}-price-{datetime}".format(item_name=item.name, + price.title = "{item_name}-price-{datetime}".format(item_name=item.name, datetime=json_date_format(utcnow())) if not price.name: price.make_name() db.session.add(price) db.session.commit() - return api_success(result={'price': dict(price.current_access())}, doc=_(u"New price created"), status_code=201) - return api_error(message=_(u"There was a problem with creating the price"), status_code=400, errors=price_form.errors) + return api_success(result={'price': dict(price.current_access())}, doc=_("New price created"), status_code=201) + return api_error(message=_("There was a problem with creating the price"), status_code=400, errors=price_form.errors) @app.route('/admin/item//price/new', methods=['GET', 'POST']) @@ -182,12 +182,12 @@ def jsonify_edit_price(data_dict): price = data_dict['price'] price_form = PriceForm(obj=price) if request.method == 'GET': - return jsonify(form_template=render_form(form=price_form, title=u"Update price", submit=u"Save", with_chrome=False)) + return jsonify(form_template=render_form(form=price_form, title="Update price", submit="Save", with_chrome=False)) if price_form.validate_on_submit(): price_form.populate_obj(price) db.session.commit() - return api_success(result={'price': dict(price.current_access())}, doc=_(u"Update price {title}.".format(title=price.title)), status_code=200) - return api_error(message=_(u"There was a problem with editing the price"), status_code=400, errors=price_form.errors) + return api_success(result={'price': dict(price.current_access())}, doc=_("Update price {title}.".format(title=price.title)), status_code=200) + return api_error(message=_("There was a problem with editing the price"), status_code=400, errors=price_form.errors) @app.route('/admin/item//price//edit', methods=['GET', 'POST']) diff --git a/boxoffice/views/admin_item_collection.py b/boxoffice/views/admin_item_collection.py index d815451e..9517ca14 100644 --- a/boxoffice/views/admin_item_collection.py +++ b/boxoffice/views/admin_item_collection.py @@ -53,7 +53,7 @@ def jsonify_new_item_collection(item_collection_dict): ic_form = ItemCollectionForm() if request.method == 'GET': return jsonify(form_template=render_form(form=ic_form, - title=u"New item collection", submit=u"Create", ajax=False, with_chrome=False)) + title="New item collection", submit="Create", ajax=False, with_chrome=False)) if ic_form.validate_on_submit(): ic = ItemCollection(organization=item_collection_dict['organization']) ic_form.populate_obj(ic) @@ -62,8 +62,8 @@ def jsonify_new_item_collection(item_collection_dict): db.session.add(ic) db.session.commit() return api_success(result={'item_collection': dict(ic.current_access())}, - doc=_(u"New item collection created"), status_code=201) - return api_error(message=_(u"There was a problem with creating the item collection"), + doc=_("New item collection created"), status_code=201) + return api_error(message=_("There was a problem with creating the item collection"), errors=ic_form.errors, status_code=400) @@ -83,13 +83,13 @@ def jsonify_edit_item_collection(item_collection_dict): ic_form = ItemCollectionForm(obj=item_collection) if request.method == 'GET': return jsonify(form_template=render_form(form=ic_form, - title=u"Edit item collection", submit=u"Save", ajax=False, with_chrome=False)) + title="Edit item collection", submit="Save", ajax=False, with_chrome=False)) if ic_form.validate_on_submit(): ic_form.populate_obj(item_collection) db.session.commit() return api_success(result={'item_collection': dict(item_collection.current_access())}, - doc=_(u"Edited item collection {title}.".format(title=item_collection.title)), status_code=200) - return api_error(message=_(u"There was a problem with editing the item collection"), + doc=_("Edited item collection {title}.".format(title=item_collection.title)), status_code=200) + return api_error(message=_("There was a problem with editing the item collection"), errors=ic_form.errors, status_code=400) diff --git a/boxoffice/views/admin_order.py b/boxoffice/views/admin_order.py index 19905c6a..f03a2dc8 100644 --- a/boxoffice/views/admin_order.py +++ b/boxoffice/views/admin_order.py @@ -4,7 +4,7 @@ from .. import app, lastuser from coaster.views import load_models, render_with from boxoffice.models import ItemCollection, Organization, Order, CURRENCY_SYMBOL, LineItem, LINE_ITEM_STATUS, ORDER_STATUS, INVOICE_STATUS -from utils import json_date_format, xhr_only, check_api_access +from .utils import json_date_format, xhr_only, check_api_access def format_assignee(assignee): @@ -54,7 +54,7 @@ def jsonify_admin_orders(data_dict): 'buyer_phone': order.buyer_phone, 'currency': CURRENCY_SYMBOL['INR'], 'amount': order.net_amount, - 'url': '/ic/' + unicode(item_collection_id) + '/' + unicode(order.id), + 'url': '/ic/' + str(item_collection_id) + '/' + str(order.id), 'receipt_url': url_for('receipt', access_token=order.access_token), 'assignee_url': url_for('line_items', access_token=order.access_token) }) diff --git a/boxoffice/views/admin_report.py b/boxoffice/views/admin_report.py index 64967dbf..9588fbf6 100644 --- a/boxoffice/views/admin_report.py +++ b/boxoffice/views/admin_report.py @@ -169,7 +169,7 @@ def invoices_report(organization): headers, rows = organization.fetch_invoices() def row_handler(row): - dict_row = dict(zip(headers, row)) + dict_row = dict(list(zip(headers, row))) if dict_row.get('status') in INVOICE_STATUS.keys(): dict_row['status'] = INVOICE_STATUS.get(dict_row['status']) if isinstance(dict_row.get('invoiced_at'), datetime): diff --git a/boxoffice/views/custom_exceptions.py b/boxoffice/views/custom_exceptions.py index c40d0257..7c930ca2 100644 --- a/boxoffice/views/custom_exceptions.py +++ b/boxoffice/views/custom_exceptions.py @@ -2,7 +2,7 @@ from .. import app from flask import jsonify, make_response -from utils import cors +from .utils import cors class PaymentGatewayError(Exception): diff --git a/boxoffice/views/item_collection.py b/boxoffice/views/item_collection.py index b44770bd..aab6b02f 100644 --- a/boxoffice/views/item_collection.py +++ b/boxoffice/views/item_collection.py @@ -6,7 +6,7 @@ from coaster.utils import getbool from boxoffice import app from boxoffice.models import Organization, ItemCollection, Item, DiscountPolicy -from utils import xhr_only, cors, sanitize_coupons +from .utils import xhr_only, cors, sanitize_coupons from boxoffice.data import indian_states diff --git a/boxoffice/views/login.py b/boxoffice/views/login.py index 7fc4a4d6..4047b340 100644 --- a/boxoffice/views/login.py +++ b/boxoffice/views/login.py @@ -18,7 +18,7 @@ def login(): @app.route('/logout') @lastuser.logout_handler def logout(): - flash(_(u"You are now logged out"), category='success') + flash(_("You are now logged out"), category='success') return get_next_url() @@ -40,12 +40,12 @@ def lastusernotify(user): @lastuser.auth_error_handler def lastuser_error(error, error_description=None, error_uri=None): if error == 'access_denied': - flash(_(u"You denied the request to login"), category='error') + flash(_("You denied the request to login"), category='error') return redirect(get_next_url()) return render_message( - title=_(u"Error: {error}").format(error=error), + title=_("Error: {error}").format(error=error), message=Markup( - u"

{desc}

URI: {uri}

".format( - desc=escape(error_description or u''), uri=escape(error_uri or _(u'NA'))) + "

{desc}

URI: {uri}

".format( + desc=escape(error_description or ''), uri=escape(error_uri or _('NA'))) ) ) diff --git a/boxoffice/views/order.py b/boxoffice/views/order.py index 3a664b2c..40b81420 100644 --- a/boxoffice/views/order.py +++ b/boxoffice/views/order.py @@ -14,9 +14,9 @@ from ..models.payment import TRANSACTION_TYPE from ..extapi import razorpay, RAZORPAY_PAYMENT_STATUS from ..forms import LineItemForm, BuyerForm, OrderSessionForm, OrderRefundForm, InvoiceForm -from custom_exceptions import PaymentGatewayError +from .custom_exceptions import PaymentGatewayError from boxoffice.mailclient import send_receipt_mail, send_line_item_cancellation_mail, send_order_refund_mail -from utils import xhr_only, cors, json_date_format, api_error, api_success, sanitize_coupons +from .utils import xhr_only, cors, json_date_format, api_error, api_success, sanitize_coupons from boxoffice.data import indian_states @@ -28,19 +28,19 @@ def jsonify_line_items(line_items): items_json = dict() for line_item in line_items: item = Item.query.get(line_item.item_id) - if not items_json.get(unicode(line_item.item_id)): - items_json[unicode(line_item.item_id)] = {'is_available': item.is_available, 'quantity': 0, 'final_amount': Decimal(0), 'discounted_amount': Decimal(0), 'discount_policy_ids': []} + if not items_json.get(str(line_item.item_id)): + items_json[str(line_item.item_id)] = {'is_available': item.is_available, 'quantity': 0, 'final_amount': Decimal(0), 'discounted_amount': Decimal(0), 'discount_policy_ids': []} if line_item.base_amount is not None: - items_json[unicode(line_item.item_id)]['base_amount'] = line_item.base_amount - items_json[unicode(line_item.item_id)]['final_amount'] += line_item.base_amount - line_item.discounted_amount - items_json[unicode(line_item.item_id)]['discounted_amount'] += line_item.discounted_amount + items_json[str(line_item.item_id)]['base_amount'] = line_item.base_amount + items_json[str(line_item.item_id)]['final_amount'] += line_item.base_amount - line_item.discounted_amount + items_json[str(line_item.item_id)]['discounted_amount'] += line_item.discounted_amount else: - items_json[unicode(line_item.item_id)]['final_amount'] = None - items_json[unicode(line_item.item_id)]['discounted_amount'] = None - items_json[unicode(line_item.item_id)]['quantity'] += 1 - items_json[unicode(line_item.item_id)]['quantity_available'] = item.quantity_available - if line_item.discount_policy_id and line_item.discount_policy_id not in items_json[unicode(line_item.item_id)]['discount_policy_ids']: - items_json[unicode(line_item.item_id)]['discount_policy_ids'].append(line_item.discount_policy_id) + items_json[str(line_item.item_id)]['final_amount'] = None + items_json[str(line_item.item_id)]['discounted_amount'] = None + items_json[str(line_item.item_id)]['quantity'] += 1 + items_json[str(line_item.item_id)]['quantity_available'] = item.quantity_available + if line_item.discount_policy_id and line_item.discount_policy_id not in items_json[str(line_item.item_id)]['discount_policy_ids']: + items_json[str(line_item.item_id)]['discount_policy_ids'].append(line_item.discount_policy_id) return items_json @@ -133,7 +133,7 @@ def order(item_collection): return api_error(message="Invalid buyer details", status_code=400, errors=buyer_form.errors) - invalid_quantity_error_msg = _(u'Selected quantity for ‘{item}’ is not available. Please edit the order and update the quantity') + invalid_quantity_error_msg = _('Selected quantity for ‘{item}’ is not available. Please edit the order and update the quantity') item_dicts = Item.get_availability([line_item_form.data.get('item_id') for line_item_form in line_item_forms]) for line_item_form in line_item_forms: @@ -191,7 +191,7 @@ def order(item_collection): final_amount=line_item_tup.base_amount - line_item_tup.discounted_amount) db.session.add(line_item) else: - return api_error(message=_(u"‘{item}’ is no longer available.").format(item=item.title), + return api_error(message=_("‘{item}’ is no longer available.").format(item=item.title), status_code=400, errors=['order calculation error']) @@ -206,7 +206,7 @@ def order(item_collection): db.session.commit() - return api_success(doc=_(u"New purchase order created"), + return api_success(doc=_("New purchase order created"), result={'order_id': order.id, 'order_access_token': order.access_token, 'payment_url': url_for('payment', order=order.id), @@ -237,9 +237,9 @@ def free(order): line_item.discount_coupon.update_used_count() db.session.add(line_item.discount_coupon) db.session.commit() - send_receipt_mail.queue(order.id, subject=u"{item_collection_title}: Your registration is confirmed!".format(item_collection_title=order.item_collection.title), template='free_order_confirmation_mail.html.jinja2') + send_receipt_mail.queue(order.id, subject="{item_collection_title}: Your registration is confirmed!".format(item_collection_title=order.item_collection.title), template='free_order_confirmation_mail.html.jinja2') return api_success(result={'order_id': order.id}, - doc=_(u"Free order confirmed"), status_code=201) + doc=_("Free order confirmed"), status_code=201) else: return api_error(message="Free order confirmation failed", @@ -288,19 +288,19 @@ def payment(order): line_item.discount_coupon.update_used_count() db.session.add(line_item.discount_coupon) db.session.commit() - send_receipt_mail.queue(order.id, subject=u"{item_collection_title}: Thank you for your order (#{invoice_no})!".format(item_collection_title=order.item_collection.title, invoice_no=order.invoice_no)) + send_receipt_mail.queue(order.id, subject="{item_collection_title}: Thank you for your order (#{invoice_no})!".format(item_collection_title=order.item_collection.title, invoice_no=order.invoice_no)) return api_success(result={'invoice_id': invoice.id}, - doc=_(u"Payment verified"), status_code=201) + doc=_("Payment verified"), status_code=201) else: online_payment.fail() db.session.add(online_payment) db.session.commit() raise PaymentGatewayError( - u"Online payment failed for order - {order} with the following details - {msg}".format( + "Online payment failed for order - {order} with the following details - {msg}".format( order=order.id, msg=rp_resp.content), 424, - u"Your payment failed. Please try again or contact us at {email}.".format( + "Your payment failed. Please try again or contact us at {email}.".format( email=order.organization.contact_email)) @@ -346,22 +346,22 @@ def edit_invoice_details(order): abort(404) invoice_dict = request.json.get('invoice') if not request.json or not invoice_dict: - return api_error(message=_(u"Missing invoice details"), status_code=400) + return api_error(message=_("Missing invoice details"), status_code=400) invoice = Invoice.query.get(request.json.get('invoice_id')) if invoice.is_final: - return api_error(message=_(u"This invoice has been finalised and hence cannot be modified"), + return api_error(message=_("This invoice has been finalised and hence cannot be modified"), status_code=400) invoice_form = InvoiceForm.from_json(invoice_dict, meta={'csrf': False}) if not invoice_form.validate(): - return api_error(message=_(u"Incorrect invoice details"), + return api_error(message=_("Incorrect invoice details"), status_code=400, errors=invoice_form.errors) else: invoice_form.populate_obj(invoice) db.session.commit() return api_success(result={'message': 'Invoice updated', 'invoice': jsonify_invoice(invoice)}, - doc=_(u"Invoice details added"), status_code=201) + doc=_("Invoice details added"), status_code=201) def jsonify_invoices(data_dict): @@ -424,7 +424,7 @@ def format_assignee(line_item): order_dict['line_items'].append({ 'assignee': format_assignee(line_item), 'line_item_seq': line_item.line_item_seq, - 'line_item_status': u"confirmed" if line_item.is_confirmed else u"cancelled", + 'line_item_status': "confirmed" if line_item.is_confirmed else "cancelled", 'item': { 'title': line_item.item.title } @@ -523,14 +523,14 @@ def process_line_item_cancellation(line_item): if rp_resp.status_code == 200: db.session.add(PaymentTransaction(order=order, transaction_type=TRANSACTION_TYPE.REFUND, pg_refundid=rp_refund['id'], online_payment=payment, amount=refund_amount, currency=CURRENCY.INR, refunded_at=func.utcnow(), - refund_description=u"Refund: {line_item_title}".format(line_item_title=line_item.item.title))) + refund_description="Refund: {line_item_title}".format(line_item_title=line_item.item.title))) else: raise PaymentGatewayError( - u"Cancellation failed for order - {order} with the following details - {msg}".format( + "Cancellation failed for order - {order} with the following details - {msg}".format( order=order.id, msg=rp_refund['error']['description']), 424, - u"Refund failed. {reason}. Please try again or write to us at {email}.".format( + "Refund failed. {reason}. Please try again or write to us at {email}.".format( reason=rp_refund['error']['description'], email=line_item.order.organization.contact_email)) else: @@ -555,7 +555,7 @@ def cancel_line_item(line_item): refund_amount = process_line_item_cancellation(line_item) send_line_item_cancellation_mail.queue(line_item.id, refund_amount) return api_success(result={'cancelled_at': json_date_format(line_item.cancelled_at)}, - doc=_(u"Ticket cancelled"), status_code=200) + doc=_("Ticket cancelled"), status_code=200) def process_partial_refund_for_order(data_dict): @@ -564,7 +564,7 @@ def process_partial_refund_for_order(data_dict): request_method = data_dict['request_method'] if request_method == 'GET': - return jsonify(form_template=render_form(form=form, title=u"Partial refund", submit=u"Refund", with_chrome=False)) + return jsonify(form_template=render_form(form=form, title="Partial refund", submit="Refund", with_chrome=False)) if form.validate_on_submit(): requested_refund_amount = form.amount.data payment = OnlinePayment.query.filter_by(order=order, pg_payment_status=RAZORPAY_PAYMENT_STATUS.CAPTURED).one() @@ -579,14 +579,14 @@ def process_partial_refund_for_order(data_dict): db.session.commit() send_order_refund_mail.queue(order.id, transaction.amount, transaction.note_to_user) return api_success(result={'order_net_amount': order.net_amount}, - doc=_(u"Refund processed for order"), status_code=200) + doc=_("Refund processed for order"), status_code=200) else: raise PaymentGatewayError( - u"Refund failed for order - {order} with the following details - {msg}".format( + "Refund failed for order - {order} with the following details - {msg}".format( order=order.id, msg=rp_refund['error']['description']), 424, - u"Refund failed. {reason}. Please try again or contact support at {email}.".format( + "Refund failed. {reason}. Please try again or contact support at {email}.".format( reason=rp_refund['error']['description'], email=order.organization.contact_email)) else: diff --git a/boxoffice/views/participant.py b/boxoffice/views/participant.py index 2d59edfd..3807dd9f 100644 --- a/boxoffice/views/participant.py +++ b/boxoffice/views/participant.py @@ -6,7 +6,7 @@ send_ticket_assignment_mail, send_ticket_reassignment_mail, ) -from utils import xhr_only +from .utils import xhr_only from baseframe import _ from coaster.views import load_models, render_with @@ -30,7 +30,7 @@ def assign(order): { 'status': 'error', 'error': 'missing_line_item', - 'error_description': u"Invalid line item", + 'error_description': "Invalid line item", }, 404, ) @@ -39,7 +39,7 @@ def assign(order): { 'status': 'error', 'error': 'cancelled_ticket', - 'error_description': u"Ticket has been cancelled", + 'error_description': "Ticket has been cancelled", }, 400, ) @@ -110,7 +110,7 @@ def assign(order): { 'status': 'error', 'error': 'invalid_assignee_details', - 'error_description': u"Invalid form values. Please resubmit.", + 'error_description': "Invalid form values. Please resubmit.", 'error_details': assignee_form.errors, }, 400, diff --git a/boxoffice/views/utils.py b/boxoffice/views/utils.py index 00bc0468..44ca8a37 100644 --- a/boxoffice/views/utils.py +++ b/boxoffice/views/utils.py @@ -1,22 +1,22 @@ # -*- coding: utf-8 -*- -from flask import request, abort, Response, jsonify, make_response +import csv from functools import wraps -from urlparse import urlparse -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO -import unicodecsv +from io import StringIO +from urllib.parse import urlparse + +from flask import Response, abort, jsonify, make_response, request + from baseframe import localize_timezone from boxoffice import app + def sanitize_coupons(coupons): if not isinstance(coupons, list): return [] # Remove falsy values and coerce the valid values into unicode - return [unicode(coupon_code) for coupon_code in coupons if coupon_code] + return [str(coupon_code) for coupon_code in coupons if coupon_code] def xhr_only(f): @@ -57,7 +57,7 @@ def basepath(url): parsed_url = urlparse(url) if not (parsed_url.scheme or parsed_url.netloc): raise ValueError("Invalid URL") - return u"{scheme}://{netloc}".format(scheme=parsed_url.scheme, netloc=parsed_url.netloc) + return "{scheme}://{netloc}".format(scheme=parsed_url.scheme, netloc=parsed_url.netloc) def cors(f): @@ -111,16 +111,16 @@ def csv_response(headers, rows, row_type=None, row_handler=None): """ stream = StringIO() if row_type == 'dict': - csv_writer = unicodecsv.DictWriter(stream, fieldnames=headers, extrasaction='ignore') + csv_writer = csv.DictWriter(stream, fieldnames=headers, extrasaction='ignore', quoting=csv.QUOTE_MINIMAL) csv_writer.writeheader() else: - csv_writer = unicodecsv.writer(stream) + csv_writer = csv.writer(stream, quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(headers) if callable(row_handler): csv_writer.writerows(row_handler(row) for row in rows) else: csv_writer.writerows(rows) - return Response(unicode(stream.getvalue().decode('utf-8')), mimetype='text/csv') + return Response(stream.getvalue(), mimetype='text/csv') def api_error(message, status_code, errors=[]): diff --git a/manage.py b/manage.py index 3648ea54..fe4fa8ad 100755 --- a/manage.py +++ b/manage.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from __future__ import print_function + from coaster.manage import manager, init_manager import boxoffice diff --git a/migrations/env.py b/migrations/env.py index 46a8e201..e936a859 100755 --- a/migrations/env.py +++ b/migrations/env.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig diff --git a/migrations/versions/1a22f5035244_create_invoice.py b/migrations/versions/1a22f5035244_create_invoice.py index 551faf39..05209d1b 100644 --- a/migrations/versions/1a22f5035244_create_invoice.py +++ b/migrations/versions/1a22f5035244_create_invoice.py @@ -43,10 +43,10 @@ def upgrade(): sa.UniqueConstraint('organization_id', 'invoice_no') ) op.create_index(op.f('ix_invoice_customer_order_id'), 'invoice', ['customer_order_id'], unique=False) - op.add_column(u'item_collection', sa.Column('tax_type', sa.Unicode(length=80), nullable=True)) + op.add_column('item_collection', sa.Column('tax_type', sa.Unicode(length=80), nullable=True)) def downgrade(): - op.drop_column(u'item_collection', 'tax_type') + op.drop_column('item_collection', 'tax_type') op.drop_index(op.f('ix_invoice_customer_order_id'), table_name='invoice') op.drop_table('invoice') diff --git a/migrations/versions/1ea1e8070ac8_add_assignee.py b/migrations/versions/1ea1e8070ac8_add_assignee.py index bcf7216f..d9059389 100644 --- a/migrations/versions/1ea1e8070ac8_add_assignee.py +++ b/migrations/versions/1ea1e8070ac8_add_assignee.py @@ -30,8 +30,8 @@ def upgrade(): sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id'), ) - op.add_column(u'line_item', sa.Column('assignee_id', sa.Integer(), nullable=True)) - op.add_column(u'item', sa.Column('assignee_details', JsonDict(), server_default='{}', nullable=True)) + op.add_column('line_item', sa.Column('assignee_id', sa.Integer(), nullable=True)) + op.add_column('item', sa.Column('assignee_details', JsonDict(), server_default='{}', nullable=True)) op.alter_column('item', 'assignee_details', server_default=None) op.create_foreign_key('line_item_assignee_id_fkey', 'line_item', 'assignee', ['assignee_id'], ['id']) op.create_index(op.f('assignee_email_key'), 'assignee', ['email'], unique=True) @@ -40,6 +40,6 @@ def upgrade(): def downgrade(): op.drop_index(op.f('assignee_email_key'), table_name='assignee') op.drop_constraint('line_item_assignee_id_fkey', 'line_item', type_='foreignkey') - op.drop_column(u'item', 'assignee_details') - op.drop_column(u'line_item', 'assignee_id') + op.drop_column('item', 'assignee_details') + op.drop_column('line_item', 'assignee_id') op.drop_table('assignee') diff --git a/migrations/versions/253e7b76eb8e_modify_assignee.py b/migrations/versions/253e7b76eb8e_modify_assignee.py index 6da2434c..e6170f5e 100644 --- a/migrations/versions/253e7b76eb8e_modify_assignee.py +++ b/migrations/versions/253e7b76eb8e_modify_assignee.py @@ -17,23 +17,23 @@ def upgrade(): op.add_column('assignee', sa.Column('current', sa.Boolean(), nullable=True)) - op.create_check_constraint('assignee_current_check', 'assignee', u"current != '0'") + op.create_check_constraint('assignee_current_check', 'assignee', "current != '0'") op.add_column('assignee', sa.Column('line_item_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False)) op.drop_index('assignee_email_key', table_name='assignee') op.create_unique_constraint('assignee_line_item_current_key', 'assignee', ['line_item_id', 'current']) - op.drop_constraint(u'assignee_previous_id_fkey', 'assignee', type_='foreignkey') + op.drop_constraint('assignee_previous_id_fkey', 'assignee', type_='foreignkey') op.create_foreign_key('assignee_line_item_id', 'assignee', 'line_item', ['line_item_id'], ['id']) op.drop_column('assignee', 'previous_id') - op.drop_constraint(u'line_item_assignee_id_fkey', 'line_item', type_='foreignkey') + op.drop_constraint('line_item_assignee_id_fkey', 'line_item', type_='foreignkey') op.drop_column('line_item', 'assignee_id') def downgrade(): op.add_column('line_item', sa.Column('assignee_id', sa.INTEGER(), autoincrement=False, nullable=True)) - op.create_foreign_key(u'line_item_assignee_id_fkey', 'line_item', 'assignee', ['assignee_id'], ['id']) + op.create_foreign_key('line_item_assignee_id_fkey', 'line_item', 'assignee', ['assignee_id'], ['id']) op.add_column('assignee', sa.Column('previous_id', sa.INTEGER(), autoincrement=False, nullable=True)) op.drop_constraint('assignee_line_item_id', 'assignee', type_='foreignkey') - op.create_foreign_key(u'assignee_previous_id_fkey', 'assignee', 'assignee', ['previous_id'], ['id']) + op.create_foreign_key('assignee_previous_id_fkey', 'assignee', 'assignee', ['previous_id'], ['id']) op.drop_constraint('assignee_line_item_current_key', 'assignee', type_='unique') op.create_index('assignee_email_key', 'assignee', ['email'], unique=False) op.drop_column('assignee', 'line_item_id') diff --git a/migrations/versions/32abb3608d9a_simplify_discounts.py b/migrations/versions/32abb3608d9a_simplify_discounts.py index ad000849..d72bfa8d 100644 --- a/migrations/versions/32abb3608d9a_simplify_discounts.py +++ b/migrations/versions/32abb3608d9a_simplify_discounts.py @@ -53,5 +53,5 @@ def downgrade(): existing_type=sa.INTEGER(), nullable=False) op.drop_column('discount_coupon', 'used') - op.create_check_constraint('discount_coupon_quantity_check', 'discount_coupon', u'quantity_available <= quantity_total') - op.create_check_constraint('discount_policy_item_quantity_check', 'discount_policy', u'item_quantity_min <= item_quantity_max') + op.create_check_constraint('discount_coupon_quantity_check', 'discount_coupon', 'quantity_available <= quantity_total') + op.create_check_constraint('discount_policy_item_quantity_check', 'discount_policy', 'item_quantity_min <= item_quantity_max') diff --git a/migrations/versions/36f458047cfd_update_index_on_discount_title.py b/migrations/versions/36f458047cfd_update_index_on_discount_title.py index b996586b..f9152294 100644 --- a/migrations/versions/36f458047cfd_update_index_on_discount_title.py +++ b/migrations/versions/36f458047cfd_update_index_on_discount_title.py @@ -15,10 +15,10 @@ def upgrade(): - op.drop_constraint(u'discount_policy_discount_code_base_key', 'discount_policy', type_='unique') - op.create_unique_constraint(u'discount_policy_organization_id_discount_code_base_key', 'discount_policy', ['organization_id', 'discount_code_base']) + op.drop_constraint('discount_policy_discount_code_base_key', 'discount_policy', type_='unique') + op.create_unique_constraint('discount_policy_organization_id_discount_code_base_key', 'discount_policy', ['organization_id', 'discount_code_base']) def downgrade(): op.drop_constraint('discount_policy_organization_id_discount_code_base_key', 'discount_policy', type_='unique') - op.create_unique_constraint(u'discount_policy_discount_code_base_key', 'discount_policy', ['discount_code_base']) + op.create_unique_constraint('discount_policy_discount_code_base_key', 'discount_policy', ['discount_code_base']) diff --git a/migrations/versions/4ffee334e82e_init_models.py b/migrations/versions/4ffee334e82e_init_models.py index 3722856e..28e3c3f9 100644 --- a/migrations/versions/4ffee334e82e_init_models.py +++ b/migrations/versions/4ffee334e82e_init_models.py @@ -61,8 +61,8 @@ def upgrade(): sa.Column('name', sa.Unicode(length=250), nullable=False), sa.Column('title', sa.Unicode(length=250), nullable=False), sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), - sa.CheckConstraint(u'item_quantity_min <= item_quantity_max', name='discount_policy_item_quantity_check'), - sa.CheckConstraint(u'percentage > 0 and percentage <= 100', name='discount_policy_percentage_check'), + sa.CheckConstraint('item_quantity_min <= item_quantity_max', name='discount_policy_item_quantity_check'), + sa.CheckConstraint('percentage > 0 and percentage <= 100', name='discount_policy_percentage_check'), sa.ForeignKeyConstraint(['organization_id'], ['organization.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('organization_id', 'name') @@ -123,7 +123,7 @@ def upgrade(): sa.Column('quantity_total', sa.Integer(), nullable=False), sa.Column('used_at', sa.DateTime(), nullable=True), sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), - sa.CheckConstraint(u'quantity_available <= quantity_total', name='discount_coupon_quantity_check'), + sa.CheckConstraint('quantity_available <= quantity_total', name='discount_coupon_quantity_check'), sa.ForeignKeyConstraint(['discount_policy_id'], ['discount_policy.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('discount_policy_id', 'code') @@ -144,7 +144,7 @@ def upgrade(): sa.ForeignKeyConstraint(['item_collection_id'], ['item_collection.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('item_collection_id', 'name'), - sa.CheckConstraint(u'quantity_available <= quantity_total', name='item_quantity_available_lte_quantity_total_check') + sa.CheckConstraint('quantity_available <= quantity_total', name='item_quantity_available_lte_quantity_total_check') ) op.create_table('online_payment', sa.Column('created_at', sa.DateTime(), nullable=False), @@ -216,7 +216,7 @@ def upgrade(): sa.ForeignKeyConstraint(['item_id'], ['item.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('item_id', 'name'), - sa.CheckConstraint(u'start_at < end_at', name='price_start_at_lt_end_at_check') + sa.CheckConstraint('start_at < end_at', name='price_start_at_lt_end_at_check') ) diff --git a/migrations/versions/66b67130c901_retroactively_migrate_previous_id_for_.py b/migrations/versions/66b67130c901_retroactively_migrate_previous_id_for_.py index 6e812f70..478374dd 100644 --- a/migrations/versions/66b67130c901_retroactively_migrate_previous_id_for_.py +++ b/migrations/versions/66b67130c901_retroactively_migrate_previous_id_for_.py @@ -35,7 +35,7 @@ def set_previous_keys_for_line_items(line_items): # Some line items may have been created a few milliseconds later, so the nearest timestamp # with a tolerance level of one second is searched for for line_item in line_items: - ts_key = find_nearest_timestamp(timestamped_line_items.keys(), line_item.created_at) or line_item.created_at + ts_key = find_nearest_timestamp(list(timestamped_line_items.keys()), line_item.created_at) or line_item.created_at if not timestamped_line_items.get(ts_key): timestamped_line_items[ts_key] = [] timestamped_line_items[ts_key].append({ @@ -55,7 +55,7 @@ def set_previous_keys_for_line_items(line_items): # timestamped_line_items.keys()[idx] and not timestamped_line_items.keys()[idx-1] # because the timestamped_line_items.items() list is enumerated from index 1 previous_li_dict = [previous_li_dict - for previous_li_dict in timestamped_line_items[timestamped_line_items.keys()[idx]] + for previous_li_dict in timestamped_line_items[list(timestamped_line_items.keys())[idx]] if previous_li_dict['item_id'] == li_dict['item_id'] and previous_li_dict['id'] not in used_line_item_ids and previous_li_dict['status'] == LINE_ITEM_STATUS.VOID diff --git a/migrations/versions/829f42c03de3_add_fy_to_invoice.py b/migrations/versions/829f42c03de3_add_fy_to_invoice.py index 8923a3fd..3eb13067 100644 --- a/migrations/versions/829f42c03de3_add_fy_to_invoice.py +++ b/migrations/versions/829f42c03de3_add_fy_to_invoice.py @@ -29,12 +29,12 @@ def upgrade(): conn = op.get_bind() op.add_column('invoice', sa.Column('fy_end_at', sa.DateTime(), nullable=True)) op.add_column('invoice', sa.Column('fy_start_at', sa.DateTime(), nullable=True)) - op.drop_constraint(u'invoice_organization_id_invoice_no_key', 'invoice', type_='unique') + op.drop_constraint('invoice_organization_id_invoice_no_key', 'invoice', type_='unique') op.create_unique_constraint('invoice_organization_id_fy_start_at_fy_end_at_invoice_no_key', 'invoice', ['organization_id', 'fy_start_at', 'fy_end_at', 'invoice_no']) invoices = conn.execute(sa.select([invoice_table.c.id, invoice_table.c.invoiced_at]).select_from(invoice_table)) for invoice in invoices: - fy_start_at, fy_end_at = get_fiscal_year(u'in', invoice.invoiced_at) + fy_start_at, fy_end_at = get_fiscal_year('in', invoice.invoiced_at) conn.execute(sa.update(invoice_table).where( invoice_table.c.id == invoice.id ).values(fy_start_at=fy_start_at, fy_end_at=fy_end_at)) @@ -60,6 +60,6 @@ def downgrade(): invoice_table.c.id == invoice.id ).values(fy_start_at=None, fy_end_at=None)) op.drop_constraint('invoice_organization_id_fy_start_at_fy_end_at_invoice_no_key', 'invoice', type_='unique') - op.create_unique_constraint(u'invoice_organization_id_invoice_no_key', 'invoice', ['organization_id', 'invoice_no']) + op.create_unique_constraint('invoice_organization_id_invoice_no_key', 'invoice', ['organization_id', 'invoice_no']) op.drop_column('invoice', 'fy_start_at') op.drop_column('invoice', 'fy_end_at') diff --git a/migrations/versions/dadc5748932_rm_quantity_available.py b/migrations/versions/dadc5748932_rm_quantity_available.py index 6ecd2428..0e5b4879 100644 --- a/migrations/versions/dadc5748932_rm_quantity_available.py +++ b/migrations/versions/dadc5748932_rm_quantity_available.py @@ -26,7 +26,7 @@ def upgrade(): - op.drop_constraint(u'item_quantity_available_lte_quantity_total_check', 'item') + op.drop_constraint('item_quantity_available_lte_quantity_total_check', 'item') op.drop_column('item', 'quantity_available') @@ -34,4 +34,4 @@ def downgrade(): op.add_column('item', sa.Column('quantity_available', sa.INTEGER(), autoincrement=False, nullable=True)) op.execute(item.update().values({'quantity_available': item.c.quantity_total - line_item.count().where(line_item.c.item_id == item.c.id).where(line_item.c.status == 0)})) op.alter_column('item', 'quantity_available', nullable=False) - op.create_check_constraint('item_quantity_available_lte_quantity_total_check', 'item', u"quantity_available <= quantity_total") + op.create_check_constraint('item_quantity_available_lte_quantity_total_check', 'item', "quantity_available <= quantity_total") diff --git a/rqinit.py b/rqinit.py index 024a9656..5255d6c8 100644 --- a/rqinit.py +++ b/rqinit.py @@ -1,4 +1,4 @@ -from urlparse import urlparse +from urllib.parse import urlparse from boxoffice import app diff --git a/scripts/razorpay_settlement.py b/scripts/razorpay_settlement.py index 5004871f..7b0f79f7 100644 --- a/scripts/razorpay_settlement.py +++ b/scripts/razorpay_settlement.py @@ -106,7 +106,7 @@ def get_settled_orders(date_ranges=[], filenames=[]): # settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, line_item, 'refund'))) except Exception as error_msg: - print error_msg + print(error_msg) pass settlement_refund_ids = [entity['entity_id'] for entity in entity_dict.values() if entity['type'] == 'refund' and entity['settlement_id'] == settlement_id] @@ -131,8 +131,8 @@ def get_settled_orders(date_ranges=[], filenames=[]): if cancelled_line_item: settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, cancelled_line_item, 'refund'))) else: - print "no line item found" - print payment.pg_paymentid + print("no line item found") + print(payment.pg_paymentid) return settled_orders @@ -199,7 +199,7 @@ def get_settled_order_transactions(date_ranges=[], filenames=[]): # settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, line_item, 'refund'))) except Exception as error_msg: - print error_msg + print(error_msg) pass settlement_refund_ids = [entity['entity_id'] for entity in entity_dict.values() if entity['type'] == 'refund' and entity['settlement_id'] == settlement_id] diff --git a/scripts/razorpay_settlement_old.py b/scripts/razorpay_settlement_old.py index 9497c500..f916bdec 100644 --- a/scripts/razorpay_settlement_old.py +++ b/scripts/razorpay_settlement_old.py @@ -96,7 +96,7 @@ def get_settled_orders(date_ranges=[], filenames=[]): # settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, line_item, 'refund'))) except Exception as error_msg: - print error_msg + print(error_msg) pass settlement_refund_ids = [entity['entity_id'] for entity in entity_dict.values() if entity['type'] == 'refund' and entity['settlement_id'] == settlement_id] @@ -121,8 +121,8 @@ def get_settled_orders(date_ranges=[], filenames=[]): if cancelled_line_item: settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, cancelled_line_item, 'refund'))) else: - print "no line item found" - print payment.pg_paymentid + print("no line item found") + print(payment.pg_paymentid) return settled_orders diff --git a/scripts/settled_order.py b/scripts/settled_order.py index 749cdd4f..fc5c3b53 100644 --- a/scripts/settled_order.py +++ b/scripts/settled_order.py @@ -90,14 +90,14 @@ def format_line_item(settlement_id, payment_id, line_item, payment_status): cancelled_line_item = LineItem.query.filter(LineItem.order == order, LineItem.final_amount == Decimal(entity_dict[settlement_refund_id]['debit']), LineItem.status == LINE_ITEM_STATUS.CANCELLED).first() settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, cancelled_line_item, 'refund'))) except Exception: - print "Multiple line items found" - print payment.pg_paymentid + print("Multiple line items found") + print(payment.pg_paymentid) cancelled_line_item = LineItem.query.filter(LineItem.order == order, LineItem.final_amount == Decimal(entity_dict[settlement_refund_id]['debit']), LineItem.status == LINE_ITEM_STATUS.CANCELLED).first() if cancelled_line_item: settled_orders.append(format_row(format_line_item(settlement_id, settlement_payment_id, cancelled_line_item, 'refund'))) else: - print "no line item found" - print payment.pg_paymentid + print("no line item found") + print(payment.pg_paymentid) return settled_orders diff --git a/scripts/settlement.py b/scripts/settlement.py index 8c52fa6f..c82370d0 100755 --- a/scripts/settlement.py +++ b/scripts/settlement.py @@ -76,9 +76,9 @@ def get_settlements(filename): 'receivable_amount': Decimal(pt.amount) - Decimal(trans[6]), 'type': 'payment' }) - print "settlement not settled yet {settlement}".format(settlement=trans[11]) + print("settlement not settled yet {settlement}".format(settlement=trans[11])) else: - print "payment not found {payment}".format(payment=trans[0]) + print("payment not found {payment}".format(payment=trans[0])) elif trans[1] == 'refund': payment = OnlinePayment.query.filter_by(pg_paymentid=trans[14], pg_payment_status=RAZORPAY_PAYMENT_STATUS.CAPTURED).first() if payment: @@ -113,9 +113,9 @@ def get_settlements(filename): 'receivable_amount': Decimal(0) - Decimal(rt.amount), 'type': 'refund' }) - print "settlement not settled yet {settlement}".format(settlement=trans[11]) + print("settlement not settled yet {settlement}".format(settlement=trans[11])) else: - print "payment not found {payment}".format(payment=trans[0]) + print("payment not found {payment}".format(payment=trans[0])) elif trans[1] == 'adjustment': settlement = [tr for tr in transactions if tr[0] == trans[11]] if settlement: @@ -132,11 +132,11 @@ def get_settlements(filename): 'type': 'adjustment' }) else: - print "settlement not settled yet {settlement}".format(settlement=trans[11]) + print("settlement not settled yet {settlement}".format(settlement=trans[11])) rows = [] header = ['settlement_id', 'settlement_amount', 'settlement_date', 'order_id', 'razorpay_fee', 'razorpay_service_tax', 'order_amount', 'buyer_name', 'transaction_date', 'receivable_amount', 'type'] - for stmt, stm_transactions in settlements.iteritems(): + for stmt, stm_transactions in settlements.items(): for details in stm_transactions: rows.append([stmt, details['settlement_amount'], details['settlement_date'], details['order_id'], details['razorpay_fee'], details['razorpay_service_tax'], details['order_amount'], details['buyer_name'], details['transaction_date'], details['receivable_amount'], details['type']]) @@ -187,7 +187,7 @@ def get_orders(settlement_filename): 'transaction_date': localize(payment_transaction.created_at) }) if Decimal(settlement_dict['credit']) != payment_transaction.amount - Decimal(settlement_dict['fee']): - print "Tally failed for " + settlement_dict['entity_id'] + print("Tally failed for " + settlement_dict['entity_id']) elif settlement_dict['type'] == 'refund' and settlement_dict['entity_id'] not in [pord['entity_id'] for pord in payment_orders]: try: payment = OnlinePayment.query.filter_by(pg_paymentid=settlement_dict['payment_id'], pg_payment_status=RAZORPAY_PAYMENT_STATUS.CAPTURED).one() @@ -207,14 +207,14 @@ def get_orders(settlement_filename): 'transaction_date': localize(payment_transaction.created_at) }) else: - print "no transaction for " + settlement_dict['entity_id'] + print("no transaction for " + settlement_dict['entity_id']) except Exception: - print "no payment found for " + settlement_dict['payment_id'] + "for entity " + settlement_dict['entity_id'] + print("no payment found for " + settlement_dict['payment_id'] + "for entity " + settlement_dict['entity_id']) # check if settlements tally for settlement_dict in [settlement_dict for settlement_dict in settlement_dicts if settlement_dict['type'] == 'settlement']: if Decimal(settlement_dict['amount']) != sum([payment_order['receivable_amount'] for payment_order in payment_orders if payment_order['settlement_id'] == settlement_dict['entity_id']]): - print "Settlement not tallying for " + settlement_dict['entity_id'] + print("Settlement not tallying for " + settlement_dict['entity_id']) # write result to csv with open('settlement_orders.csv', 'w') as outputcsv: diff --git a/scripts/settlement1.py b/scripts/settlement1.py index d764635e..576b1f45 100755 --- a/scripts/settlement1.py +++ b/scripts/settlement1.py @@ -60,7 +60,7 @@ def get_settlements(filename): 'type': 'payment' }) else: - print trans[0] + print(trans[0]) elif trans[1] == 'refund': payment = OnlinePayment.query.filter_by(pg_paymentid=trans[14]).first() if payment: @@ -80,11 +80,11 @@ def get_settlements(filename): 'type': 'refund' }) else: - print trans[0] + print(trans[0]) rows = [] header = ['settlement_id', 'settlement_amount', 'settlement_date', 'order_id', 'razorpay_fee', 'razorpay_service_tax', 'order_amount', 'buyer_name', 'transaction_date', 'receivable_amount', 'type'] - for stmt, stm_transactions in settlements.iteritems(): + for stmt, stm_transactions in settlements.items(): for details in stm_transactions: rows.append([stmt, details['settlement_amount'], details['settlement_date'], details['order_id'], details['razorpay_fee'], details['razorpay_service_tax'], details['order_amount'], details['buyer_name'], details['transaction_date'], details['receivable_amount'], details['type']]) diff --git a/scripts/sync_razorpay_refunds.py b/scripts/sync_razorpay_refunds.py index a26ab67b..0fd994c1 100644 --- a/scripts/sync_razorpay_refunds.py +++ b/scripts/sync_razorpay_refunds.py @@ -45,7 +45,7 @@ def sync_refunds(): correspongding_rp_refund = min(possible_rp_refunds, key=lambda rp_refund: abs(rp_refund['created_at'] - refund_epoch_dt)) if not correspongding_rp_refund or amount_in_paise(refund.amount) != correspongding_rp_refund['amount']: - raise("Oops! No refund found for {refundid}.".format(refundid=refund.id)) + raise "Oops! No refund found for {refundid}." refund.pg_refundid = correspongding_rp_refund['id'] used_pg_refundids.append(correspongding_rp_refund['id']) db.session.commit() diff --git a/tests/__init__.py b/tests/__init__.py index 8a964d1f..f4e811ca 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,2 +1,2 @@ # flake8: noqa -from test_item_collection import * +from .test_item_collection import * diff --git a/tests/fixtures.py b/tests/fixtures.py index 50530fdc..90b5cd88 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -11,110 +11,110 @@ def init_data(): db.drop_all() db.create_all() - user = User(userid=u"U3_JesHfQ2OUmdihAXaAGQ", email=u"test@hasgeek.com") + user = User(userid="U3_JesHfQ2OUmdihAXaAGQ", email="test@hasgeek.com") db.session.add(user) db.session.commit() one_month_from_now = date.today() + relativedelta(months=+1) - rootconf = Organization(title=u'Rootconf', userid=u"U3_JesHfQ2OUmdihAXaAGQ", - status=0, contact_email=u'test@gmail.com', - details={'service_tax_no': 'xx', 'address': u'

XYZ

Bangalore - 560034

India

', 'cin': u'1234', 'pan': u'abc', 'website': u'https://www.test.com', 'refund_policy': u'

We offer full refund.

', 'support_email': 'test@boxoffice.com', 'ticket_faq': '

To cancel your ticket, please mail test@boxoffice.com with your receipt number.

'}) + rootconf = Organization(title='Rootconf', userid="U3_JesHfQ2OUmdihAXaAGQ", + status=0, contact_email='test@gmail.com', + details={'service_tax_no': 'xx', 'address': '

XYZ

Bangalore - 560034

India

', 'cin': '1234', 'pan': 'abc', 'website': 'https://www.test.com', 'refund_policy': '

We offer full refund.

', 'support_email': 'test@boxoffice.com', 'ticket_faq': '

To cancel your ticket, please mail test@boxoffice.com with your receipt number.

'}) db.session.add(rootconf) db.session.commit() - rc2016 = ItemCollection(title=u'2016', organization=rootconf) + rc2016 = ItemCollection(title='2016', organization=rootconf) db.session.add(rc2016) db.session.commit() - category_conference = Category(title=u'Conference', item_collection=rc2016, seq=1) + category_conference = Category(title='Conference', item_collection=rc2016, seq=1) db.session.add(category_conference) - category_workshop = Category(title=u'Workshop', item_collection=rc2016, seq=2) + category_workshop = Category(title='Workshop', item_collection=rc2016, seq=2) db.session.add(category_workshop) - category_merch = Category(title=u'Merchandise', item_collection=rc2016, seq=3) + category_merch = Category(title='Merchandise', item_collection=rc2016, seq=3) db.session.add(category_merch) db.session.commit() # import IPython; IPython.embed() with db.session.no_autoflush: - conf_ticket = Item(title=u'Conference ticket', description=u'

14 - 15 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th and 15th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name=u'conference').first(), quantity_total=1000) + conf_ticket = Item(title='Conference ticket', description='

14 - 15 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th and 15th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name='conference').first(), quantity_total=1000) rc2016.items.append(conf_ticket) db.session.commit() - expired_ticket = Item(title=u'Expired ticket', description=u'

14 - 15 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th and 15th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name=u'conference').first(), quantity_total=1000) + expired_ticket = Item(title='Expired ticket', description='

14 - 15 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th and 15th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name='conference').first(), quantity_total=1000) rc2016.items.append(expired_ticket) db.session.commit() - price = Price(item=conf_ticket, title=u'Super Early Geek', start_at=utcnow(), end_at=one_month_from_now, amount=3500) + price = Price(item=conf_ticket, title='Super Early Geek', start_at=utcnow(), end_at=one_month_from_now, amount=3500) db.session.add(price) db.session.commit() - single_day_conf_ticket = Item(title=u'Single Day', description=u'

14 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name=u'conference').first(), quantity_total=1000) + single_day_conf_ticket = Item(title='Single Day', description='

14 April 2016

MLR Convention Center, JP Nagar

This ticket gets you access to rootconf conference on 14th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name='conference').first(), quantity_total=1000) rc2016.items.append(single_day_conf_ticket) db.session.commit() - single_day_price = Price(item=single_day_conf_ticket, title=u'Single Day', start_at=utcnow(), end_at=one_month_from_now, amount=2500) + single_day_price = Price(item=single_day_conf_ticket, title='Single Day', start_at=utcnow(), end_at=one_month_from_now, amount=2500) db.session.add(single_day_price) db.session.commit() - tshirt = Item(title=u'T-shirt', description=u'Rootconf', item_collection=rc2016, category=Category.query.filter_by(name=u'merchandise').first(), quantity_total=1000) + tshirt = Item(title='T-shirt', description='Rootconf', item_collection=rc2016, category=Category.query.filter_by(name='merchandise').first(), quantity_total=1000) rc2016.items.append(tshirt) db.session.commit() - tshirt_price = Price(item=tshirt, title=u'T-shirt', start_at=utcnow(), end_at=one_month_from_now, amount=500) + tshirt_price = Price(item=tshirt, title='T-shirt', start_at=utcnow(), end_at=one_month_from_now, amount=500) db.session.add(tshirt_price) db.session.commit() - dns_workshop = Item(title=u'DNSSEC workshop', description=u'

12 April 2016

TERI, Domlur

This ticket gets you access to DNSSEC workshop 12th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name=u'workshop').first(), quantity_total=1000) + dns_workshop = Item(title='DNSSEC workshop', description='

12 April 2016

TERI, Domlur

This ticket gets you access to DNSSEC workshop 12th April 2016.

', item_collection=rc2016, category=Category.query.filter_by(name='workshop').first(), quantity_total=1000) rc2016.items.append(dns_workshop) db.session.commit() - dns_workshop_price = Price(item=dns_workshop, title=u'DNSSEC workshop early', start_at=utcnow(), end_at=one_month_from_now, amount=2500) + dns_workshop_price = Price(item=dns_workshop, title='DNSSEC workshop early', start_at=utcnow(), end_at=one_month_from_now, amount=2500) db.session.add(dns_workshop_price) db.session.commit() - policy = DiscountPolicy(title=u'10% discount on rootconf', item_quantity_min=10, percentage=10, organization=rootconf) + policy = DiscountPolicy(title='10% discount on rootconf', item_quantity_min=10, percentage=10, organization=rootconf) policy.items.append(conf_ticket) db.session.add(policy) db.session.commit() - tshirt_policy = DiscountPolicy(title=u'5% discount on 5 t-shirts', item_quantity_min=5, percentage=5, organization=rootconf) + tshirt_policy = DiscountPolicy(title='5% discount on 5 t-shirts', item_quantity_min=5, percentage=5, organization=rootconf) tshirt_policy.items.append(tshirt) db.session.add(tshirt_policy) db.session.commit() - discount_coupon1 = DiscountPolicy(title=u'15% discount for coupon code with STU', item_quantity_min=1, percentage=15, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) + discount_coupon1 = DiscountPolicy(title='15% discount for coupon code with STU', item_quantity_min=1, percentage=15, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) discount_coupon1.items.append(conf_ticket) db.session.add(discount_coupon1) db.session.commit() - coupon1 = DiscountCoupon(code=u'coupon1', discount_policy=discount_coupon1) + coupon1 = DiscountCoupon(code='coupon1', discount_policy=discount_coupon1) db.session.add(coupon1) db.session.commit() - discount_coupon_expired_ticket = DiscountPolicy(title=u'15% discount for expired ticket', item_quantity_min=1, percentage=15, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) + discount_coupon_expired_ticket = DiscountPolicy(title='15% discount for expired ticket', item_quantity_min=1, percentage=15, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) discount_coupon_expired_ticket.items.append(expired_ticket) db.session.add(discount_coupon_expired_ticket) db.session.commit() - discount_coupon_expired_ticket_coupon = DiscountCoupon(code=u'couponex', discount_policy=discount_coupon_expired_ticket) + discount_coupon_expired_ticket_coupon = DiscountCoupon(code='couponex', discount_policy=discount_coupon_expired_ticket) db.session.add(discount_coupon_expired_ticket_coupon) db.session.commit() - discount_coupon2 = DiscountPolicy(title=u'100% discount', item_quantity_min=1, percentage=100, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) + discount_coupon2 = DiscountPolicy(title='100% discount', item_quantity_min=1, percentage=100, organization=rootconf, discount_type=DISCOUNT_TYPE.COUPON) discount_coupon2.items.append(conf_ticket) db.session.add(discount_coupon1) db.session.commit() - coupon2 = DiscountCoupon(code=u'coupon2', discount_policy=discount_coupon2) + coupon2 = DiscountCoupon(code='coupon2', discount_policy=discount_coupon2) db.session.add(coupon2) db.session.commit() - coupon3 = DiscountCoupon(code=u'coupon3', discount_policy=discount_coupon2) + coupon3 = DiscountCoupon(code='coupon3', discount_policy=discount_coupon2) db.session.add(coupon3) db.session.commit() - forever_early_geek = DiscountPolicy(title=u'Forever Early Geek', + forever_early_geek = DiscountPolicy(title='Forever Early Geek', item_quantity_min=1, is_price_based=True, discount_type=DISCOUNT_TYPE.COUPON, @@ -123,11 +123,11 @@ def init_data(): db.session.add(forever_early_geek) db.session.commit() - forever_coupon = DiscountCoupon(code=u'forever', discount_policy=forever_early_geek) + forever_coupon = DiscountCoupon(code='forever', discount_policy=forever_early_geek) db.session.add(forever_coupon) db.session.commit() - noprice_discount = DiscountPolicy(title=u'noprice', + noprice_discount = DiscountPolicy(title='noprice', item_quantity_min=1, is_price_based=True, discount_type=DISCOUNT_TYPE.COUPON, @@ -136,22 +136,22 @@ def init_data(): db.session.add(noprice_discount) db.session.commit() - noprice_coupon = DiscountCoupon(code=u'noprice', discount_policy=noprice_discount) + noprice_coupon = DiscountCoupon(code='noprice', discount_policy=noprice_discount) db.session.add(noprice_coupon) db.session.commit() - forever_unlimited_coupon = DiscountCoupon(code=u'unlimited', discount_policy=forever_early_geek, + forever_unlimited_coupon = DiscountCoupon(code='unlimited', discount_policy=forever_early_geek, usage_limit=500) db.session.add(forever_unlimited_coupon) db.session.commit() discount_price = Price(item=conf_ticket, - discount_policy=forever_early_geek, title=u'Forever Early Geek', + discount_policy=forever_early_geek, title='Forever Early Geek', start_at=utcnow(), end_at=one_month_from_now, amount=3400) db.session.add(discount_price) db.session.commit() - unlimited_geek = DiscountPolicy(title=u'Unlimited Geek', + unlimited_geek = DiscountPolicy(title='Unlimited Geek', item_quantity_min=1, discount_type=DISCOUNT_TYPE.COUPON, percentage=10, @@ -160,12 +160,12 @@ def init_data(): db.session.add(unlimited_geek) db.session.commit() - unlimited_coupon = DiscountCoupon(code=u'unlimited', discount_policy=unlimited_geek, + unlimited_coupon = DiscountCoupon(code='unlimited', discount_policy=unlimited_geek, usage_limit=500) db.session.add(unlimited_coupon) db.session.commit() - zero_discount = DiscountPolicy(title=u'Zero Discount', + zero_discount = DiscountPolicy(title='Zero Discount', item_quantity_min=1, is_price_based=True, discount_type=DISCOUNT_TYPE.COUPON, @@ -174,17 +174,17 @@ def init_data(): db.session.add(zero_discount) db.session.commit() - zero_coupon = DiscountCoupon(code=u'zerodi', discount_policy=zero_discount) + zero_coupon = DiscountCoupon(code='zerodi', discount_policy=zero_discount) db.session.add(zero_coupon) db.session.commit() zero_discount_price = Price(item=conf_ticket, - discount_policy=zero_discount, title=u'Zero Discount', + discount_policy=zero_discount, title='Zero Discount', start_at=utcnow(), end_at=one_month_from_now, amount=3600) db.session.add(zero_discount_price) db.session.commit() - bulk = DiscountPolicy.make_bulk(u'signed', organization=rootconf, title=u'Signed', percentage=10, bulk_coupon_usage_limit=2) + bulk = DiscountPolicy.make_bulk('signed', organization=rootconf, title='Signed', percentage=10, bulk_coupon_usage_limit=2) bulk.items.append(conf_ticket) db.session.add(bulk) db.session.commit() diff --git a/tests/integration/test_items.py b/tests/integration/test_items.py index 00e7c5a0..cd39e946 100644 --- a/tests/integration/test_items.py +++ b/tests/integration/test_items.py @@ -33,10 +33,10 @@ def ajax_post(self, url, data): ) def test_assign(self): - item = Item.query.filter_by(name=u"conference-ticket").first() + item = Item.query.filter_by(name="conference-ticket").first() data = { - 'line_items': [{'item_id': unicode(item.id), 'quantity': 2}], + 'line_items': [{'item_id': str(item.id), 'quantity': 2}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -46,10 +46,10 @@ def test_assign(self): ic = ItemCollection.query.first() resp = self.ajax_post('/ic/{ic}/order'.format(ic=ic.id), data) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] order = Order.query.get(resp_data.get('order_id')) - self.assertEquals(order.status, ORDER_STATUS.PURCHASE_ORDER) + self.assertEqual(order.status, ORDER_STATUS.PURCHASE_ORDER) self.assertEqual(len(order.line_items), 2) li_one = order.line_items[0] diff --git a/tests/test_item_collection.py b/tests/test_item_collection.py index a83f7be3..e52581a7 100644 --- a/tests/test_item_collection.py +++ b/tests/test_item_collection.py @@ -4,7 +4,7 @@ import json from boxoffice import app from boxoffice.models import (db, ItemCollection) -from fixtures import init_data +from .fixtures import init_data class TestItemCollectionAPI(unittest.TestCase): @@ -57,26 +57,26 @@ def setUp(self): self.resp = self.client.get('/ic/{ic}'.format(ic=ic.id), headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) def test_status(self): - self.assertEquals(self.resp.status_code, 200) + self.assertEqual(self.resp.status_code, 200) def test_root_keys(self): data = json.loads(self.resp.data) - self.assertEquals(sorted(data.keys()), sorted(self.expected_keys)) + self.assertEqual(sorted(data.keys()), sorted(self.expected_keys)) def test_category_keys(self): data = json.loads(self.resp.data) - self.assertEquals(sorted([cat['name'] for cat in data['categories']]), sorted(self.expected_categories_names)) + self.assertEqual(sorted([cat['name'] for cat in data['categories']]), sorted(self.expected_categories_names)) for category in data['categories']: expected_items = self.expected_data[category['name']] - self.assertEquals(sorted([c['name'] for c in category['items']]), sorted(expected_items.keys())) + self.assertEqual(sorted([c['name'] for c in category['items']]), sorted(expected_items.keys())) for item in category['items']: expected_item_data = expected_items[item['name']] - self.assertEquals(item['title'], expected_item_data['title']) - self.assertEquals(item['price'], expected_item_data['price']) - self.assertEquals(item['description'], expected_item_data['description']) - self.assertEquals(item['quantity_total'], expected_item_data['quantity_total']) + self.assertEqual(item['title'], expected_item_data['title']) + self.assertEqual(item['price'], expected_item_data['price']) + self.assertEqual(item['description'], expected_item_data['description']) + self.assertEqual(item['quantity_total'], expected_item_data['quantity_total']) def tearDown(self): db.session.rollback() diff --git a/tests/test_kharcha.py b/tests/test_kharcha.py index 9c516e1f..0a600e06 100644 --- a/tests/test_kharcha.py +++ b/tests/test_kharcha.py @@ -7,7 +7,7 @@ from coaster.utils import make_name from boxoffice import app from boxoffice.models import (db) -from fixtures import init_data +from .fixtures import init_data from boxoffice.models import Item, DiscountPolicy, DiscountCoupon @@ -22,59 +22,59 @@ def setUp(self): def test_undiscounted_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() undiscounted_quantity = 2 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': undiscounted_quantity}]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': undiscounted_quantity}]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) # Test that the price is correct - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), undiscounted_quantity * first_item.current_price().amount) - policy_ids = [policy for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), undiscounted_quantity * first_item.current_price().amount) + policy_ids = [policy for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), undiscounted_quantity * first_item.current_price().amount) expected_discount_policy_ids = [] - self.assertEquals(expected_discount_policy_ids, policy_ids) + self.assertEqual(expected_discount_policy_ids, policy_ids) def test_expired_item_kharcha(self): expired_ticket = Item.query.filter_by(name='expired-ticket').first() quantity = 2 - kharcha_req = {'line_items': [{'item_id': unicode(expired_ticket.id), 'quantity': quantity}]} + kharcha_req = {'line_items': [{'item_id': str(expired_ticket.id), 'quantity': quantity}]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) # Test that the price is None - self.assertEquals(resp_json.get('line_items')[unicode(expired_ticket.id)].get('base_amount'), None) + self.assertEqual(resp_json.get('line_items')[str(expired_ticket.id)].get('base_amount'), None) def test_expired_discounted_item_kharcha(self): expired_ticket = Item.query.filter_by(name='expired-ticket').first() quantity = 2 coupon = DiscountCoupon.query.filter_by(code='couponex').first() # import IPython; IPython.embed() - kharcha_req = {'line_items': [{'item_id': unicode(expired_ticket.id), 'quantity': quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(expired_ticket.id), 'quantity': quantity}], 'discount_coupons': [coupon.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) # Test that the price is None - self.assertEquals(resp_json.get('line_items')[unicode(expired_ticket.id)].get('base_amount'), None) + self.assertEqual(resp_json.get('line_items')[str(expired_ticket.id)].get('base_amount'), None) def test_discounted_bulk_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() discounted_quantity = 10 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) base_amount = discounted_quantity * first_item.current_price().amount discounted_amount = (first_item.discount_policies[0].percentage * base_amount) / decimal.Decimal(100.0) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - expected_discount_policy_ids = [unicode(DiscountPolicy.query.filter_by(title='10% discount on rootconf').first().id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(DiscountPolicy.query.filter_by(title='10% discount on rootconf').first().id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -84,18 +84,18 @@ def test_discounted_coupon_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() coupon = DiscountCoupon.query.filter_by(code='coupon1').first() discounted_quantity = 1 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) base_amount = discounted_quantity * first_item.current_price().amount discounted_amount = (coupon.discount_policy.percentage * base_amount) / decimal.Decimal(100.0) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - expected_discount_policy_ids = [unicode(coupon.discount_policy_id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(coupon.discount_policy_id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -106,18 +106,18 @@ def test_signed_discounted_coupon_kharcha(self): signed_policy = DiscountPolicy.query.filter_by(name='signed').first() code = signed_policy.gen_signed_code() discounted_quantity = 2 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) base_amount = discounted_quantity * first_item.current_price().amount discounted_amount = (signed_policy.percentage * base_amount) / decimal.Decimal(100.0) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - expected_discount_policy_ids = [unicode(signed_policy.id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(signed_policy.id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -128,42 +128,42 @@ def test_unlimited_coupon_kharcha(self): coupon_code = 'unlimited' discounted_quantity = 5 kharcha_req = {'line_items': [{ - 'item_id': unicode(first_item.id), + 'item_id': str(first_item.id), 'quantity': discounted_quantity }], 'discount_coupons': [coupon_code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) resp_json = json.loads(resp.get_data()) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) base_amount = discounted_quantity * first_item.current_price().amount discount_policy = DiscountPolicy.query.filter_by(name=make_name('Unlimited Geek')).one() discounted_amount = discounted_quantity * ((discount_policy.percentage / decimal.Decimal('100')) * first_item.current_price().amount) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] expected_discount_policy_ids = [discount_policy.id] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: - self.assertIn(unicode(expected_policy_id), [policy for policy in policy_ids]) + self.assertIn(str(expected_policy_id), [policy for policy in policy_ids]) def test_coupon_limit(self): first_item = Item.query.filter_by(name='conference-ticket').first() coupon = DiscountCoupon.query.filter_by(code='coupon1').first() discounted_quantity = 2 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) base_amount = discounted_quantity * first_item.current_price().amount discounted_amount = (coupon.discount_policy.percentage * first_item.current_price().amount) / decimal.Decimal(100.0) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - expected_discount_policy_ids = [unicode(coupon.discount_policy_id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(coupon.discount_policy_id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -173,16 +173,16 @@ def test_discounted_price_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() coupon = DiscountCoupon.query.filter_by(code='forever').first() discounted_quantity = 1 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) - discounted_price = [price for price in first_item.prices if price.name == u'forever-early-geek'][0] - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + discounted_price = [price for price in first_item.prices if price.name == 'forever-early-geek'][0] + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), int(discounted_price.amount)) - expected_discount_policy_ids = [unicode(coupon.discount_policy_id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(coupon.discount_policy_id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -192,28 +192,28 @@ def test_discount_policy_without_price_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() coupon = DiscountCoupon.query.filter_by(code='noprice').first() discounted_quantity = 1 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} # print first_item.discount_policies.all() resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) # print resp.status_code - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('discounted_amount'), decimal.Decimal(0)) + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('discounted_amount'), decimal.Decimal(0)) def test_zero_discounted_price_kharcha(self): first_item = Item.query.filter_by(name='conference-ticket').first() coupon = DiscountCoupon.query.filter_by(code='zerodi').first() discounted_quantity = 1 - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) - discounted_price = [price for price in first_item.prices if price.name == u'zero-discount'][0] - self.assertNotEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + discounted_price = [price for price in first_item.prices if price.name == 'zero-discount'][0] + self.assertNotEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), int(discounted_price.amount)) - expected_discount_policy_ids = [unicode(coupon.discount_policy_id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(coupon.discount_policy_id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: @@ -224,20 +224,20 @@ def test_discounted_complex_kharcha(self): discounted_quantity = 9 coupon2 = DiscountCoupon.query.filter_by(code='coupon2').first() coupon3 = DiscountCoupon.query.filter_by(code='coupon3').first() - kharcha_req = {'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon2.code, coupon3.code]} + kharcha_req = {'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [coupon2.code, coupon3.code]} resp = self.client.post(url_for('kharcha'), data=json.dumps(kharcha_req), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) resp_json = json.loads(resp.get_data()) base_amount = discounted_quantity * first_item.current_price().amount discounted_amount = 2 * first_item.current_price().amount - self.assertEquals(resp_json.get('line_items')[unicode(first_item.id)].get('final_amount'), + self.assertEqual(resp_json.get('line_items')[str(first_item.id)].get('final_amount'), base_amount - discounted_amount) - expected_discount_policy_ids = [unicode(coupon2.discount_policy_id), unicode(coupon3.discount_policy_id)] - policy_ids = [unicode(policy) for policy in resp_json.get('line_items')[unicode(first_item.id)].get('discount_policy_ids')] + expected_discount_policy_ids = [str(coupon2.discount_policy_id), str(coupon3.discount_policy_id)] + policy_ids = [str(policy) for policy in resp_json.get('line_items')[str(first_item.id)].get('discount_policy_ids')] # Test that all the discount policies are returned for expected_policy_id in expected_discount_policy_ids: self.assertIn(expected_policy_id, [policy for policy in policy_ids]) diff --git a/tests/test_order.py b/tests/test_order.py index 09777425..ad903509 100644 --- a/tests/test_order.py +++ b/tests/test_order.py @@ -14,7 +14,7 @@ from boxoffice.forms import OrderRefundForm from boxoffice.extapi import razorpay from boxoffice.views.order import process_line_item_cancellation, process_partial_refund_for_order -from fixtures import init_data +from .fixtures import init_data import datetime @@ -40,7 +40,7 @@ def setUp(self): def test_basic(self): item = Item.query.filter_by(name='conference-ticket').first() data = { - 'line_items': [{'item_id': unicode(item.id), 'quantity': 2}], + 'line_items': [{'item_id': str(item.id), 'quantity': 2}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -49,12 +49,12 @@ def test_basic(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] order = Order.query.get(resp_data.get('order_id')) - self.assertEquals(order.status, ORDER_STATUS.PURCHASE_ORDER) + self.assertEqual(order.status, ORDER_STATUS.PURCHASE_ORDER) # 3500*2 = 7000 - self.assertEquals(resp_data['final_amount'], 7000) + self.assertEqual(resp_data['final_amount'], 7000) def test_basic_with_utm_headers(self): item = Item.query.filter_by(name='conference-ticket').first() @@ -66,7 +66,7 @@ def test_basic_with_utm_headers(self): utm_id = 'id' gclid = 'gclid' data = { - 'line_items': [{'item_id': unicode(item.id), 'quantity': 2}], + 'line_items': [{'item_id': str(item.id), 'quantity': 2}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -84,22 +84,22 @@ def test_basic_with_utm_headers(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] order = Order.query.get(resp_data.get('order_id')) order_session = order.session - self.assertEquals(order_session.utm_campaign, utm_campaign) - self.assertEquals(order_session.utm_medium, utm_medium) - self.assertEquals(order_session.utm_source, utm_source) - self.assertEquals(order_session.utm_term, utm_term) - self.assertEquals(order_session.utm_content, utm_content) - self.assertEquals(order_session.utm_id, utm_id) - self.assertEquals(order_session.gclid, gclid) + self.assertEqual(order_session.utm_campaign, utm_campaign) + self.assertEqual(order_session.utm_medium, utm_medium) + self.assertEqual(order_session.utm_source, utm_source) + self.assertEqual(order_session.utm_term, utm_term) + self.assertEqual(order_session.utm_content, utm_content) + self.assertEqual(order_session.utm_id, utm_id) + self.assertEqual(order_session.gclid, gclid) def test_order_with_invalid_quantity(self): item = Item.query.filter_by(name='conference-ticket').first() data = { - 'line_items': [{'item_id': unicode(item.id), 'quantity': 1001}], + 'line_items': [{'item_id': str(item.id), 'quantity': 1001}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -108,12 +108,12 @@ def test_order_with_invalid_quantity(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 400) + self.assertEqual(resp.status_code, 400) def test_simple_discounted_item(self): discounted_item = Item.query.filter_by(name='t-shirt').first() data = { - 'line_items': [{'item_id': unicode(discounted_item.id), 'quantity': 5}], + 'line_items': [{'item_id': str(discounted_item.id), 'quantity': 5}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -122,15 +122,15 @@ def test_simple_discounted_item(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] - self.assertEquals(resp_data['final_amount'], 2375) + self.assertEqual(resp_data['final_amount'], 2375) def test_expired_item_order(self): expired_ticket = Item.query.filter_by(name='expired-ticket').first() quantity = 2 data = { - 'line_items': [{'item_id': unicode(expired_ticket.id), 'quantity': quantity}], + 'line_items': [{'item_id': str(expired_ticket.id), 'quantity': quantity}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -139,7 +139,7 @@ def test_expired_item_order(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 400) + self.assertEqual(resp.status_code, 400) def test_signed_discounted_coupon_order(self): first_item = Item.query.filter_by(name='conference-ticket').first() @@ -147,7 +147,7 @@ def test_signed_discounted_coupon_order(self): signed_code = signed_policy.gen_signed_code() discounted_quantity = 1 data = { - 'line_items': [{'item_id': unicode(first_item.id), 'quantity': discounted_quantity}], + 'line_items': [{'item_id': str(first_item.id), 'quantity': discounted_quantity}], 'discount_coupons': [signed_code], 'buyer': { 'fullname': 'Testing', @@ -157,11 +157,11 @@ def test_signed_discounted_coupon_order(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] - self.assertEquals(resp_data['final_amount'], first_item.current_price().amount - (signed_policy.percentage * first_item.current_price().amount) / decimal.Decimal(100.0)) + self.assertEqual(resp_data['final_amount'], first_item.current_price().amount - (signed_policy.percentage * first_item.current_price().amount) / decimal.Decimal(100.0)) line_item = LineItem.query.filter_by(customer_order_id=resp_data['order_id']).first() - self.assertEquals(line_item.discount_coupon.code, signed_code) + self.assertEqual(line_item.discount_coupon.code, signed_code) def test_complex_discounted_item(self): discounted_item1 = Item.query.filter_by(name='t-shirt').first() @@ -169,11 +169,11 @@ def test_complex_discounted_item(self): data = { 'line_items': [ { - 'item_id': unicode(discounted_item1.id), + 'item_id': str(discounted_item1.id), 'quantity': 5 }, { - 'item_id': unicode(discounted_item2.id), + 'item_id': str(discounted_item2.id), 'quantity': 10 } ], @@ -185,10 +185,10 @@ def test_complex_discounted_item(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) # 10*3500@90% + 5*500*@95 = 33875 resp_data = json.loads(resp.data)['result'] - self.assertEquals(resp_data['final_amount'], 33875) + self.assertEqual(resp_data['final_amount'], 33875) def test_discounted_complex_order(self): conf = Item.query.filter_by(name='conference-ticket').first() @@ -202,11 +202,11 @@ def test_discounted_complex_order(self): data = { 'line_items': [ { - 'item_id': unicode(tshirt.id), + 'item_id': str(tshirt.id), 'quantity': tshirt_quantity }, { - 'item_id': unicode(conf.id), + 'item_id': str(conf.id), 'quantity': conf_quantity } ], @@ -219,19 +219,19 @@ def test_discounted_complex_order(self): } ic = ItemCollection.query.first() resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_json = json.loads(resp.data)['result'] order = Order.query.get(resp_json.get('order_id')) tshirt_policy = DiscountPolicy.query.filter_by(title='5% discount on 5 t-shirts').first() tshirt_final_amount = (tshirt_price * tshirt_quantity) - (tshirt_quantity * (tshirt_policy.percentage * tshirt_price) / decimal.Decimal(100)) conf_policy = DiscountPolicy.query.filter_by(title='10% discount on rootconf').first() conf_final_amount = (conf_price * (conf_quantity - 2)) - ((conf_quantity - 2) * (conf_policy.percentage * conf_price) / decimal.Decimal(100)) - self.assertEquals(tshirt_final_amount + conf_final_amount, order.get_amounts(LINE_ITEM_STATUS.PURCHASE_ORDER).final_amount) + self.assertEqual(tshirt_final_amount + conf_final_amount, order.get_amounts(LINE_ITEM_STATUS.PURCHASE_ORDER).final_amount) def make_free_order(self): item = Item.query.filter_by(name='conference-ticket').first() data = { - 'line_items': [{'item_id': unicode(item.id), 'quantity': 1}], + 'line_items': [{'item_id': str(item.id), 'quantity': 1}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -245,25 +245,25 @@ def make_free_order(self): def test_free_order(self): resp = self.make_free_order() - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_json = json.loads(resp.data)['result'] order = Order.query.get(resp_json.get('order_id')) - self.assertEquals(order.status, ORDER_STATUS.PURCHASE_ORDER) - self.assertEquals(order.line_items[0].status, LINE_ITEM_STATUS.PURCHASE_ORDER) - self.assertEquals(resp_json['final_amount'], 0) + self.assertEqual(order.status, ORDER_STATUS.PURCHASE_ORDER) + self.assertEqual(order.line_items[0].status, LINE_ITEM_STATUS.PURCHASE_ORDER) + self.assertEqual(resp_json['final_amount'], 0) resp = self.client.post('/order/{order_id}/free'.format(order_id=order.id), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) coupon = DiscountCoupon.query.filter_by(code='coupon2').first() - self.assertEquals(coupon.used_count, 1) - self.assertEquals(order.status, ORDER_STATUS.SALES_ORDER) - self.assertEquals(order.line_items[0].status, LINE_ITEM_STATUS.CONFIRMED) + self.assertEqual(coupon.used_count, 1) + self.assertEqual(order.status, ORDER_STATUS.SALES_ORDER) + self.assertEqual(order.line_items[0].status, LINE_ITEM_STATUS.CONFIRMED) def test_cancel_line_item_in_order(self): original_quantity = 2 order_item = Item.query.filter_by(name='t-shirt').first() total_amount = order_item.current_price().amount * original_quantity data = { - 'line_items': [{'item_id': unicode(order_item.id), 'quantity': original_quantity}], + 'line_items': [{'item_id': str(order_item.id), 'quantity': original_quantity}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -273,9 +273,9 @@ def test_cancel_line_item_in_order(self): ic = ItemCollection.query.first() # make a purchase order resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_json = json.loads(resp.data)['result'] - self.assertEquals(resp_json['final_amount'], total_amount) + self.assertEqual(resp_json['final_amount'], total_amount) order = Order.query.get(resp_json['order_id']) # Create fake payment and transaction objects @@ -304,23 +304,23 @@ def test_cancel_line_item_in_order(self): } with app.request_context(self.post_env): process_partial_refund_for_order(partial_refund_args) - self.assertEquals(pre_refund_transactions_count + 1, order.refund_transactions.count()) + self.assertEqual(pre_refund_transactions_count + 1, order.refund_transactions.count()) first_line_item = order.line_items[0] # Mock Razorpay's API razorpay.refund_payment = MagicMock(return_value=MockResponse(response_data={'id': buid()})) process_line_item_cancellation(first_line_item) - self.assertEquals(first_line_item.status, LINE_ITEM_STATUS.CANCELLED) + self.assertEqual(first_line_item.status, LINE_ITEM_STATUS.CANCELLED) expected_refund_amount = total_amount - refund_amount refund_transaction1 = PaymentTransaction.query.filter_by(order=order, transaction_type=TRANSACTION_TYPE.REFUND).order_by(PaymentTransaction.created_at.desc()).first() - self.assertEquals(refund_transaction1.amount, expected_refund_amount) + self.assertEqual(refund_transaction1.amount, expected_refund_amount) def test_cancel_line_item_in_bulk_order(self): original_quantity = 5 discounted_item = Item.query.filter_by(name='t-shirt').first() total_amount = discounted_item.current_price().amount * original_quantity data = { - 'line_items': [{'item_id': unicode(discounted_item.id), 'quantity': original_quantity}], + 'line_items': [{'item_id': str(discounted_item.id), 'quantity': original_quantity}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -330,9 +330,9 @@ def test_cancel_line_item_in_bulk_order(self): ic = ItemCollection.query.first() # make a purchase order resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_json = json.loads(resp.data)['result'] - self.assertEquals(resp_json['final_amount'], (total_amount - 5 * total_amount / decimal.Decimal(100))) + self.assertEqual(resp_json['final_amount'], (total_amount - 5 * total_amount / decimal.Decimal(100))) order = Order.query.get(resp_json['order_id']) # Create fake payment and transaction objects @@ -350,19 +350,19 @@ def test_cancel_line_item_in_bulk_order(self): # Mock Razorpay's API razorpay.refund_payment = MagicMock(return_value=MockResponse(response_data={'id': buid()})) process_line_item_cancellation(first_line_item) - self.assertEquals(first_line_item.status, LINE_ITEM_STATUS.CANCELLED) + self.assertEqual(first_line_item.status, LINE_ITEM_STATUS.CANCELLED) for void_line_item in to_be_void_line_items: - self.assertEquals(void_line_item.status, LINE_ITEM_STATUS.VOID) + self.assertEqual(void_line_item.status, LINE_ITEM_STATUS.VOID) expected_refund_amount = precancellation_order_amount - order.get_amounts(LINE_ITEM_STATUS.CONFIRMED).final_amount refund_transaction1 = PaymentTransaction.query.filter_by(order=order, transaction_type=TRANSACTION_TYPE.REFUND).first() - self.assertEquals(refund_transaction1.amount, expected_refund_amount) + self.assertEqual(refund_transaction1.amount, expected_refund_amount) second_line_item = order.confirmed_line_items[0] razorpay.refund_payment = MagicMock(return_value=MockResponse(response_data={'id': buid()})) process_line_item_cancellation(second_line_item) - self.assertEquals(second_line_item.status, LINE_ITEM_STATUS.CANCELLED) + self.assertEqual(second_line_item.status, LINE_ITEM_STATUS.CANCELLED) refund_transaction2 = PaymentTransaction.query.filter_by(order=order, transaction_type=TRANSACTION_TYPE.REFUND).order_by(PaymentTransaction.created_at.desc()).first() - self.assertEquals(refund_transaction2.amount, second_line_item.final_amount) + self.assertEqual(refund_transaction2.amount, second_line_item.final_amount) # test failed cancellation third_line_item = order.confirmed_line_items[0] @@ -403,8 +403,8 @@ def test_cancel_line_item_in_bulk_order(self): third_line_item = order.confirmed_line_items[0] pre_cancellation_transactions_count = order.refund_transactions.count() cancelled_refund_amount = process_line_item_cancellation(third_line_item) - self.assertEquals(cancelled_refund_amount, decimal.Decimal(0)) - self.assertEquals(pre_cancellation_transactions_count, order.refund_transactions.count()) + self.assertEqual(cancelled_refund_amount, decimal.Decimal(0)) + self.assertEqual(pre_cancellation_transactions_count, order.refund_transactions.count()) # test free line item cancellation free_order_resp = self.make_free_order() @@ -412,15 +412,15 @@ def test_cancel_line_item_in_bulk_order(self): free_order = Order.query.get(free_order_resp_data.get('order_id')) free_line_item = free_order.line_items[0] process_line_item_cancellation(free_line_item) - self.assertEquals(free_line_item.status, LINE_ITEM_STATUS.CANCELLED) - self.assertEquals(free_order.transactions.count(), 0) + self.assertEqual(free_line_item.status, LINE_ITEM_STATUS.CANCELLED) + self.assertEqual(free_order.transactions.count(), 0) def test_partial_refund_in_order(self): original_quantity = 5 discounted_item = Item.query.filter_by(name='t-shirt').first() total_amount = discounted_item.current_price().amount * original_quantity data = { - 'line_items': [{'item_id': unicode(discounted_item.id), 'quantity': original_quantity}], + 'line_items': [{'item_id': str(discounted_item.id), 'quantity': original_quantity}], 'buyer': { 'fullname': 'Testing', 'phone': '9814141414', @@ -430,9 +430,9 @@ def test_partial_refund_in_order(self): ic = ItemCollection.query.first() # make a purchase order resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])]) - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] - self.assertEquals(resp_data['final_amount'], (total_amount - 5 * total_amount / decimal.Decimal(100))) + self.assertEqual(resp_data['final_amount'], (total_amount - 5 * total_amount / decimal.Decimal(100))) order = Order.query.get(resp_data['order_id']) # Create fake payment and transaction objects @@ -465,10 +465,10 @@ def test_partial_refund_in_order(self): refund_transactions = order.transactions.filter_by(transaction_type=TRANSACTION_TYPE.REFUND).all() self.assertIsInstance(refund_transactions[0].refunded_at, datetime.datetime) - self.assertEquals(refund_transactions[0].amount, decimal.Decimal(valid_refund_amount)) - self.assertEquals(refund_transactions[0].internal_note, formdata['internal_note']) - self.assertEquals(refund_transactions[0].note_to_user, formdata['note_to_user']) - self.assertEquals(refund_transactions[0].refund_description, formdata['refund_description']) + self.assertEqual(refund_transactions[0].amount, decimal.Decimal(valid_refund_amount)) + self.assertEqual(refund_transactions[0].internal_note, formdata['internal_note']) + self.assertEqual(refund_transactions[0].note_to_user, formdata['note_to_user']) + self.assertEqual(refund_transactions[0].refund_description, formdata['refund_description']) invalid_refund_amount = 100000000 formdata = { @@ -483,12 +483,12 @@ def test_partial_refund_in_order(self): with app.request_context(self.post_env): resp = process_partial_refund_for_order(partial_refund_args) - self.assertEquals(resp.status_code, 403) + self.assertEqual(resp.status_code, 403) refund_transactions = order.transactions.filter_by(transaction_type=TRANSACTION_TYPE.REFUND).all() - self.assertEquals(refund_transactions[0].amount, decimal.Decimal(valid_refund_amount)) + self.assertEqual(refund_transactions[0].amount, decimal.Decimal(valid_refund_amount)) resp = self.make_free_order() - self.assertEquals(resp.status_code, 201) + self.assertEqual(resp.status_code, 201) resp_data = json.loads(resp.data)['result'] order = Order.query.get(resp_data.get('order_id')) invalid_refund_amount = 100000000 @@ -505,7 +505,7 @@ def test_partial_refund_in_order(self): with app.request_context(self.post_env): refund_resp = process_partial_refund_for_order(partial_refund_args) - self.assertEquals(refund_resp.status_code, 403) + self.assertEqual(refund_resp.status_code, 403) def tearDown(self): db.session.rollback() From 345c1d3220cefb5cdc2d9760e4815e602ad435d1 Mon Sep 17 00:00:00 2001 From: Bibhas Date: Fri, 31 Jan 2020 00:42:17 +0530 Subject: [PATCH 2/7] bumped up python version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 722863b6..ded8b24c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: python python: - - 2.7 + - 3.7 cache: directories: - $HOME/.cache/pip From d55323003e950374eb0b110e46fb5746ec724df0 Mon Sep 17 00:00:00 2001 From: Bibhas Date: Fri, 31 Jan 2020 18:31:49 +0530 Subject: [PATCH 3/7] updated test requirements --- test_requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test_requirements.txt b/test_requirements.txt index c65cf2f4..920deb77 100644 --- a/test_requirements.txt +++ b/test_requirements.txt @@ -1,3 +1,4 @@ coverage==4.5.4 -nose-progressive==1.5.2 +coveralls==1.8.2 mock==3.0.5 +pytest>=4.6.3 From 1376c9a7823a15a543893c3f944133dafd9a205d Mon Sep 17 00:00:00 2001 From: Bibhas Date: Fri, 31 Jan 2020 20:38:51 +0530 Subject: [PATCH 4/7] updated requirements file --- .travis.yml | 4 ---- requirements.txt | 1 - 2 files changed, 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index ded8b24c..d947ac29 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,6 @@ install: - pip install -U pip wheel - pip install -r test_requirements.txt - pip install -r requirements.txt - - pip install https://github.com/hasgeek/coaster/archive/master.zip - npm install casperjs - make env: @@ -27,6 +26,3 @@ services: - redis-server notifications: email: false - slack: - - hasgeek:HDCoMDj3T4ICB59qFFVorCG8 - - friendsofhasgeek:3bLViYSzhfaThJovFYCVD3fX diff --git a/requirements.txt b/requirements.txt index 2d3b0179..703ffcb2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -18,7 +18,6 @@ premailer==3.6.1 python-dateutil==2.8.0 tabulate==0.8.5 Flask-Admin==1.5.4 -unicodecsv==0.14.1 isoweek==1.3.3 Flask-Migrate==2.5.2 html5print==0.1.2 From 3cb8f723f6c8a57ab20fc31615fe040276afee90 Mon Sep 17 00:00:00 2001 From: Bibhas Date: Sat, 1 Feb 2020 13:34:55 +0530 Subject: [PATCH 5/7] import syntax fix --- boxoffice/__init__.py | 2 +- boxoffice/extapi/razorpay.py | 2 +- boxoffice/forms/category.py | 2 +- boxoffice/forms/item.py | 2 +- boxoffice/forms/item_collection.py | 2 +- boxoffice/forms/order.py | 2 +- boxoffice/forms/participant.py | 2 +- boxoffice/models/category.py | 3 +-- boxoffice/models/discount_policy.py | 6 +++--- boxoffice/models/invoice.py | 4 ++-- boxoffice/models/item.py | 3 +-- boxoffice/models/line_item.py | 2 +- boxoffice/models/line_item_discounter.py | 2 +- boxoffice/models/order.py | 2 +- boxoffice/models/payment.py | 2 +- boxoffice/models/user.py | 2 +- boxoffice/views/admin.py | 8 ++++---- boxoffice/views/admin_category.py | 6 +++--- boxoffice/views/admin_discount.py | 3 +-- boxoffice/views/admin_item.py | 6 +++--- boxoffice/views/admin_item_collection.py | 10 +++++----- boxoffice/views/admin_order.py | 2 +- boxoffice/views/admin_report.py | 4 ++-- boxoffice/views/item_collection.py | 6 +++--- boxoffice/views/order.py | 9 +++------ boxoffice/views/participant.py | 4 ++-- boxoffice/views/utils.py | 3 +-- tests/integration/test_items.py | 4 ++-- 28 files changed, 49 insertions(+), 56 deletions(-) diff --git a/boxoffice/__init__.py b/boxoffice/__init__.py index 84eaf38d..4f078983 100644 --- a/boxoffice/__init__.py +++ b/boxoffice/__init__.py @@ -28,7 +28,7 @@ from . import extapi, views # NOQA -from boxoffice.models import db, User, Item, Price, DiscountPolicy, DiscountCoupon, ItemCollection, Organization, Category, Invoice # noqa +from .models import db, User, Item, Price, DiscountPolicy, DiscountCoupon, ItemCollection, Organization, Category, Invoice # noqa from .siteadmin import OrganizationModelView, DiscountCouponModelView, InvoiceModelView # noqa diff --git a/boxoffice/extapi/razorpay.py b/boxoffice/extapi/razorpay.py index d0d4bb35..f3d156f6 100644 --- a/boxoffice/extapi/razorpay.py +++ b/boxoffice/extapi/razorpay.py @@ -3,7 +3,7 @@ import requests from baseframe import localize_timezone from boxoffice import app -from boxoffice.models import OnlinePayment, PaymentTransaction, TRANSACTION_TYPE +from ..models import OnlinePayment, PaymentTransaction, TRANSACTION_TYPE # Don't use a trailing slash base_url = 'https://api.razorpay.com/v1' diff --git a/boxoffice/forms/category.py b/boxoffice/forms/category.py index 77f01157..df0c6e37 100644 --- a/boxoffice/forms/category.py +++ b/boxoffice/forms/category.py @@ -3,7 +3,7 @@ from baseframe import __ import baseframe.forms as forms from baseframe.forms.validators import StopValidation -from boxoffice.models import db, Category +from ..models import db, Category __all__ = ['CategoryForm'] diff --git a/boxoffice/forms/item.py b/boxoffice/forms/item.py index dc155766..7323558c 100644 --- a/boxoffice/forms/item.py +++ b/boxoffice/forms/item.py @@ -6,7 +6,7 @@ from baseframe import __, forms, localized_country_list from baseframe.forms.sqlalchemy import QuerySelectField from ..models import db, Category, ItemCollection -from boxoffice.data import indian_states, indian_states_dict +from ..data import indian_states, indian_states_dict __all__ = ['ItemForm'] diff --git a/boxoffice/forms/item_collection.py b/boxoffice/forms/item_collection.py index d7d13f21..d0752ae2 100644 --- a/boxoffice/forms/item_collection.py +++ b/boxoffice/forms/item_collection.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from baseframe import __, forms, localized_country_list -from boxoffice.data import indian_states, indian_states_dict +from ..data import indian_states, indian_states_dict __all__ = ['ItemCollectionForm'] diff --git a/boxoffice/forms/order.py b/boxoffice/forms/order.py index 62ef1e4c..48a62c32 100644 --- a/boxoffice/forms/order.py +++ b/boxoffice/forms/order.py @@ -2,7 +2,7 @@ from baseframe import __ import baseframe.forms as forms -from boxoffice.data import indian_states_dict, short_codes +from ..data import indian_states_dict, short_codes __all__ = ['LineItemForm', 'BuyerForm', 'OrderSessionForm', 'InvoiceForm'] diff --git a/boxoffice/forms/participant.py b/boxoffice/forms/participant.py index 5d598a86..95f4834a 100644 --- a/boxoffice/forms/participant.py +++ b/boxoffice/forms/participant.py @@ -3,7 +3,7 @@ from baseframe import __ import baseframe.forms as forms -from boxoffice.models import Assignee, Item, LineItem, Order, ORDER_STATUS +from ..models import Assignee, LineItem, Order, ORDER_STATUS __all__ = ['AssigneeForm'] diff --git a/boxoffice/models/category.py b/boxoffice/models/category.py index 94afc331..8ad2c29c 100644 --- a/boxoffice/models/category.py +++ b/boxoffice/models/category.py @@ -1,8 +1,7 @@ # -*- coding: utf-8 -*- -from boxoffice.models import db, BaseScopedNameMixin -from boxoffice.models import ItemCollection from sqlalchemy.ext.orderinglist import ordering_list +from ..models import db, BaseScopedNameMixin, ItemCollection __all__ = ['Category'] diff --git a/boxoffice/models/discount_policy.py b/boxoffice/models/discount_policy.py index e1015d15..a0458dca 100644 --- a/boxoffice/models/discount_policy.py +++ b/boxoffice/models/discount_policy.py @@ -9,8 +9,8 @@ from baseframe import __ from coaster.utils import LabeledEnum, uuid1mc, buid from coaster.sqlalchemy import cached -from boxoffice.models import db, IdMixin, BaseScopedNameMixin -from boxoffice.models import Organization +from ..models import db, IdMixin, BaseScopedNameMixin, Organization + __all__ = ['DiscountPolicy', 'DiscountCoupon', 'item_discount_policy', 'DISCOUNT_TYPE'] @@ -92,7 +92,7 @@ def gen_signed_code(self, identifier=None): identifier = buid() signer = Signer(self.secret) key = "{base}.{identifier}".format(base=self.discount_code_base, identifier=identifier) - return signer.sign(key) + return signer.sign(key).decode('utf-8') @staticmethod def is_signed_code_format(code): diff --git a/boxoffice/models/invoice.py b/boxoffice/models/invoice.py index 423ffcca..cc528763 100644 --- a/boxoffice/models/invoice.py +++ b/boxoffice/models/invoice.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- from coaster.utils import LabeledEnum, utcnow -from boxoffice.models import db, BaseMixin, UuidMixin, HeadersAndDataTuple, Organization, Order +from ..models import db, BaseMixin, UuidMixin, HeadersAndDataTuple, Organization, Order from sqlalchemy.sql import select, func from sqlalchemy.orm import validates from baseframe import __ -from boxoffice.models.user import get_fiscal_year +from .user import get_fiscal_year __all__ = ['Invoice', 'INVOICE_STATUS'] diff --git a/boxoffice/models/item.py b/boxoffice/models/item.py index e4bdf891..cb08ca2c 100644 --- a/boxoffice/models/item.py +++ b/boxoffice/models/item.py @@ -6,8 +6,7 @@ from baseframe import __ from coaster.utils import LabeledEnum, utcnow from coaster.sqlalchemy import with_roles -from . import db, JsonDict, BaseScopedNameMixin, MarkdownColumn -from . import ItemCollection, Category +from ..models import db, JsonDict, BaseScopedNameMixin, MarkdownColumn, ItemCollection, Category from .discount_policy import item_discount_policy __all__ = ['Item', 'Price'] diff --git a/boxoffice/models/line_item.py b/boxoffice/models/line_item.py index 2e1fbd0c..0767179c 100644 --- a/boxoffice/models/line_item.py +++ b/boxoffice/models/line_item.py @@ -9,7 +9,7 @@ from flask import current_app -from boxoffice.models import BaseMixin, Item, JsonDict, LineItemDiscounter, Order, db +from ..models import BaseMixin, Item, JsonDict, LineItemDiscounter, Order, db from isoweek import Week from baseframe import __, localize_timezone diff --git a/boxoffice/models/line_item_discounter.py b/boxoffice/models/line_item_discounter.py index e1623640..7ffe6ffa 100644 --- a/boxoffice/models/line_item_discounter.py +++ b/boxoffice/models/line_item_discounter.py @@ -2,7 +2,7 @@ import itertools from decimal import Decimal -from boxoffice.models import DiscountPolicy, Item +from ..models import DiscountPolicy, Item __all__ = ['LineItemDiscounter'] diff --git a/boxoffice/models/order.py b/boxoffice/models/order.py index 535541f7..7ff7ad0e 100644 --- a/boxoffice/models/order.py +++ b/boxoffice/models/order.py @@ -3,7 +3,7 @@ from decimal import Decimal from collections import namedtuple from sqlalchemy.sql import select, func -from boxoffice.models import db, BaseMixin, User +from ..models import db, BaseMixin, User from coaster.utils import LabeledEnum, buid, utcnow from baseframe import __ diff --git a/boxoffice/models/payment.py b/boxoffice/models/payment.py index 053cc6dd..2d644feb 100644 --- a/boxoffice/models/payment.py +++ b/boxoffice/models/payment.py @@ -6,7 +6,7 @@ from coaster.utils import LabeledEnum, isoweek_datetime from isoweek import Week from baseframe import __ -from boxoffice.models import db, BaseMixin, Order, ORDER_STATUS, MarkdownColumn, ItemCollection +from ..models import db, BaseMixin, Order, ORDER_STATUS, MarkdownColumn, ItemCollection from ..extapi.razorpay_status import RAZORPAY_PAYMENT_STATUS __all__ = ['OnlinePayment', 'PaymentTransaction', 'CURRENCY', 'CURRENCY_SYMBOL', 'TRANSACTION_TYPE'] diff --git a/boxoffice/models/user.py b/boxoffice/models/user.py index f6fee15a..9f1cd4a6 100644 --- a/boxoffice/models/user.py +++ b/boxoffice/models/user.py @@ -5,7 +5,7 @@ import pytz from flask import g from flask_lastuser.sqlalchemy import UserBase2, ProfileBase -from boxoffice.models import db, JsonDict +from ..models import db, JsonDict __all__ = ['User', 'Organization'] diff --git a/boxoffice/views/admin.py b/boxoffice/views/admin.py index c2fe68e2..806fc8cf 100644 --- a/boxoffice/views/admin.py +++ b/boxoffice/views/admin.py @@ -6,10 +6,10 @@ from coaster.views import load_models, render_with from coaster.utils import getbool from baseframe import _ -from boxoffice.models import Organization, ItemCollection -from boxoffice.models.line_item import calculate_weekly_sales -from boxoffice.models.payment import calculate_weekly_refunds -from boxoffice.views.utils import check_api_access, api_error, api_success +from ..models import Organization, ItemCollection +from ..models.line_item import calculate_weekly_sales +from ..models.payment import calculate_weekly_refunds +from .utils import check_api_access, api_error, api_success def jsonify_dashboard(data): diff --git a/boxoffice/views/admin_category.py b/boxoffice/views/admin_category.py index 91ac3b6f..90dcb93b 100644 --- a/boxoffice/views/admin_category.py +++ b/boxoffice/views/admin_category.py @@ -5,9 +5,9 @@ from coaster.views import load_models, render_with from baseframe import _ from baseframe.forms import render_form -from boxoffice.models import db, ItemCollection, Category -from boxoffice.views.utils import api_error, api_success -from boxoffice.forms import CategoryForm +from ..models import db, ItemCollection, Category +from ..forms import CategoryForm +from .utils import api_error, api_success def jsonify_new_category(data_dict): diff --git a/boxoffice/views/admin_discount.py b/boxoffice/views/admin_discount.py index 721a7aec..af2dde2a 100644 --- a/boxoffice/views/admin_discount.py +++ b/boxoffice/views/admin_discount.py @@ -7,8 +7,7 @@ import baseframe.forms as forms from baseframe.forms import render_form from coaster.views import load_models, render_with, requestargs -from ..models import db -from boxoffice.models import Organization, DiscountPolicy, DiscountCoupon, Price, CURRENCY +from ..models import db, Organization, DiscountPolicy, DiscountCoupon, Price, CURRENCY from ..forms import DiscountPolicyForm, DiscountCouponForm, DiscountPriceForm, CouponBasedDiscountPolicyForm, AutomaticDiscountPolicyForm, PriceBasedDiscountPolicyForm from .utils import xhr_only, api_error, api_success diff --git a/boxoffice/views/admin_item.py b/boxoffice/views/admin_item.py index b3f7d3c9..ee77bd5b 100644 --- a/boxoffice/views/admin_item.py +++ b/boxoffice/views/admin_item.py @@ -6,9 +6,9 @@ from coaster.views import load_models, requestargs, render_with from baseframe import _ from baseframe.forms import render_form -from boxoffice.models import db, Organization, ItemCollection, Item, Price -from boxoffice.views.utils import api_error, api_success, json_date_format -from boxoffice.forms import ItemForm, PriceForm +from ..models import db, Organization, ItemCollection, Item, Price +from .utils import api_error, api_success, json_date_format +from ..forms import ItemForm, PriceForm from .utils import xhr_only diff --git a/boxoffice/views/admin_item_collection.py b/boxoffice/views/admin_item_collection.py index 9517ca14..2a762cbb 100644 --- a/boxoffice/views/admin_item_collection.py +++ b/boxoffice/views/admin_item_collection.py @@ -7,11 +7,11 @@ from coaster.views import load_models, render_with from baseframe import localize_timezone, _ from baseframe.forms import render_form -from boxoffice.models import db, Organization, ItemCollection -from boxoffice.models.line_item import sales_delta, sales_by_date, counts_per_date_per_item -from boxoffice.forms import ItemCollectionForm -from boxoffice.views.utils import api_error, api_success -from boxoffice.views.admin_item import format_item_details +from ..models import db, Organization, ItemCollection +from ..models.line_item import sales_delta, sales_by_date, counts_per_date_per_item +from ..forms import ItemCollectionForm +from .utils import api_error, api_success +from .admin_item import format_item_details def jsonify_item_collection(item_collection_dict): diff --git a/boxoffice/views/admin_order.py b/boxoffice/views/admin_order.py index f03a2dc8..0cc04e03 100644 --- a/boxoffice/views/admin_order.py +++ b/boxoffice/views/admin_order.py @@ -3,7 +3,7 @@ from flask import jsonify, url_for from .. import app, lastuser from coaster.views import load_models, render_with -from boxoffice.models import ItemCollection, Organization, Order, CURRENCY_SYMBOL, LineItem, LINE_ITEM_STATUS, ORDER_STATUS, INVOICE_STATUS +from ..models import ItemCollection, Organization, Order, CURRENCY_SYMBOL, LineItem, LINE_ITEM_STATUS, ORDER_STATUS, INVOICE_STATUS from .utils import json_date_format, xhr_only, check_api_access diff --git a/boxoffice/views/admin_report.py b/boxoffice/views/admin_report.py index 9588fbf6..8069858c 100644 --- a/boxoffice/views/admin_report.py +++ b/boxoffice/views/admin_report.py @@ -4,8 +4,8 @@ from .. import app, lastuser from coaster.views import load_models, render_with from baseframe import localize_timezone, get_locale -from boxoffice.models import Organization, ItemCollection, INVOICE_STATUS -from boxoffice.views.utils import check_api_access, csv_response, api_error +from ..models import Organization, ItemCollection, INVOICE_STATUS +from .utils import check_api_access, csv_response, api_error from babel.dates import format_datetime from datetime import datetime, date from ..extapi.razorpay import get_settled_transactions diff --git a/boxoffice/views/item_collection.py b/boxoffice/views/item_collection.py index aab6b02f..4adf5636 100644 --- a/boxoffice/views/item_collection.py +++ b/boxoffice/views/item_collection.py @@ -4,10 +4,10 @@ from baseframe import localized_country_list from coaster.views import load_models from coaster.utils import getbool -from boxoffice import app -from boxoffice.models import Organization, ItemCollection, Item, DiscountPolicy +from .. import app +from ..models import Organization, ItemCollection, Item, DiscountPolicy from .utils import xhr_only, cors, sanitize_coupons -from boxoffice.data import indian_states +from ..data import indian_states def jsonify_item(item): diff --git a/boxoffice/views/order.py b/boxoffice/views/order.py index 40b81420..e65e10ea 100644 --- a/boxoffice/views/order.py +++ b/boxoffice/views/order.py @@ -8,16 +8,13 @@ from baseframe import _, localized_country_list from baseframe.forms import render_form from .. import app, lastuser -from ..models import db -from ..models import ItemCollection, LineItem, Item, DiscountCoupon, DiscountPolicy, OrderSession, Assignee, LINE_ITEM_STATUS, Invoice -from ..models import Order, OnlinePayment, PaymentTransaction, User, CURRENCY, CURRENCY_SYMBOL, ORDER_STATUS -from ..models.payment import TRANSACTION_TYPE +from ..models import db, ItemCollection, LineItem, Item, DiscountCoupon, DiscountPolicy, OrderSession, Assignee, LINE_ITEM_STATUS, Invoice, Order, OnlinePayment, PaymentTransaction, User, CURRENCY, CURRENCY_SYMBOL, ORDER_STATUS, TRANSACTION_TYPE from ..extapi import razorpay, RAZORPAY_PAYMENT_STATUS from ..forms import LineItemForm, BuyerForm, OrderSessionForm, OrderRefundForm, InvoiceForm from .custom_exceptions import PaymentGatewayError -from boxoffice.mailclient import send_receipt_mail, send_line_item_cancellation_mail, send_order_refund_mail +from ..mailclient import send_receipt_mail, send_line_item_cancellation_mail, send_order_refund_mail from .utils import xhr_only, cors, json_date_format, api_error, api_success, sanitize_coupons -from boxoffice.data import indian_states +from ..data import indian_states def jsonify_line_items(line_items): diff --git a/boxoffice/views/participant.py b/boxoffice/views/participant.py index 3807dd9f..f9a102f6 100644 --- a/boxoffice/views/participant.py +++ b/boxoffice/views/participant.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- -from flask import jsonify, make_response, request +from flask import request -from boxoffice.mailclient import ( +from ..mailclient import ( send_ticket_assignment_mail, send_ticket_reassignment_mail, ) diff --git a/boxoffice/views/utils.py b/boxoffice/views/utils.py index 44ca8a37..95c59b6d 100644 --- a/boxoffice/views/utils.py +++ b/boxoffice/views/utils.py @@ -8,8 +8,7 @@ from flask import Response, abort, jsonify, make_response, request from baseframe import localize_timezone -from boxoffice import app - +from .. import app def sanitize_coupons(coupons): diff --git a/tests/integration/test_items.py b/tests/integration/test_items.py index cd39e946..7d2d97b1 100644 --- a/tests/integration/test_items.py +++ b/tests/integration/test_items.py @@ -2,13 +2,13 @@ import json import unittest -from datetime import datetime, timedelta +from datetime import timedelta from werkzeug.test import EnvironBuilder from coaster.utils import utcnow from boxoffice import app -from boxoffice.models import ORDER_STATUS, Assignee, Item, ItemCollection, Order, db +from boxoffice.models import ORDER_STATUS, Item, ItemCollection, Order, db from tests.fixtures import init_data From 19a1f2ce39e69678a5124b2583a0a7def473450b Mon Sep 17 00:00:00 2001 From: Bibhas Date: Sat, 1 Feb 2020 13:37:45 +0530 Subject: [PATCH 6/7] added back missing format() --- scripts/sync_razorpay_refunds.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/sync_razorpay_refunds.py b/scripts/sync_razorpay_refunds.py index 0fd994c1..2f353286 100644 --- a/scripts/sync_razorpay_refunds.py +++ b/scripts/sync_razorpay_refunds.py @@ -45,7 +45,7 @@ def sync_refunds(): correspongding_rp_refund = min(possible_rp_refunds, key=lambda rp_refund: abs(rp_refund['created_at'] - refund_epoch_dt)) if not correspongding_rp_refund or amount_in_paise(refund.amount) != correspongding_rp_refund['amount']: - raise "Oops! No refund found for {refundid}." + raise "Oops! No refund found for {refundid}.".format(refundid=refund.id) refund.pg_refundid = correspongding_rp_refund['id'] used_pg_refundids.append(correspongding_rp_refund['id']) db.session.commit() From 26d250f8a38f1371bf8eff0950706f83ddaaf6e7 Mon Sep 17 00:00:00 2001 From: Bibhas Date: Thu, 6 Feb 2020 11:47:21 +0530 Subject: [PATCH 7/7] keeping str to replace unicode --- boxoffice/forms/order.py | 2 +- boxoffice/models/item.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/boxoffice/forms/order.py b/boxoffice/forms/order.py index 48a62c32..ce5badf4 100644 --- a/boxoffice/forms/order.py +++ b/boxoffice/forms/order.py @@ -14,7 +14,7 @@ def trim(length): field = forms.StringField(__("Some field"), filters=[trim(25)]) """ def _inner(data): - return data[0:length] + return str(data[0:length]) return _inner diff --git a/boxoffice/models/item.py b/boxoffice/models/item.py index cb08ca2c..d3b587d6 100644 --- a/boxoffice/models/item.py +++ b/boxoffice/models/item.py @@ -153,7 +153,7 @@ def get_availability(cls, item_ids): item_tups = db.session.query(cls.id, cls.title, cls.quantity_total, db.func.count(cls.id)).join(LineItem).filter( LineItem.item_id.in_(item_ids), LineItem.status == LINE_ITEM_STATUS.CONFIRMED).group_by(cls.id).all() for item_tup in item_tups: - items_dict[item_tup[0]] = item_tup[1:] + items_dict[str(item_tup[0])] = item_tup[1:] return items_dict def demand_curve(self):