Example #1
0
 def post(self):
     try:
         db = get_connection()
         result = self.get_argument("result")
         method = self.get_argument("method", None)
         cart_no = result[2:]
         res = get_model("ecom.cart").search([["number", "=", cart_no]])
         if not res:
             raise Exception("Invalid cart  number")
         cart_id=res[0]
         cart=get_model("ecom.cart").browse(cart_id)
         if method:
             cart.update_paysbuy_method(method)
             db = database.get_connection()
             db.commit()
         if result.startswith("00") and not cart.is_paid:
             set_active_user(1)
             set_active_company(1)
             cart.import_paysbuy_payment()  # Inquiry Doublecheck
             db.commit()
     except Exception as e:
         db = get_connection()
         db.rollback
         import traceback
         audit_log("Failed to get result payment from paysbuy", details=traceback.format_exc())
         traceback.print_exc()
 def post(self):
     print("POST ARGUMENT >>>>>>>>>>>>>>>>>>>")
     print(self.request.body)
     f = open("paypal_return", "a")
     s = "################################################################################################################" + \
         "\n"
     s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
     s += "Request : " + str(self.request) + "\n"
     if self.request.body:
         s += "Body : " + str(self.request.body) + "\n"
     s += "################################################################################################################" + \
         "\n"
     f.write(s)
     f.close()
     cart_id = int(self.get_argument("cart_id"))
     token = self.get_argument("token", None)
     payer_id = self.get_argument("PayerID", None)
     cart = get_model("ecom.cart").browse(cart_id)
     if not cart.is_paid:
         access.set_active_user(1)
         access.set_active_company(1)
         cart.import_paypal_payment(token, context={})
         db = database.get_connection()
         db.commit()
     self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
Example #3
0
    def post(self):
        try:
            db = get_connection()
            print("########################################")
            print("###########Result Paypal Ipn############")
            print("########################################")

            payment_status = self.get_argument("payment_status", None)
            if payment_status != "Completed":
                raise Exception("Paypal transaction is not completed")
            invoice = self.get_argument("invoice")

            set_active_user(1)
            set_active_company(1)
            res = get_model("ecom.cart").search([["number", "=", invoice]])
            if not res:
                raise Exception("Invalid cart number: %s"%invoice)
            cart_id = res[0]
            cart=get_model("ecom.cart").browse(cart_id)
            website=cart.website_id
            receiver_email = self.get_argument("receiver_email", None)
            if receiver_email != website.paypal_user:
                raise Exception("Wrong paypal receiver email")

            if not website.paypal_user:
                raise Exception("Missing paypal user in cms setting")
            if not website.paypal_password:
                raise Exception("Missing paypal password in cms setting")
            if not website.paypal_signature:
                raise Exception("Missing paypal signature in cms setting")
            if not website.paypal_url:
                raise Exception("Missing paypal URL Server in cms setting")
            params = {}
            for argument in self.request.arguments:
                params[argument] = argument[0].decode('utf-8')
            params['cmd'] = '_notify-validate'
            if website.paypal_url == "test":
                url = "https://www.sandbox.paypal.com/cgi-bin/webscr"
            else:
                url = "https://www.paypal.com/cgi-bin/webscr"
            data = urllib.parse.urlencode(params)
            data = data.encode('utf-8')
            req = urllib.request.Request(url, data)
            response = urllib.request.urlopen(req)
            word = response.read()
            verify = word.decode('utf-8')
            if verify != "VERIFIED":
                raise Exception("Failed to verify payment")
            mc_gross = float(self.get_argument("mc_gross", None))
            if cart.amount_total != mc_gross:
                raise Exception("Amount total doesn't match")
            cart.import_paypal_payment()  # TODO Add Token
            print("Payment Created")
            db.commit()
        except Exception as e:
            db = get_connection()
            db.rollback
            import traceback
            audit_log("Failed to get IPN from paypal", details=traceback.format_exc())
            traceback.print_exc()
Example #4
0
 def post(self):
     print("POST ARGUMENT >>>>>>>>>>>>>>>>>>>")
     print(self.request.body)
     f = open("paypal_return", "a")
     s = "################################################################################################################" + \
         "\n"
     s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
     s += "Request : " + str(self.request) + "\n"
     if self.request.body:
         s += "Body : " + str(self.request.body) + "\n"
     s += "################################################################################################################" + \
         "\n"
     f.write(s)
     f.close()
     cart_id = int(self.get_argument("cart_id"))
     token = self.get_argument("token", None)
     payer_id = self.get_argument("PayerID", None)
     cart = get_model("ecom.cart").browse(cart_id)
     if not cart.is_paid:
         access.set_active_user(1)
         access.set_active_company(1)
         cart.import_paypal_payment(token, context={})
         db = database.get_connection()
         db.commit()
     self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
 def get(self):
     db = get_connection()
     try:
         cart_id = int(self.get_argument("cart_id"))
         print("cart_id", cart_id)
         cart = get_model("ecom.cart").browse(cart_id)
         set_active_company(1)
         user_id = get_active_user()
         website = self.context["website"]
         ctx = self.context
         ctx["cart"] = cart
         if not cart.is_paid and website.payment_slip_template_id and (cart.pay_method_id.id == website.bank_method_id.id):
             tmpl_name = website.payment_slip_template_id.name
             url = "/report?type=report_jasper&model=ecom.cart&convert=pdf&ids=[%d]&template=%s" % (
                 cart.id, tmpl_name)
             ctx["payment_slip_report_url"] = url
         content = render("ecom_order_confirmed", ctx)
         ctx["content"] = content
         html = render("cms_layout", ctx)
         self.write(html)
         db.commit()
     except:
         import traceback
         traceback.print_exc()
         db.rollback()
Example #6
0
 def get(self):
     db = get_connection()
     try:
         cart_id = int(self.get_argument("cart_id"))
         print("cart_id", cart_id)
         cart = get_model("ecom.cart").browse(cart_id)
         set_active_company(1)
         user_id = get_active_user()
         website = self.context["website"]
         ctx = self.context
         ctx["cart"] = cart
         if not cart.is_paid and website.payment_slip_template_id and (
                 cart.pay_method_id.id == website.bank_method_id.id):
             tmpl_name = website.payment_slip_template_id.name
             url = "/report?type=report_jasper&model=ecom.cart&convert=pdf&ids=[%d]&template=%s" % (
                 cart.id, tmpl_name)
             ctx["payment_slip_report_url"] = url
         content = render("ecom_order_confirmed", ctx)
         ctx["content"] = content
         html = render("cms_layout", ctx)
         self.write(html)
         db.commit()
     except:
         import traceback
         traceback.print_exc()
         db.rollback()
Example #7
0
 def post(self):
     try:
         db = get_connection()
         result = self.get_argument("result")
         method = self.get_argument("method", None)
         cart_no = result[2:]
         res = get_model("ecom.cart").search([["number", "=", cart_no]])
         if not res:
             raise Exception("Invalid cart  number")
         cart_id = res[0]
         cart = get_model("ecom.cart").browse(cart_id)
         if method:
             cart.update_paysbuy_method(method)
         if result.startswith("00") and not cart.is_paid:
             set_active_user(1)
             set_active_company(1)
             cart.import_paysbuy_payment()  # Inquiry Doublecheck
         db.commit()
     except Exception as e:
         db = get_connection()
         db.rollback
         import traceback
         audit_log("Failed to get result payment from paysbuy",
                   details=traceback.format_exc())
         traceback.print_exc()
Example #8
0
 def remove_expired_lots(self, context={}):
     print("StockLot.remove_expired_lots")
     access.set_active_user(1)
     access.set_active_company(1)
     settings = get_model("settings").browse(1)
     if not settings.lot_expiry_journal_id:
         raise Exception("Missing lot expiry journal")
     journal = settings.lot_expiry_journal_id
     if not journal.location_to_id:
         raise Exception("Missing to location in lot expiry journal")
     t = time.strftime("%Y-%m-%d")
     pick_vals = {"type": "out", "journal_id": journal.id, "lines": []}
     n = 0
     for obj in self.search_browse([["expiry_date", "<", t]]):
         prod = obj.product_id
         if not prod:
             continue
         for bal in obj.stock_balances:
             if bal.qty_phys <= 0:
                 continue
             line_vals = {
                 "product_id": prod.id,
                 "location_from_id": bal.location_id.id,
                 "location_to_id": journal.location_to_id.id,
                 "lot_id": obj.id,
                 "qty": bal.qty_phys,
                 "uom_id": prod.uom_id.id,
             }
             pick_vals["lines"].append(("create", line_vals))
             n += 1
     if pick_vals["lines"]:
         pick_id = get_model("stock.picking").create(pick_vals, context={"pick_type": "out"})
         get_model("stock.picking").set_done([pick_id])
         get_model("stock.picking").trigger([pick_id], "lot_expired")
     return {"flash": "%d lots removed from stock" % n}
Example #9
0
 def _get_currency(self, context={}):
     res = get_model("company").search([])  # XXX
     if not res:
         return
     company_id = res[0]
     access.set_active_company(company_id)
     settings = get_model("settings").browse(1)
     return settings.currency_id.id
Example #10
0
 def _get_currency(self,context={}):
     res=get_model("company").search([]) # XXX
     if not res:
         return
     company_id=res[0]
     access.set_active_company(company_id)
     settings=get_model("settings").browse(1)
     return settings.currency_id.id
Example #11
0
    def post(self):
        #try:
        with database.Transaction():
            #db = get_connection()
            print("########################################")
            print("#######Result Payment Online SCB########")
            print("#############     POST    ##############")
            print("########################################")

            f = open("scblog", "a")
            s = "################################################################################################################" + \
                "\n"
            s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
            s += "Request : " + str(self.request) + "\n"
            if self.request.body:
                s += "Body : " + str(self.request.body) + "\n"
            s += "################################################################################################################" + \
                "\n"
            f.write(s)
            f.close()

            if self.request.arguments:
                website = get_model("website").browse(1)
                if not website.scb_mid:
                    raise Exception("no merchant id in website settings")
                if not website.scb_terminal:
                    raise Exception("no terminal id in website settings")
                if not website.scb_url:
                    raise Exception("no URL server in website settings")
                mid = self.get_argument("mid", None)
                print(mid)
                if mid != website.scb_mid:
                    raise Exception("Merchant id does not match")
                terminal = self.get_argument("terminal", None)
                print(terminal)
                if terminal != website.scb_terminal:
                    raise Exception("Terminal id does not match")
                command = self.get_argument("command", None)
                print(command)
                if command != 'CRAUTH':
                    raise Exception("Command does not match")
                payment_status = self.get_argument("payment_status", None)
                print(payment_status)
                if payment_status == '003':
                    raise Exception("Payment host reject")
                if payment_status == '006':
                    raise Exception("Payment error")
                ref_no = self.get_argument("ref_no", None)
                print(ref_no)
                if payment_status == '002':
                    set_active_user(1)
                    set_active_company(1)
                    res = get_model("sale.order").search_browse(
                        [["number", "=", ref_no]])
                    if res:  # XXX Inquiry double check
                        sale = res[0]
                        if not sale.is_paid:
                            sale.import_scb_payment()
Example #12
0
    def post(self):
        #try:
        with database.Transaction():
            #db = get_connection()
            print("########################################")
            print("#######Result Payment Online SCB########")
            print("#############     POST    ##############")
            print("########################################")

            f = open("scblog", "a")
            s = "################################################################################################################" + \
                "\n"
            s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
            s += "Request : " + str(self.request) + "\n"
            if self.request.body:
                s += "Body : " + str(self.request.body) + "\n"
            s += "################################################################################################################" + \
                "\n"
            f.write(s)
            f.close()

            if self.request.arguments:
                website = get_model("website").browse(1)
                if not website.scb_mid:
                    raise Exception("no merchant id in website settings")
                if not website.scb_terminal:
                    raise Exception("no terminal id in website settings")
                if not website.scb_url:
                    raise Exception("no URL server in website settings")
                mid = self.get_argument("mid", None)
                print(mid)
                if mid != website.scb_mid:
                    raise Exception("Merchant id does not match")
                terminal = self.get_argument("terminal", None)
                print(terminal)
                if terminal != website.scb_terminal:
                    raise Exception("Terminal id does not match")
                command = self.get_argument("command", None)
                print(command)
                if command != 'CRAUTH':
                    raise Exception("Command does not match")
                payment_status = self.get_argument("payment_status", None)
                print(payment_status)
                if payment_status == '003':
                    raise Exception("Payment host reject")
                if payment_status == '006':
                    raise Exception("Payment error")
                ref_no = self.get_argument("ref_no", None)
                print(ref_no)
                if payment_status == '002':
                    set_active_user(1)
                    set_active_company(1)
                    res = get_model("sale.order").search_browse([["number", "=", ref_no]])
                    if res:  # XXX Inquiry double check
                        sale = res[0]
                        if not sale.is_paid:
                            sale.import_scb_payment()
Example #13
0
 def auto_create_production_orders(self, context={}):
     access.set_active_user(1)
     access.set_active_company(1)  # XXX
     vals = {
         "confirm_orders": True,
     }
     obj_id = self.create(vals)
     self.delete_planned_orders([obj_id])
     self.fill_products([obj_id])
     self.create_mo([obj_id])
Example #14
0
 def auto_create_purchase_orders(self,context={}):
     access.set_active_user(1)
     access.set_active_company(1) # XXX
     vals={
         "confirm_orders": True,
     }
     obj_id=self.create(vals)
     self.delete_planned_orders([obj_id])
     self.fill_products([obj_id])
     self.create_po([obj_id])
Example #15
0
 def migrate(self):
     comp_ids = get_model("company").search([])
     for comp_id in comp_ids:
         access.set_active_company(comp_id)
         settings = get_model("settings").browse(1)
         currency_id = settings.currency_id.id
         if not currency_id:
             print("WARNING: no currency for company %d" % comp_id)
             continue
         print("company %d -> currency %d" % (comp_id, currency_id))
         acc_ids = get_model("account.account").search([["company_id", "=", comp_id]])
         get_model("account.account").write(acc_ids, {"currency_id": currency_id})
Example #16
0
 def migrate(self):
     comp_ids=get_model("company").search([])
     for comp_id in comp_ids:
         access.set_active_company(comp_id)
         settings=get_model("settings").browse(1)
         currency_id=settings.currency_id.id
         if not currency_id:
             print("WARNING: no currency for company %d"%comp_id)
             continue
         print("company %d -> currency %d"%(comp_id,currency_id))
         acc_ids=get_model("account.account").search([["company_id","=",comp_id]])
         get_model("account.account").write(acc_ids,{"currency_id":currency_id})
Example #17
0
 def get_company_currency(self, ids, context={}):
     comp_cur = {}
     comp_id = get_active_company()
     for comp in get_model("company").search_browse([]):
         set_active_company(comp.id)
         comp_settings = get_model("settings").browse(1)
         comp_cur[comp.id] = comp_settings.currency_id.id
     set_active_company(comp_id)
     vals = {}
     for obj in self.browse(ids):
         vals[obj.id] = comp_cur.get(obj.company_id.id)
     return vals
 def get_company_currency(self, ids, context={}):
     comp_cur = {}
     comp_id = get_active_company()
     for comp in get_model("company").search_browse([]):
         set_active_company(comp.id)
         comp_settings = get_model("settings").browse(1)
         comp_cur[comp.id] = comp_settings.currency_id.id
     set_active_company(comp_id)
     vals = {}
     for obj in self.browse(ids):
         vals[obj.id] = comp_cur.get(obj.company_id.id)
     return vals
Example #19
0
def apply_migrations(from_version):
    to_version = get_db_version()
    print("Applying migrations from version %s to %s..." % (from_version, to_version))
    for mig_cls in sorted(_migrations, key=lambda m: (m._version, m._name)):
        if compare_version(mig_cls._version, from_version) <= 0:
            continue
        if mig_cls._max_version and compare_version(to_version, mig_cls._max_version) > 0:
            raise Exception(
                "Can not apply migration '%s', maximum version that can apply this migration is %s" % (mig._name, mig._max_version))
        mig = mig_cls()
        print("Applying migration %s..." % mig._name)
        set_active_user(1)
        set_active_company(None)
        mig.migrate()
Example #20
0
 def confirm(self,ids,context={}):
     obj=self.browse(ids)[0]
     user_id=context.get("user_id") # XXX: remove this later
     if user_id:
         user_id=int(user_id)
         user=get_model("base.user").browse(user_id)
         if user.contact_id: # XXX
             obj.write({"customer_id": user.contact_id.id})
     if obj.state=="confirmed":
         raise Exception("Order is already confirmed")
     access.set_active_company(1) # XXX
     order_lines={}
     for line in obj.lines:
         due_date=line.delivery_date or obj.delivery_date
         ship_address_id=line.ship_address_id.id
         k=(due_date,ship_address_id)
         order_lines.setdefault(k,[]).append(line)
     for (due_date,ship_address_id),lines in order_lines.items():
         vals={
             "contact_id": obj.customer_id.id,
             "ship_address_id": ship_address_id,
             "bill_address_id": obj.bill_address_id.id,
             "due_date": due_date,
             "lines": [],
             "related_id": "ecom2.cart,%s"%obj.id,
             "delivery_slot_id": obj.delivery_slot_id.id,
         }
         for line in lines:
             prod=line.product_id
             if not prod.locations:
                 raise Exception("Can't find location for product %s"%prod.code)
             location_id=prod.locations[0].location_id.id
             line_vals={
                 "product_id": prod.id,
                 "description": prod.description,
                 "qty": line.qty,
                 "uom_id": line.uom_id.id,
                 "unit_price": line.unit_price,
                 "location_id": location_id,
                 "lot_id": line.lot_id.id,
             }
             vals["lines"].append(("create",line_vals))
         sale_id=get_model("sale.order").create(vals)
         sale=get_model("sale.order").browse(sale_id)
         sale.confirm()
     obj.write({"state": "confirmed"})
     return {
         "order_id": sale.id,
         "order_num": sale.number,
     }
Example #21
0
def apply_migrations(from_version):
    to_version = get_db_version()
    print("Applying migrations from version %s to %s..." %
          (from_version, to_version))
    for mig_cls in sorted(_migrations, key=lambda m: (m._version, m._name)):
        if compare_version(mig_cls._version, from_version) <= 0:
            continue
        if mig_cls._max_version and compare_version(to_version,
                                                    mig_cls._max_version) > 0:
            raise Exception(
                "Can not apply migration '%s', maximum version that can apply this migration is %s"
                % (mig._name, mig._max_version))
        mig = mig_cls()
        print("Applying migration %s..." % mig._name)
        set_active_user(1)
        set_active_company(None)
        mig.migrate()
Example #22
0
 def post(self):
     try:
         print("POST ARGUMENT >>>>>>>>>>>>>>>>>>>")
         print(self.request.body)
         f = open("paysbuy_return", "a")
         s = "################################################################################################################" + \
             "\n"
         s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
         s += "Request : " + str(self.request) + "\n"
         if self.request.body:
             s += "Body : " + str(self.request.body) + "\n"
         s += "################################################################################################################" + \
             "\n"
         f.write(s)
         f.close()
         cart_id = int(self.get_argument("cart_id"))
         result = self.get_argument("result", None)
         method = self.get_argument("method", None)
         cart = get_model("ecom.cart").browse(cart_id)
         if method:
             access.set_active_user(1)
             access.set_active_company(1)
             cart.update_paysbuy_method(method)
             db = database.get_connection()
             db.commit()
         if result.startswith("00"): # received payment already
             if not cart.is_paid:
                 access.set_active_user(1)
                 access.set_active_company(1)
                 cart.import_paysbuy_payment()
                 db = database.get_connection()
                 db.commit()
             self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
         elif result.startswith("02"): # will receive payment later
             self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
         else:
             cart.cancel_order()
             db = database.get_connection()
             db.commit()
             #self.set_cookie("cart_id", str(cart_id))
             self.redirect("/ecom_order_cancelled?cart_id=%s" % cart_id)
     except Exception as e:
         db = database.get_connection()
         db.rollback
         import traceback
         traceback.print_exc()
Example #23
0
 def get_company_logo(self, context={}):
     dbname = database.get_active_db()
     if not dbname:
         return None
     user_id = get_active_user()
     try:
         set_active_user(1)
         res = get_model("company").search([["parent_id", "=", None]], order="id")
         if not res:
             return None
         company_id = res[0]
         set_active_company(company_id)
         settings = get_model("settings").browse(1)
         if not settings.logo:
             return None
         return "/static/db/%s/files/%s" % (dbname, settings.logo)
     finally:
         set_active_user(user_id)
Example #24
0
 def get_company_logo(self, context={}):
     dbname = database.get_active_db()
     if not dbname:
         return None
     user_id = get_active_user()
     try:
         set_active_user(1)
         res = get_model("company").search([["parent_id", "=", None]],
                                           order="id")
         if not res:
             return None
         company_id = res[0]
         set_active_company(company_id)
         settings = get_model("settings").browse(1)
         if not settings.logo:
             return None
         return "/static/db/%s/files/%s" % (dbname, settings.logo)
     finally:
         set_active_user(user_id)
Example #25
0
 def post(self):
     db = get_connection()
     try:
         ctx = self.context
         cart_id = int(self.get_argument("cart_id"))
         cart = get_model("ecom.cart").browse(cart_id)
         action = self.get_argument("action")
         if action == "cancel_cart":
             set_active_company(1)  #XXX Set to ICC company
             cart.ecom_cancel_cart()
             cart.trigger("cancel_by_customer")
             self.redirect("/cms_account")
         else:
             raise Exception("Invalid post action")
         db.commit()
     except:
         import traceback
         traceback.print_exc()
         db.rollback()
Example #26
0
 def post(self):
     db = get_connection()
     try:
         ctx = self.context
         cart_id = int(self.get_argument("cart_id"))
         cart = get_model("ecom.cart").browse(cart_id)
         action = self.get_argument("action")
         if action == "cancel_cart":
             set_active_company(1) #XXX Set to ICC company
             cart.ecom_cancel_cart()
             cart.trigger("cancel_by_customer")
             self.redirect("/cms_account")
         else:
             raise Exception("Invalid post action")
         db.commit()
     except:
         import traceback
         traceback.print_exc()
         db.rollback()
Example #27
0
 def remove_expired_lots(self, context={}):
     print("StockLot.remove_expired_lots")
     access.set_active_user(1)
     access.set_active_company(1)
     settings = get_model("settings").browse(1)
     if not settings.lot_expiry_journal_id:
         raise Exception("Missing lot expiry journal")
     journal = settings.lot_expiry_journal_id
     if not journal.location_to_id:
         raise Exception("Missing to location in lot expiry journal")
     t = time.strftime("%Y-%m-%d")
     pick_vals = {
         "type": "out",
         "journal_id": journal.id,
         "lines": [],
     }
     n = 0
     for obj in self.search_browse([["expiry_date", "<", t]]):
         prod = obj.product_id
         if not prod:
             continue
         for bal in obj.stock_balances:
             if bal.qty_phys <= 0:
                 continue
             line_vals = {
                 "product_id": prod.id,
                 "location_from_id": bal.location_id.id,
                 "location_to_id": journal.location_to_id.id,
                 "lot_id": obj.id,
                 "qty": bal.qty_phys,
                 "uom_id": prod.uom_id.id,
             }
             pick_vals["lines"].append(("create", line_vals))
             n += 1
     if pick_vals["lines"]:
         pick_id = get_model("stock.picking").create(
             pick_vals, context={"pick_type": "out"})
         get_model("stock.picking").set_done([pick_id])
         get_model("stock.picking").trigger([pick_id], "lot_expired")
     return {
         "flash": "%d lots removed from stock" % n,
     }
Example #28
0
 def post(self):
     print("POST >>>>>>>>>>>>>>>>>>>")
     with database.Transaction():
         cart_id = int(self.get_argument("cart_id"))
         cart = get_model("ecom.cart").browse(cart_id)
         website=cart.website_id
         base_url=(website.url or "").strip()
         if base_url.endswith("/"):
             base_url=base_url[:-1]
         response = self.get_argument("response")
         if response == "declined":
             cart.cancel_order()
             #self.set_cookie("cart_id", str(cart_id))
             self.redirect(base_url+"/ecom_order_cancelled?cart_id=%s" % cart_id)
             return
         if not cart.is_paid:
             access.set_active_user(1)
             access.set_active_company(1)
             cart.import_scb_payment()
         self.redirect(base_url+"/ecom_order_confirmed?cart_id=%s" % cart_id)
Example #29
0
 def post(self):
     with database.Transaction():
         print("POST ARGUMENT >>>>>>>>>>>>>>>>>>>")
         print(self.request.body)
         f = open("paysbuy_return", "a")
         s = "################################################################################################################" + \
             "\n"
         s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
         s += "Request : " + str(self.request) + "\n"
         if self.request.body:
             s += "Body : " + str(self.request.body) + "\n"
         s += "################################################################################################################" + \
             "\n"
         f.write(s)
         f.close()
         cart_id = int(self.get_argument("cart_id"))
         result = self.get_argument("result", None)
         method = self.get_argument("method", None)
         cart = get_model("ecom.cart").browse(cart_id)
         f = open("record_return", "a")
         x = "cart_id:" + str(cart_id)
         x += "\nrestut:" + result
         f.write(x)
         f.close()
         if method:
             access.set_active_user(1)
             access.set_active_company(1)
             cart.update_paysbuy_method(method)
         if result.startswith("00"):  # received payment already
             if not cart.is_paid:
                 access.set_active_user(1)
                 access.set_active_company(1)
                 cart.import_paysbuy_payment()
             self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
         elif result.startswith("02"):  # will receive payment later
             self.redirect("/ecom_order_confirmed?cart_id=%s" % cart_id)
         else:
             cart.cancel_order()
             self.redirect("/ecom_order_cancelled?cart_id=%s" % cart_id)
             self.redirect("/ecom_order_cancelled?cart_id=%s" % cart_id)
Example #30
0
 def post(self):
     print("POST >>>>>>>>>>>>>>>>>>>")
     with database.Transaction():
         cart_id = int(self.get_argument("cart_id"))
         cart = get_model("ecom.cart").browse(cart_id)
         website = cart.website_id
         base_url = (website.url or "").strip()
         if base_url.endswith("/"):
             base_url = base_url[:-1]
         response = self.get_argument("response")
         if response == "declined":
             cart.cancel_order()
             #self.set_cookie("cart_id", str(cart_id))
             self.redirect(base_url +
                           "/ecom_order_cancelled?cart_id=%s" % cart_id)
             return
         if not cart.is_paid:
             access.set_active_user(1)
             access.set_active_company(1)
             cart.import_scb_payment()
         self.redirect(base_url +
                       "/ecom_order_confirmed?cart_id=%s" % cart_id)
 def _conv_currency(bals):
     if not bals:
         return {}
     comp_cur = {}
     comp_id = get_active_company()
     for comp in get_model("company").search_browse([]):
         set_active_company(comp.id)
         comp_settings = get_model("settings").browse(1)
         comp_cur[comp.id] = comp_settings.currency_id.id
     set_active_company(comp_id)
     acc_ids = bals.keys()
     res = db.query("SELECT id,code,currency_id,company_id,type FROM account_account WHERE id IN %s", tuple(acc_ids))
     acc_cur = {}
     acc_comp = {}
     acc_rate_type = {}
     rate_sell = ["cash","cheque","bank","receivable","cur_asset","fixed_asset","noncur_asset","revenue","other_income"]
     for r in res:
         if not r["currency_id"]:
             raise Exception("Missing currency for account %s" % r["code"])
         acc_cur[r["id"]] = r["currency_id"]
         acc_comp[r["id"]] = r["company_id"]
         if r["type"]in rate_sell:
             acc_rate_type[r["id"]] = "sell"
         else:
             acc_rate_type[r["id"]] = "buy"
     bals2 = {}
     settings = get_model('settings').browse(1)
     for acc_id, vals in bals.items():
         comp_id = acc_comp.get(acc_id)
         comp_currency_id = comp_cur.get(comp_id) or settings.currency_id.id
         acc_currency_id = acc_cur[acc_id]
         rate_type = acc_rate_type[acc_id]
         bals2[acc_id] = {
             "debit": get_model("currency").convert(vals["debit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "credit": get_model("currency").convert(vals["credit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "balance": get_model("currency").convert(vals["balance"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "balance_cur": get_model("currency").convert(vals["balance_cur"], acc_currency_id, currency_id, date=date_to, rate_type=rate_type),
         }
     return bals2
Example #32
0
 def _conv_currency(bals):
     if not bals:
         return {}
     comp_cur = {}
     comp_id = get_active_company()
     for comp in get_model("company").search_browse([]):
         set_active_company(comp.id)
         comp_settings = get_model("settings").browse(1)
         comp_cur[comp.id] = comp_settings.currency_id.id
     set_active_company(comp_id)
     acc_ids = bals.keys()
     res = db.query("SELECT id,code,currency_id,company_id,type FROM account_account WHERE id IN %s", tuple(acc_ids))
     acc_cur = {}
     acc_comp = {}
     acc_rate_type = {}
     rate_sell = ["cash","cheque","bank","receivable","cur_asset","fixed_asset","noncur_asset","revenue","other_income"]
     for r in res:
         if not r["currency_id"]:
             raise Exception("Missing currency for account %s" % r["code"])
         acc_cur[r["id"]] = r["currency_id"]
         acc_comp[r["id"]] = r["company_id"]
         if r["type"]in rate_sell:
             acc_rate_type[r["id"]] = "sell"
         else:
             acc_rate_type[r["id"]] = "buy"
     bals2 = {}
     for acc_id, vals in bals.items():
         comp_id = acc_comp[acc_id]
         comp_currency_id = comp_cur[comp_id]
         acc_currency_id = acc_cur[acc_id]
         rate_type = acc_rate_type[acc_id]
         bals2[acc_id] = {
             "debit": get_model("currency").convert(vals["debit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "credit": get_model("currency").convert(vals["credit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "balance": get_model("currency").convert(vals["balance"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
             "balance_cur": get_model("currency").convert(vals["balance_cur"], acc_currency_id, currency_id, date=date_to, rate_type=rate_type),
         }
     return bals2
Example #33
0
 def confirm(self,ids,context={}):
     obj=self.browse(ids)[0]
     if obj.state=="confirmed":
         raise Exception("Order is already confirmed")
     access.set_active_company(1) # XXX
     order_lines={}
     for line in obj.lines:
         due_date=line.delivery_date or obj.delivery_date
         ship_address_id=line.ship_address_id.id
         k=(due_date,ship_address_id)
         order_lines.setdefault(k,[]).append(line)
     for (due_date,ship_address_id),lines in order_lines.items():
         vals={
             "contact_id": obj.customer_id.id,
             "ship_address_id": ship_address_id,
             "bill_address_id": obj.bill_address_id.id,
             "due_date": due_date,
             "lines": [],
             "related_id": "ecom2.cart,%s"%obj.id,
         }
         for line in lines:
             line_vals={
                 "product_id": line.product_id.id,
                 "description": line.product_id.description,
                 "qty": line.qty,
                 "uom_id": line.uom_id.id,
                 "unit_price": line.unit_price,
             }
             vals["lines"].append(("create",line_vals))
         sale_id=get_model("sale.order").create(vals)
         sale=get_model("sale.order").browse(sale_id)
     obj.write({"state": "confirmed"})
     return {
         "order_id": sale.id,
         "order_num": sale.number,
     }
Example #34
0
 def save_pay_method(self,ids,pay_method_id,context={}): # XXX: remove later
     access.set_active_company(1) # XXX
     obj=self.browse(ids[0])
     obj.write({"pay_method_id":pay_method_id})
Example #35
0
    def get(self):
        try:
            db = get_connection()
            print("########################################")
            print("#######Result Payment Online SCB########")
            print("#############     GET     ##############")
            print("########################################")

            f = open("scblog", "a")
            s = "################################################################################################################" + \
                "\n"
            s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
            s += "Request : " + str(self.request) + "\n"
            if self.request.body:
                s += "Body : " + str(self.request.body) + "\n"
            s += "################################################################################################################" + \
                "\n"
            f.write(s)
            f.close()

            if self.request.arguments:
                website=self.context["website"]
                if not website.scb_mid:
                    raise Exception("no merchant id in website settings")
                if not website.scb_terminal:
                    raise Exception("no terminal id in website settings")
                if not website.scb_url:
                    raise Exception("no URL server in website settings")
                mid = self.get_argument("mid", None)
                print(mid)
                if mid != settings.scb_mid:
                    raise Exception("Mercahant id does not match")
                terminal = self.get_argument("terminal", None)
                print(terminal)
                if terminal != settings.scb_terminal:
                    raise Exception("Terminal id does not match")
                command = self.get_argument("command", None)
                print(command)
                if command != 'CRAUTH':
                    raise Exception("Command does not match")
                payment_status = self.get_argument("payment_status", None)
                print(payment_status)
                if payment_status == '003':
                    raise Exception("Payment host reject")
                if payment_status == '006':
                    raise Exception("Payment error")
                ref_no = self.get_argument("ref_no", None)
                print(ref_no)
                if payment_status == '002':
                    set_active_user(1)
                    set_active_company(1)
                    res = get_model("ecom.cart").search_browse([["id", "=", ref_no]])
                    if res:  # XXX Inquiry double check
                        sale = res[0]
                        sale.import_scb_payment()
                        db.commit()
        except Exception as e:
            db = get_connection()
            db.rollback
            import traceback
            audit_log("Failed to get result payment from scb", details=traceback.format_exc())
            traceback.print_exc()
Example #36
0
    def copy_to_credit_note(self, ids, context={}):
        obj = self.browse(ids[0])
        company_id = get_active_company()
        set_active_company(obj.company_id.id)  # XXX
        try:
            ship_method_ids = []
            ship_method_amts = {}
            ship_amt_total = 0
            for line in obj.lines:
                ship_method_ids.append(line.ship_method_id.id)
                ship_method_amts.setdefault(line.ship_method_id.id, 0)
                ship_method_amts[line.ship_method_id.id] += line.amount
                ship_amt_total += line.amount
            ship_method_ids = list(set(ship_method_ids))
            inv_ids = []
            for ship_method_id in ship_method_ids:
                contact = obj.contact_id
                inv_vals = {
                    "type": "out",
                    "inv_type": "credit",
                    "ref": obj.number,
                    "related_id": "sale.return,%s" % obj.id,
                    "contact_id": contact.id,
                    "bill_address_id": obj.bill_address_id.id,
                    "currency_id": obj.currency_id.id,
                    "tax_type": obj.tax_type,
                    "pay_method_id": obj.pay_method_id.id,
                    "lines": [],
                }
                if contact.sale_journal_id:
                    inv_vals["journal_id"] = contact.sale_journal_id.id
                    if contact.sale_journal_id.sequence_id:
                        inv_vals[
                            "sequence_id"] = contact.sale_journal_id.sequence_id.id
                for line in obj.lines:
                    if not line.unit_price:
                        continue
                    if line.ship_method_id.id != ship_method_id:
                        continue
                    prod = line.product_id
                    remain_qty = line.qty - line.qty_invoiced
                    if remain_qty <= 0:
                        continue

                    sale_acc_id = None
                    if prod:
                        #1. get account from product
                        sale_acc_id = prod.sale_return_account_id and prod.sale_return_account_id.id
                        if not sale_acc_id and prod.sale_account_id:
                            sale_acc_id = prod.sale_account_id.id
                        # 2. if not get from master/parent product
                        if not sale_acc_id and prod.parent_id:
                            sale_acc_id = prod.parent_id.sale_account_id.id
                        # 3. if not get from product category
                        categ = prod.categ_id
                        if categ and not sale_acc_id:
                            sale_acc_id = categ.sale_account_id and categ.sale_account_id.id or None

                    #if not sale_acc_id:
                    #raise Exception("Missing sale account for product [%s] " % prod.name )

                    line_vals = {
                        "product_id":
                        prod.id,
                        "description":
                        line.description,
                        "qty":
                        remain_qty,
                        "uom_id":
                        line.uom_id.id,
                        "unit_price":
                        line.unit_price,
                        "discount":
                        line.discount,
                        "discount_amount":
                        line.discount_amount,
                        "account_id":
                        sale_acc_id,
                        "tax_id":
                        line.tax_id.id,
                        "amount":
                        line.qty * line.unit_price *
                        (1 - (line.discount or Decimal(0)) / 100) -
                        (line.discount_amount or Decimal(0)),
                    }
                    inv_vals["lines"].append(("create", line_vals))
                if not inv_vals["lines"]:
                    continue
                inv_id = get_model("account.invoice").create(
                    inv_vals, {
                        "type": "out",
                        "inv_type": "credit"
                    })
                inv_ids.append(inv_id)
            if not inv_ids:
                raise Exception("Nothing to invoice")
            print("inv_ids", inv_ids)
            return {
                "next": {
                    "name": "view_invoice",
                    "active_id": inv_ids[0],
                },
                "flash":
                "Credit note created from sales order %s" % obj.number,
                "invoice_id": inv_ids[0],
            }
        finally:
            set_active_company(company_id)
Example #37
0
 def confirm(self,ids,context={}):
     obj=self.browse(ids[0])
     user_id=context.get("user_id") # XX: remove this
     if user_id:
         user_id=int(user_id)
         user=get_model("base.user").browse(user_id)
         if user.contact_id:
             obj.write({"customer_id": user.contact_id.id})
     access.set_active_company(1) # XXX
     vals={
         "contact_id": obj.customer_id.id,
         "ship_address_id": obj.ship_address_id.id,
         "ship_method_id": obj.ship_method_id.id,
         "bill_address_id": obj.bill_address_id.id,
         "due_date": obj.delivery_date,
         "lines": [],
         "related_id": "ecom2.cart,%s"%obj.id,
         "delivery_slot_id": obj.delivery_slot_id.id,
         "pay_method_id": obj.pay_method_id.id,
         "other_info": obj.comments,
         "voucher_id": obj.voucher_id.id,
         "ref": obj.comments, # XXX
     }
     print (">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Ship Method Id ",ship_method_id)
     for line in obj.lines:
         prod=line.product_id
         if line.lot_id and line.qty_avail<=0:
             raise Exception("Lot is out of stock (%s)"%prod.name)
         if not prod.locations:
             raise Exception("Can't find location for product %s"%prod.code)
         location_id=prod.locations[0].location_id.id
         line_vals={
             "product_id": prod.id,
             "description": prod.description,
             "qty": line.qty,
             "uom_id": line.uom_id.id,
             "unit_price": line.unit_price,
             "location_id": location_id,
             "lot_id": line.lot_id.id,
             "due_date": line.delivery_date,
             "delivery_slot_id": obj.delivery_slot_id.id,
             "ship_address_id": line.ship_address_id.id,
         }
         vals["lines"].append(("create",line_vals))
     for ship in obj.ship_amount_details:
         meth_id=ship["ship_method_id"]
         amount=ship["ship_amount"]
         meth=get_model("ship.method").browse(meth_id)
         prod=meth.product_id
         if not prod:
             raise Exception("Missing product in shipping method %s"%meth.name)
         line_vals={
             "product_id": prod.id,
             "description": prod.description,
             "qty": 1,
             "uom_id": prod.uom_id.id,
             "unit_price": amount,
         }
         vals["lines"].append(("create",line_vals))
     sale_id=get_model("sale.order").create(vals)
     sale=get_model("sale.order").browse(sale_id)
     sale.confirm()
     obj.write({"state":"confirmed"})
     obj.trigger("confirm_order")
     return {
         "sale_id": sale_id,
     }
Example #38
0
    def post(self):
        try:
            db = get_connection()
            print("########################################")
            print("#######Result Payment Online SCB########")
            print("#############     POST    ##############")
            print("########################################")

            f = open("scblog", "a")
            s = "################################################################################################################" + \
                "\n"
            s += "Date : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
            s += "Request : " + str(self.request) + "\n"
            if self.request.body:
                s += "Body : " + str(self.request.body) + "\n"
            s += "################################################################################################################" + \
                "\n"
            f.write(s)
            f.close()

            if self.request.arguments:
                website = get_model("website").browse(1)
                if not website.scb_mid:
                    raise Exception("no merchant id in website settings")
                if not website.scb_terminal:
                    raise Exception("no terminal id in website settings")
                if not website.scb_url:
                    raise Exception("no URL server in website settings")
                mid = self.get_argument("mid", None)
                print(mid)
                if mid != website.scb_mid:
                    raise Exception("Merchant id does not match")
                terminal = self.get_argument("terminal", None)
                print(terminal)
                if terminal != website.scb_terminal:
                    raise Exception("Terminal id does not match")
                command = self.get_argument("command", None)
                print(command)
                if command != 'CRAUTH':
                    raise Exception("Command does not match")
                payment_status = self.get_argument("payment_status", None)
                print(payment_status)
                if payment_status == '003':
                    raise Exception("Payment host reject")
                if payment_status == '006':
                    raise Exception("Payment error")
                ref_no = self.get_argument("ref_no", None)
                print(ref_no)
                if payment_status == '002':
                    set_active_user(1)
                    set_active_company(1)
                    res = get_model("sale.order").search_browse([["number", "=", ref_no]])
                    if res:  # XXX Inquiry double check
                        sale = res[0]
                        sale.import_scb_payment()
                        db.commit()
                        #sale_date = time.strptime(sale.date, '%Y-%m-%d')
                        #date = time.strftime('%Y%m%d%H%M%S', sale_date)
                        # qs = urllib.parse.urlencode([
                        #('mid', mid),
                        #('terminal', terminal),
                        #('command', 'CRINQ'),
                        #('ref_no', sale.number),
                        #('ref_date', date),
                        #('service_id', 10),
                        #('cur_abbr', 'THB'),
                        #('amount', sale.amount_total),
                        #])
                        # if settings.scb_url == "test":
                        #url = 'https://nsips-test.scb.co.th:443/NSIPSWeb/NsipsMessageAction.do?'
                        # else:
                        #url = 'https://nsips.scb.co.th/NSIPSWeb/NsipsMessageAction.do?'
                        #data = qs.encode('utf-8')
                        #req = urllib.request.Request(url, data)
                        # print(qs)
                        #response = urllib.request.urlopen(req)
                        #ur = response.read()
                        # print(ur)
                        #te = ur.decode('utf-8')
                        #p = urllib.parse.parse_qsl(te)
                        #params = dict(list(map(lambda x: (x[0],x[1]),p)))
                        #inq_payment_status = params['payment_status'] or ''
                        #inq_payment_amount = params['amount'] or ''
                        # if not inq_payment_amount:
                        #raise Exception("Cannot get paid amount from SCB")
                        #inq_payment_amount = float(inq_payment_amount)
                        #print("Cart Amount --->%f"%sale.amount_total)
                        #print("Inquiry Amount--->%f"%inq_payment_amount)
                        # if abs(sale.amount_total-inq_payment_amount) >= 0.01:
                        #raise Exception("Pay amount does not match!!!")
                        # print(params)
                        # if inq_payment_status == "002":
                        # cart.write({"state":"paid"})
                        # db.commit()
                        # cart.copy_to_contact()
                        # if not cart.sale_id:
                        # cart.copy_to_sale()
                        #print("Payment Created")
                        # db.commit()
        except Exception as e:
            db = get_connection()
            db.rollback
            import traceback
            audit_log("Failed to get result payment from scb", details=traceback.format_exc())
            traceback.print_exc()
Example #39
0
 def confirm(self, ids, context={}):
     obj = self.browse(ids[0])
     user_id = context.get("user_id")  # XX: remove this
     if user_id:
         user_id = int(user_id)
         user = get_model("base.user").browse(user_id)
         if user.contact_id:
             obj.write({"customer_id": user.contact_id.id})
     access.set_active_company(1)  # XXX
     vals = {
         "contact_id": obj.customer_id.id,
         "ship_address_id": obj.ship_address_id.id,
         "ship_method_id": obj.ship_method_id.id,
         "bill_address_id": obj.bill_address_id.id,
         "due_date": obj.delivery_date,
         "lines": [],
         "related_id": "ecom2.cart,%s" % obj.id,
         "delivery_slot_id": obj.delivery_slot_id.id,
         "pay_method_id": obj.pay_method_id.id,
         "other_info": obj.comments,
         "voucher_id": obj.voucher_id.id,
         "ref": obj.comments,  # XXX
     }
     print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Ship Method Id ",
           ship_method_id)
     for line in obj.lines:
         prod = line.product_id
         if line.lot_id and line.qty_avail <= 0:
             raise Exception("Lot is out of stock (%s)" % prod.name)
         if not prod.locations:
             raise Exception("Can't find location for product %s" %
                             prod.code)
         location_id = prod.locations[0].location_id.id
         line_vals = {
             "product_id": prod.id,
             "description": prod.description,
             "qty": line.qty,
             "uom_id": line.uom_id.id,
             "unit_price": line.unit_price,
             "location_id": location_id,
             "lot_id": line.lot_id.id,
             "due_date": line.delivery_date,
             "delivery_slot_id": obj.delivery_slot_id.id,
             "ship_address_id": line.ship_address_id.id,
         }
         vals["lines"].append(("create", line_vals))
     for ship in obj.ship_amount_details:
         meth_id = ship["ship_method_id"]
         amount = ship["ship_amount"]
         meth = get_model("ship.method").browse(meth_id)
         prod = meth.product_id
         if not prod:
             raise Exception("Missing product in shipping method %s" %
                             meth.name)
         line_vals = {
             "product_id": prod.id,
             "description": prod.description,
             "qty": 1,
             "uom_id": prod.uom_id.id,
             "unit_price": amount,
         }
         vals["lines"].append(("create", line_vals))
     sale_id = get_model("sale.order").create(vals)
     sale = get_model("sale.order").browse(sale_id)
     sale.confirm()
     obj.write({"state": "confirmed"})
     obj.trigger("confirm_order")
     return {
         "sale_id": sale_id,
     }
Example #40
0
 def copy_to_credit_note(self, ids, context={}):
     obj = self.browse(ids[0])
     company_id = get_active_company()
     set_active_company(obj.company_id.id)  # XXX
     try:
         ship_method_ids = []
         ship_method_amts = {}
         ship_amt_total = 0
         for line in obj.lines:
             ship_method_ids.append(line.ship_method_id.id)
             ship_method_amts.setdefault(line.ship_method_id.id, 0)
             ship_method_amts[line.ship_method_id.id] += line.amount
             ship_amt_total += line.amount
         ship_method_ids = list(set(ship_method_ids))
         inv_ids = []
         for ship_method_id in ship_method_ids:
             contact = obj.contact_id
             inv_vals = {
                 "type": "out",
                 "inv_type": "credit",
                 "ref": obj.number,
                 "related_id": "sale.return,%s" % obj.id,
                 "contact_id": contact.id,
                 "bill_address_id": obj.bill_address_id.id,
                 "currency_id": obj.currency_id.id,
                 "tax_type": obj.tax_type,
                 "pay_method_id": obj.pay_method_id.id,
                 "lines": [],
             }
             if contact.sale_journal_id:
                 inv_vals["journal_id"] = contact.sale_journal_id.id
                 if contact.sale_journal_id.sequence_id:
                     inv_vals["sequence_id"] = contact.sale_journal_id.sequence_id.id
             for line in obj.lines:
                 if not line.unit_price:
                     continue
                 if line.ship_method_id.id != ship_method_id:
                     continue
                 prod = line.product_id
                 remain_qty = line.qty - line.qty_invoiced
                 if remain_qty <= 0:
                     continue
                 sale_acc_id = None
                 if prod:
                     sale_acc_id = prod.sale_account_id.id
                     if not sale_acc_id and prod.parent_id:
                         sale_acc_id = prod.parent_id.sale_account_id.id
                 line_vals = {
                     "product_id": prod.id,
                     "description": line.description,
                     "qty": remain_qty,
                     "uom_id": line.uom_id.id,
                     "unit_price": line.unit_price,
                     "discount": line.discount,
                     "discount_amount": line.discount_amount,
                     "account_id": sale_acc_id,
                     "tax_id": line.tax_id.id,
                     "amount": line.qty * line.unit_price * (1 - (line.discount or Decimal(0)) / 100)
                     - (line.discount_amount or Decimal(0)),
                 }
                 inv_vals["lines"].append(("create", line_vals))
             if not inv_vals["lines"]:
                 continue
             inv_id = get_model("account.invoice").create(inv_vals, {"type": "out", "inv_type": "invoice"})
             inv_ids.append(inv_id)
         if not inv_ids:
             raise Exception("Nothing to invoice")
         print("inv_ids", inv_ids)
         return {
             "next": {"name": "view_invoice", "active_id": inv_ids[0]},
             "flash": "Credit note created from sales order %s" % obj.number,
             "invoice_id": inv_ids[0],
         }
     finally:
         set_active_company(company_id)
Example #41
0
 def save_pay_method(self,ids,pay_method_id,context={}): # XXX: remove later
     access.set_active_company(1) # XXX
     obj=self.browse(ids[0])
     obj.write({"pay_method_id":pay_method_id})
    def get_balance(self, ids, context={}, nocache=False):
        print("Account.get_balance", ids, context)
        date_from = context.get("date_from")
        date_to = context.get("date_to")
        track_id = context.get("track_id")
        track2_id = context.get("track2_id")
        currency_id = context.get("currency_id")
        contact_id = context.get("contact_id")
        bank_rec_state = context.get("bank_rec_state")
        excl_date_to = context.get("excl_date_to")
        journal_id = context.get("journal_id")
        print("#########################################################################")
        print("get_balance CACHE MISS", ids)
        db = database.get_connection()

        def _get_balance(ids, date_from=None, date_to=None, track_id=None, track2_id=None, journal_id=None, contact_id=None, bank_rec_state=None, excl_date_to=None, nocache=False):
            if not ids:
                return {}
            if not nocache and not date_from and not date_to and not track_id and not track2_id and not journal_id and not contact_id and not bank_rec_state and not excl_date_to:
                acc_bals = get_model("field.cache").get_value("account.account", "balance", ids)
                remain_ids = [id for id in ids if id not in acc_bals]
                if remain_ids:
                    res = _get_balance(remain_ids, nocache=True)
                    for id, vals in res.items():
                        acc_bals[id] = vals
                        get_model("field.cache").set_value("account.account", "balance", id, vals)
                return acc_bals
            q = "SELECT l.account_id,SUM(l.debit) AS debit,SUM(l.credit) AS credit,SUM(COALESCE(l.amount_cur,l.debit-l.credit)) AS amount_cur FROM account_move_line l JOIN account_move m ON m.id=l.move_id WHERE l.account_id IN %s AND m.state='posted'"
            q_args = [tuple(ids)]
            if date_from:
                q += " AND m.date>=%s"
                q_args.append(date_from)
            if date_to:
                if excl_date_to:
                    q += " AND m.date<%s"
                else:
                    q += " AND m.date<=%s"
                q_args.append(date_to)
            if track_id:
                track_ids = get_model("account.track.categ").search([["id", "child_of", track_id]])
                q += " AND l.track_id IN %s"
                q_args.append(tuple(track_ids))
            if track2_id:
                track2_ids = get_model("account.track.categ").search([["id", "child_of", track2_id]])
                q += " AND l.track2_id IN %s"
                q_args.append(tuple(track2_ids))
            if contact_id:
                q += " AND l.contact_id=%s"
                q_args.append(contact_id)
            if bank_rec_state:
                q += " AND m.state=%s"
                q_args.append(bank_rec_state)
            if journal_id:
                q += " AND m.journal_id=%s"
                q_args.append(journal_id)
            q += " GROUP BY l.account_id"
            res = db.query(q, *q_args)
            id_res = {}
            for r in res:
                id_res[r.account_id] = r
            vals = {}
            for id in ids:
                r = id_res.get(id)
                vals[id] = {
                    "debit": r["debit"] if r else 0,
                    "credit": r["credit"] if r else 0,
                    "balance": r["debit"] - r["credit"] if r else 0,
                    "balance_cur": r["amount_cur"] if r else 0,
                }
            return vals

        def _conv_currency(bals):
            if not bals:
                return {}
            comp_cur = {}
            comp_id = get_active_company()
            for comp in get_model("company").search_browse([]):
                set_active_company(comp.id)
                comp_settings = get_model("settings").browse(1)
                comp_cur[comp.id] = comp_settings.currency_id.id
            set_active_company(comp_id)
            acc_ids = bals.keys()
            res = db.query("SELECT id,code,currency_id,company_id,type FROM account_account WHERE id IN %s", tuple(acc_ids))
            acc_cur = {}
            acc_comp = {}
            acc_rate_type = {}
            rate_sell = ["cash","cheque","bank","receivable","cur_asset","fixed_asset","noncur_asset","revenue","other_income"]
            for r in res:
                if not r["currency_id"]:
                    raise Exception("Missing currency for account %s" % r["code"])
                acc_cur[r["id"]] = r["currency_id"]
                acc_comp[r["id"]] = r["company_id"]
                if r["type"]in rate_sell:
                    acc_rate_type[r["id"]] = "sell"
                else:
                    acc_rate_type[r["id"]] = "buy"
            bals2 = {}
            settings = get_model('settings').browse(1)
            for acc_id, vals in bals.items():
                comp_id = acc_comp.get(acc_id)
                comp_currency_id = comp_cur.get(comp_id) or settings.currency_id.id
                acc_currency_id = acc_cur[acc_id]
                rate_type = acc_rate_type[acc_id]
                bals2[acc_id] = {
                    "debit": get_model("currency").convert(vals["debit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "credit": get_model("currency").convert(vals["credit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "balance": get_model("currency").convert(vals["balance"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "balance_cur": get_model("currency").convert(vals["balance_cur"], acc_currency_id, currency_id, date=date_to, rate_type=rate_type),
                }
            return bals2
        acc_bals = _get_balance(ids, date_from=date_from, date_to=date_to, track_id=track_id,
                                track2_id=track2_id, journal_id=journal_id, contact_id=contact_id, bank_rec_state=bank_rec_state, excl_date_to=excl_date_to)
        pl_types = ("revenue", "other_income", "cost_sales", "expense", "other_expense")
        pl_acc_ids = self.search([["type", "in", pl_types]])
        ret_acc_ids = {}
        comp_id = get_active_company()
        for comp in get_model("company").search_browse([]):
            set_active_company(comp.id)
            comp_settings = get_model("settings").browse(1)
            ret_acc_ids[comp.id] = comp_settings.retained_earnings_account_id.id
        set_active_company(comp_id)
        if (set(ids) & set(pl_acc_ids) or set(ids) & set(ret_acc_ids.values())) and not context.get("no_close"):
            pl_acc_comps = {}
            for acc in self.browse(pl_acc_ids):
                pl_acc_comps[acc.id] = acc.company_id.id
            if date_from:
                pl_date_from = get_model("settings").get_fiscal_year_start(date_from)
            else:
                pl_date_from = None
            pl_date_to = get_model("settings").get_fiscal_year_start(date_to)
            pl_date_to = (datetime.datetime.strptime(pl_date_to, "%Y-%m-%d") -
                          datetime.timedelta(days=1)).strftime("%Y-%m-%d")
            if not pl_date_from or pl_date_from <= pl_date_to:
                pl_bals = _get_balance(pl_acc_ids, date_from=pl_date_from, date_to=pl_date_to,
                                       track_id=track_id, track2_id=track2_id, journal_id=journal_id, contact_id=contact_id, bank_rec_state=bank_rec_state)
                ret_amts = {}
                for acc_id, pl_vals in pl_bals.items():
                    comp_id = pl_acc_comps[acc_id]
                    ret_amts.setdefault(comp_id, 0)
                    ret_amts[comp_id] += pl_vals["balance"]
                    if acc_id in acc_bals:
                        acc_vals = acc_bals[acc_id]
                        bal = acc_vals["balance"] - pl_vals["balance"]
                        acc_vals["debit"] = bal > 0 and bal or 0
                        acc_vals["credit"] = bal < 0 and -bal or 0
                        acc_vals["balance"] = bal
                        acc_vals["balance_cur"] = bal
                for comp_id, ret_amt in ret_amts.items():
                    ret_acc_id = ret_acc_ids.get(comp_id)
                    if not ret_acc_id or ret_acc_id not in acc_bals:
                        continue
                    acc_vals = acc_bals[ret_acc_id]
                    bal = acc_vals["balance"] + ret_amt
                    acc_vals["debit"] = bal > 0 and bal or 0
                    acc_vals["credit"] = bal < 0 and -bal or 0
                    acc_vals["balance"] = bal
                    acc_vals["balance_cur"] = bal
        if currency_id:
            acc_bals = _conv_currency(acc_bals)
        return acc_bals
Example #43
0
    def post(self):
        try:
            db = get_connection()
            print("########################################")
            print("###########Result Paypal Ipn############")
            print("########################################")

            payment_status = self.get_argument("payment_status", None)
            if payment_status != "Completed":
                raise Exception("Paypal transaction is not completed")
            invoice = self.get_argument("invoice")

            set_active_user(1)
            set_active_company(1)
            res = get_model("ecom.cart").search([["number", "=", invoice]])
            if not res:
                raise Exception("Invalid cart number: %s" % invoice)
            cart_id = res[0]
            cart = get_model("ecom.cart").browse(cart_id)
            website = cart.website_id
            receiver_email = self.get_argument("receiver_email", None)
            if receiver_email != website.paypal_user:
                raise Exception("Wrong paypal receiver email")

            if not website.paypal_user:
                raise Exception("Missing paypal user in cms setting")
            if not website.paypal_password:
                raise Exception("Missing paypal password in cms setting")
            if not website.paypal_signature:
                raise Exception("Missing paypal signature in cms setting")
            if not website.paypal_url:
                raise Exception("Missing paypal URL Server in cms setting")
            params = {}
            for argument in self.request.arguments:
                params[argument] = argument[0].decode('utf-8')
            params['cmd'] = '_notify-validate'
            if website.paypal_url == "test":
                url = "https://www.sandbox.paypal.com/cgi-bin/webscr"
            else:
                url = "https://www.paypal.com/cgi-bin/webscr"
            data = urllib.parse.urlencode(params)
            data = data.encode('utf-8')
            req = urllib.request.Request(url, data)
            response = urllib.request.urlopen(req)
            word = response.read()
            verify = word.decode('utf-8')
            if verify != "VERIFIED":
                raise Exception("Failed to verify payment")
            mc_gross = float(self.get_argument("mc_gross", None))
            if cart.amount_total != mc_gross:
                raise Exception("Amount total doesn't match")
            cart.import_paypal_payment()  # TODO Add Token
            print("Payment Created")
            db.commit()
        except Exception as e:
            db = get_connection()
            db.rollback
            import traceback
            audit_log("Failed to get IPN from paypal",
                      details=traceback.format_exc())
            traceback.print_exc()
Example #44
0
    def get_balance(self, ids, context={}, nocache=False):
        print("Account.get_balance", ids, context)
        date_from = context.get("date_from")
        date_to = context.get("date_to")
        track_id = context.get("track_id")
        track2_id = context.get("track2_id")
        currency_id = context.get("currency_id")
        contact_id = context.get("contact_id")
        bank_rec_state = context.get("bank_rec_state")
        excl_date_to = context.get("excl_date_to")
        journal_id = context.get("journal_id")
        print("#########################################################################")
        print("get_balance CACHE MISS", ids)
        db = database.get_connection()

        def _get_balance(ids, date_from=None, date_to=None, track_id=None, track2_id=None, journal_id=None, contact_id=None, bank_rec_state=None, excl_date_to=None, nocache=False):
            if not ids:
                return {}
            if not nocache and not date_from and not date_to and not track_id and not track2_id and not journal_id and not contact_id and not bank_rec_state and not excl_date_to:
                acc_bals = get_model("field.cache").get_value("account.account", "balance", ids)
                remain_ids = [id for id in ids if id not in acc_bals]
                if remain_ids:
                    res = _get_balance(remain_ids, nocache=True)
                    for id, vals in res.items():
                        acc_bals[id] = vals
                        get_model("field.cache").set_value("account.account", "balance", id, vals)
                return acc_bals
            q = "SELECT l.account_id,SUM(l.debit) AS debit,SUM(l.credit) AS credit,SUM(COALESCE(l.amount_cur,l.debit-l.credit)) AS amount_cur FROM account_move_line l JOIN account_move m ON m.id=l.move_id WHERE l.account_id IN %s AND m.state='posted'"
            q_args = [tuple(ids)]
            if date_from:
                q += " AND m.date>=%s"
                q_args.append(date_from)
            if date_to:
                if excl_date_to:
                    q += " AND m.date<%s"
                else:
                    q += " AND m.date<=%s"
                q_args.append(date_to)
            if track_id:
                track_ids = get_model("account.track.categ").search([["id", "child_of", track_id]])
                q += " AND l.track_id IN %s"
                q_args.append(tuple(track_ids))
            if track2_id:
                track2_ids = get_model("account.track.categ").search([["id", "child_of", track2_id]])
                q += " AND l.track2_id IN %s"
                q_args.append(tuple(track2_ids))
            if contact_id:
                q += " AND l.contact_id=%s"
                q_args.append(contact_id)
            if bank_rec_state:
                q += " AND m.state=%s"
                q_args.append(bank_rec_state)
            if journal_id:
                q += " AND m.journal_id=%s"
                q_args.append(journal_id)
            q += " GROUP BY l.account_id"
            res = db.query(q, *q_args)
            id_res = {}
            for r in res:
                id_res[r.account_id] = r
            vals = {}
            for id in ids:
                r = id_res.get(id)
                vals[id] = {
                    "debit": r["debit"] if r else 0,
                    "credit": r["credit"] if r else 0,
                    "balance": r["debit"] - r["credit"] if r else 0,
                    "balance_cur": r["amount_cur"] if r else 0,
                }
            return vals

        def _conv_currency(bals):
            if not bals:
                return {}
            comp_cur = {}
            comp_id = get_active_company()
            for comp in get_model("company").search_browse([]):
                set_active_company(comp.id)
                comp_settings = get_model("settings").browse(1)
                comp_cur[comp.id] = comp_settings.currency_id.id
            set_active_company(comp_id)
            acc_ids = bals.keys()
            res = db.query("SELECT id,code,currency_id,company_id,type FROM account_account WHERE id IN %s", tuple(acc_ids))
            acc_cur = {}
            acc_comp = {}
            acc_rate_type = {}
            rate_sell = ["cash","cheque","bank","receivable","cur_asset","fixed_asset","noncur_asset","revenue","other_income"]
            for r in res:
                if not r["currency_id"]:
                    raise Exception("Missing currency for account %s" % r["code"])
                acc_cur[r["id"]] = r["currency_id"]
                acc_comp[r["id"]] = r["company_id"]
                if r["type"]in rate_sell:
                    acc_rate_type[r["id"]] = "sell"
                else:
                    acc_rate_type[r["id"]] = "buy"
            bals2 = {}
            for acc_id, vals in bals.items():
                comp_id = acc_comp[acc_id]
                comp_currency_id = comp_cur[comp_id]
                acc_currency_id = acc_cur[acc_id]
                rate_type = acc_rate_type[acc_id]
                bals2[acc_id] = {
                    "debit": get_model("currency").convert(vals["debit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "credit": get_model("currency").convert(vals["credit"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "balance": get_model("currency").convert(vals["balance"], comp_currency_id, currency_id, date=date_to, rate_type=rate_type),
                    "balance_cur": get_model("currency").convert(vals["balance_cur"], acc_currency_id, currency_id, date=date_to, rate_type=rate_type),
                }
            return bals2
        acc_bals = _get_balance(ids, date_from=date_from, date_to=date_to, track_id=track_id,
                                track2_id=track2_id, journal_id=journal_id, contact_id=contact_id, bank_rec_state=bank_rec_state, excl_date_to=excl_date_to)
        pl_types = ("revenue", "other_income", "cost_sales", "expense", "other_expense")
        pl_acc_ids = self.search([["type", "in", pl_types]])
        ret_acc_ids = {}
        comp_id = get_active_company()
        for comp in get_model("company").search_browse([]):
            set_active_company(comp.id)
            comp_settings = get_model("settings").browse(1)
            ret_acc_ids[comp.id] = comp_settings.retained_earnings_account_id.id
        set_active_company(comp_id)
        if (set(ids) & set(pl_acc_ids) or set(ids) & set(ret_acc_ids.values())) and not context.get("no_close"):
            pl_acc_comps = {}
            for acc in self.browse(pl_acc_ids):
                pl_acc_comps[acc.id] = acc.company_id.id
            if date_from:
                pl_date_from = get_model("settings").get_fiscal_year_start(date_from)
            else:
                pl_date_from = None
            pl_date_to = get_model("settings").get_fiscal_year_start(date_to)
            pl_date_to = (datetime.datetime.strptime(pl_date_to, "%Y-%m-%d") -
                          datetime.timedelta(days=1)).strftime("%Y-%m-%d")
            if not pl_date_from or pl_date_from <= pl_date_to:
                pl_bals = _get_balance(pl_acc_ids, date_from=pl_date_from, date_to=pl_date_to,
                                       track_id=track_id, track2_id=track2_id, journal_id=journal_id, contact_id=contact_id, bank_rec_state=bank_rec_state)
                ret_amts = {}
                for acc_id, pl_vals in pl_bals.items():
                    comp_id = pl_acc_comps[acc_id]
                    ret_amts.setdefault(comp_id, 0)
                    ret_amts[comp_id] += pl_vals["balance"]
                    if acc_id in acc_bals:
                        acc_vals = acc_bals[acc_id]
                        bal = acc_vals["balance"] - pl_vals["balance"]
                        acc_vals["debit"] = bal > 0 and bal or 0
                        acc_vals["credit"] = bal < 0 and -bal or 0
                        acc_vals["balance"] = bal
                        acc_vals["balance_cur"] = bal
                for comp_id, ret_amt in ret_amts.items():
                    ret_acc_id = ret_acc_ids.get(comp_id)
                    if not ret_acc_id or ret_acc_id not in acc_bals:
                        continue
                    acc_vals = acc_bals[ret_acc_id]
                    bal = acc_vals["balance"] + ret_amt
                    acc_vals["debit"] = bal > 0 and bal or 0
                    acc_vals["credit"] = bal < 0 and -bal or 0
                    acc_vals["balance"] = bal
                    acc_vals["balance_cur"] = bal
        if currency_id:
            acc_bals = _conv_currency(acc_bals)
        return acc_bals
Example #45
0
 def post(self):
     website=self.context["website"]
     db = get_connection()
     try:
         if self.get_argument("commit", None):
             cart_id = self.get_argument("cart_id")
             cart_id = int(cart_id)
             fnames = [
                 "accept_marketing",
             ]
             vals = {}
             for n in fnames:
                 v = self.get_argument(n, None)
                 f = get_model("ecom.cart")._fields[n]
                 if v:
                     if isinstance(f, fields.Boolean):
                         v = v and True or False
                     elif isinstance(f, fields.Many2One):
                         v = int(v)
                 vals[n] = v
             if self.get_argument("check_tax", None):
                 if not self.get_argument("tax_no", None):
                     raise Exception("Please Enter Tax ID")
                 vals["tax_no"] = self.get_argument("tax_no", None)
             else:
                 vals["tax_no"] = ""
             if self.get_argument("tax_branch_no",None):
                 vals["tax_branch_no"]= self.get_argument("tax_branch_no",None)
             else:
                 vals["tax_branch_no"]= ""
             pay_method=self.get_argument("pay_method",None)
             if not pay_method:
                 raise Exception("Missing payment method")
             if pay_method=="bank_transfer":
                 pay_method_id=website.bank_method_id.id
             elif pay_method=="paypal":
                 pay_method_id=website.paypal_method_id.id
             elif pay_method=="paysbuy":
                 pay_method_id=website.paysbuy_method_id.id
             elif pay_method=="scb_gateway":
                 pay_method_id=website.scb_method_id.id
             else:
                 raise Exception("Invalid payment method")
             if not pay_method_id:
                 raise Exception("Payment method not configured")
             vals["pay_method_id"]=pay_method_id
             print("CART VALS", vals)
             get_model("ecom.cart").write([cart_id], vals)
             for arg in self.request.arguments:
                 if not arg.startswith("LINE_SHIP_METHOD_"):
                     continue
                 line_id=int(arg.replace("LINE_SHIP_METHOD_",""))
                 ship_method_code=self.get_argument(arg)
                 if ship_method_code:
                     res=get_model("ship.method").search([["code","=",ship_method_code]])
                     if not res:
                         raise Exception("Shipping method not found: %s"%ship_method_code)
                     ship_method_id=res[0]
                 else:
                     ship_method_id=None
                 vals={
                     "ship_method_id": ship_method_id,
                 }
                 print("line_id=%s => ship_method_id=%s"%(line_id,ship_method_id))
                 get_model("ecom.cart.line").write([line_id],vals)
             cart = get_model("ecom.cart").browse(cart_id)
             is_accept = self.get_argument("accept_marketing", None)
             if is_accept == 'on':
                 user_id = 1
                 res = get_model("sale.lead").search([["email", "=", cart.email]])
                 if not res:  # Check if this email already exist in Newsletter contact
                     vals = {
                         "state": "open",
                         "first_name": cart.bill_first_name,
                         "last_name": cart.bill_last_name,
                         "email": cart.email,
                         "user_id": user_id,
                     }
                     get_model("sale.lead").create(vals)
                 if not website.target_list_id:
                     raise Exception("No target list")
                 list_id = website.target_list_id.id
                 res = get_model("mkt.target").search([["email", "=", cart.email], ["list_id", "=", list_id]])
                 if not res:
                     target_vals = {
                         "list_id": list_id,
                         "first_name": cart.bill_first_name,
                         "last_name": cart.bill_last_name,
                         "email": cart.email,
                         "company": cart.bill_company,
                         "city": cart.bill_city,
                         "province_id": cart.bill_province_id.id,
                         "country_id": cart.bill_country_id.id,
                         "phone": cart.bill_phone,
                         "zip": cart.bill_postal_code,
                     }
                     get_model("mkt.target").create(target_vals)
             user_id = get_active_user()
             if not user_id and website.auto_create_account:
                 user_id = cart.create_account()
                 dbname = get_active_db()
                 token = new_token(dbname, user_id)
                 self.set_cookie("user_id", str(user_id))
                 self.set_cookie("token", token)
             set_active_user(1)
             set_active_company(1)
             cart.copy_to_contact({'force_write': False})
             if not user_id and website.auto_create_account: #First time create account
                 get_model("contact").trigger([cart.contact_id.id],"ecom_register")
             cart.copy_to_sale()
             cart = get_model("ecom.cart").browse(cart_id)
             db.commit()  # XXX: need otherwise browser redirect before commit?
             self.clear_cookie("cart_id")
             meth=cart.pay_method_id
             if not meth:
                 raise Exception("Missing payment method")
             if meth.type == "bank":
                 self.redirect("/ecom_order_confirmed?cart_id=%s" % cart.id)
             elif meth.type == "paypal":
                 if not meth.paypal_user:
                     raise Exception("Missing paypal user")
                 if not meth.paypal_password:
                     raise Exception("Missing paypal password")
                 if not meth.paypal_signature:
                     raise Exception("Missing paypal signature")
                 if not meth.paypal_url:
                     raise Exception("Missing paypal URL Server")
                 if meth.paypal_url == "test":
                     url = "https://api-3t.sandbox.paypal.com/nvp"
                 else:
                     url = "https://api-3t.paypal.com/nvp"
                 params = {
                     "method": "SetExpressCheckout",
                     "PAYMENTREQUEST_0_ITEMAMT": "%.2f" % (cart.amount_total - cart.amount_ship),
                     "PAYMENTREQUEST_0_AMT": "%.2f" % cart.amount_total,
                     "PAYMENTREQUEST_0_SHIPPINGAMT": "%.2f" % cart.amount_ship,
                     "PAYMENTREQUEST_0_CURRENCYCODE": "THB",
                     "PAYMENTREQUEST_0_PAYMENTACTION": "Sale",
                     "PAYMENTREQUEST_0_INVNUM": cart.number,
                     "returnUrl": "%s://%s/ecom_return_paypal?cart_id=%s" % (self.request.protocol, self.request.host, cart.id),
                     "cancelUrl": "%s://%s/ecom_order_cancelled?cart_id=%s" % (self.request.protocol, self.request.host, cart.id),
                     "version": "104.0",
                     "user": meth.paypal_user,
                     "pwd": meth.paypal_password,
                     "signature": meth.paypal_signature,
                 }
                 for i, line in enumerate(cart.lines):
                     params.update({
                         "L_PAYMENTREQUEST_0_NAME%d" % i: line.product_id.name,
                         "L_PAYMENTREQUEST_0_AMT%d" % i: "%.2f" % (line.amount / line.qty),
                         "L_PAYMENTREQUEST_0_QTY%d" % i: "%d" % line.qty,
                     })
                 try:
                     r = requests.get(url, params=params)
                     print("URL", r.url)
                     print("params", params)
                     res = urllib.parse.parse_qs(r.text)
                     print("RES", res)
                     token = res["TOKEN"][0]
                 except:
                     raise Exception("Failed start paypal transaction")
                 print("TOKEN", token)
                 if meth.paypal_url == "test":
                     url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=%s" % token
                 else:
                     url = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=%s" % token
                 self.redirect(url)
             elif meth.type == "paysbuy":
                 psbID = meth.paysbuy_id
                 if not meth.paysbuy_username:
                     raise Exception("Missing paysbuy username")
                 username = meth.paysbuy_username
                 if not meth.paysbuy_securecode:
                     raise Exception("Missing paysbuy secure code")
                 secureCode = meth.paysbuy_securecode
                 if not meth.paysbuy_url:
                     raise Exception("Missing paysbuy server URL")
                 if meth.paysbuy_url == "test":
                     url = "http://demo.paysbuy.com/api_paynow/api_paynow.asmx/api_paynow_authentication_new"
                 else:
                     url = "https://paysbuy.com/api_paynow/api_paynow.asmx/api_paynow_authentication_new"
                 itm = " & ".join(["%s x %s" % (line.product_id.name, line.qty) for line in cart.lines])
                 data = {
                     "psbId": psbID,
                     "username": username,
                     "secureCode": secureCode,
                     "inv": cart.number,
                     "itm": itm,
                     "amt": "%.2f" % cart.amount_total,
                     "curr_type": "TH",
                     "method": 1,
                     "language": "T",
                     "resp_front_url": "%s://%s/ecom_return_paysbuy?cart_id=%s" % (self.request.protocol, self.request.host, cart.id),
                     "resp_back_url": "%s://%s/ecom_notif_paysbuy?cart_id=%s" % (self.request.protocol, self.request.host, cart.id),
                     "paypal_amt": "",
                     "com": "",
                     "opt_fix_redirect": "1",
                     "opt_fix_method": "",
                     "opt_name": "",
                     "opt_email": "",
                     "opt_mobile": "",
                     "opt_address": "",
                     "opt_detail": "",
                 }
                 print("url", url)
                 print("Data sent to paysbuy:")
                 pprint(data)
                 try:
                     r = requests.post(url, data=data)
                     print("Paysbuy response:", r.text)
                     res = r.text.encode(encoding="utf-8")
                     parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8')
                     tree = etree.fromstring(res, parser)
                     response = tree.text
                     code = response[0:2]
                     refid = response[2:]
                     print("refid: %s" % refid)
                 except:
                     raise Exception("Failed start paysbuy transaction")
                 if code == "00":
                     if meth.paysbuy_url == "test":
                         url = "http://demo.paysbuy.com/api_payment/paynow.aspx?refid=%s" % refid
                     else:
                         url = "https://paysbuy.com/api_payment/paynow.aspx?refid=%s" % refid
                 else:
                     raise Exception("Invalid paysbuy response code: %s" % code)
                 self.redirect(url)
             elif meth.type == "scb_gateway":
                 if not meth.scb_mid:
                     raise Exception("Missing SCB merchant ID")
                 mid = meth.scb_mid
                 if not meth.scb_terminal:
                     raise Exception("Missing SCB terminal ID")
                 terminal = meth.scb_terminal
                 if not meth.scb_url:
                     raise Exception("Missing SCB server URL")
                 sale_date = time.strptime(cart.date_created, '%Y-%m-%d %H:%M:%S')
                 date = time.strftime('%Y%m%d%H%M%S', sale_date)
                 params = [
                     ('mid', mid),
                     ('terminal', terminal),
                     ('command', 'CRAUTH'),
                     ('ref_no', cart.number),
                     ('ref_date', date),
                     ('service_id', 10),
                     ('cur_abbr', 'THB'),
                     ('amount', '%.2f' % float(cart.amount_total)),
                     ('backURL', 'http://%s/ecom_returnscb?cart_id=%s' % (self.request.host, cart.id))
                 ]
                 urlparams = '&'.join(['%s=%s' % (k, v) for (k, v) in params])
                 if meth.scb_url == "test":
                     url = 'https://nsips-test.scb.co.th:443/NSIPSWeb/NsipsMessageAction.do?' + urlparams
                 else:
                     url = 'https://nsips.scb.co.th/NSIPSWeb/NsipsMessageAction.do?' + urlparams
                 self.redirect(url)
             else:
                 raise Exception("Unsupported payment method")
         db.commit()
     except Exception as e:
         import traceback
         traceback.print_exc()
         error_message = str(e)
         ctx = self.context
         cart = ctx.get("cart")
         if not cart:
             db.commit()
             self.redirect("/index")
             return
         ctx["ship_methods"] = cart.get_ship_methods()
         website=self.context["website"]
         ctx["error_message"] = error_message
         content = render("ecom_checkout2", ctx)
         ctx["content"] = content
         html = render("cms_layout", ctx)
         self.write(html)
         db.rollback()