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()
def payment_received(self,context={}): res=super().payment_received(context=context) if res: return res transaction_no=context.get("transaction_no") audit_log("Payment received: transaction_no=%s"%transaction_no) amount=context.get("amount") currency_id=context.get("currency_id") pay_type=context.get("type") res=get_model("sale.order").search([["transaction_no","=",transaction_no]]) if not res: print("Sales order not found for transaction_no=%s"%transaction_no) return sale_id=res[0] print("Found sales order %d for transaction_no=%s"%(sale_id,transaction_no)) sale=get_model("sale.order").browse(sale_id) if not sale.is_paid: if currency_id and currency_id!=sale.currency_id.id: raise Exception("Received sales order payment in wrong currency (pmt: %s, sale: %s)"%(currency_id,sale.currency_id.id)) method=sale.pay_method_id if not method: raise Exception("Missing sales order payment method") if method.type!=pay_type: raise Exception("Received sales order payment with wrong method (pmt: %s, sale: %s)"%(pay_type,method.type)) audit_log("Creating payment for sales order %s: transaction_no=%s"%(sale.number,transaction_no)) sale.payment_received() settings=get_model("ecom2.settings").browse(1) # XXX: change this if settings.ecom_return_url: url=settings.ecom_return_url+str(sale_id) else: url="/ui#name=sale&mode=form&active_id=%d"%sale_id return { "next_url": url, }
def payment_received(self,context={}): res=super().payment_received(context=context) if res: return res transaction_no=context.get("transaction_no") audit_log("Payment received: transaction_no=%s"%transaction_no) pay_type=context.get("type") res=get_model("sale.order").search([["transaction_no","=",transaction_no]]) if not res: print("Sales order not found for transaction_no=%s"%transaction_no) return sale_id=res[0] print("Found sales order %d for transaction_no=%s"%(sale_id,transaction_no)) sale=get_model("sale.order").browse(sale_id) if not sale.is_paid: method=sale.pay_method_id if not method: raise Exception("Missing sales order payment method") if method.type!=pay_type: raise Exception("Received sales order payment with wrong method (pmt: %s, sale: %s)"%(pay_type,method.type)) audit_log("Creating payment for sales order %s: transaction_no=%s"%(sale.number,transaction_no)) sale.payment_received(context=context) settings=get_model("ecom2.settings").browse(1) # XXX: change this if settings.ecom_return_url: url=settings.ecom_return_url+str(sale_id) else: url="/ui#name=sale&mode=form&active_id=%d"%sale_id return { "next_url": url, }
def login(self, context={}): set_active_user(None) data = context["data"] db_name = data.get("db_name") if not db_name: raise Exception("Missing db name") database.set_active_db(db_name) login = data["login"] password = data["password"] user_id = get_model("base.user").check_password(login, password) if not user_id: audit_log("Invalid login (%s)" % login) db = database.get_connection() db.commit() raise Exception("Invalid login") try: print("login ok", login) set_active_user(1) user = get_model("base.user").browse(user_id) if user.profile_id.prevent_login or not user.active: raise Exception("User not allowed to login") t = time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog": t}) profile = user.profile_id action = profile.home_action or "account_board" token = new_token(db_name, user_id) db = database.get_connection() res = db.get("SELECT * FROM pg_class WHERE relname='settings'") settings = get_model("settings").browse(1) version = settings.version mod_version = get_module_version() if version != mod_version: raise Exception("Database version (%s) is different than modules version (%s), please upgrade database before login." % ( version, mod_version)) company_id = user.company_id.id or profile.login_company_id.id if not company_id: res = get_model("company").search([["parent_id", "=", None]]) if not res: raise Exception("No company found") company_id = res[0] comp = get_model("company").browse(company_id) return { "cookies": { "dbname": database.get_active_db(), "user_id": user_id, "token": token, "user_name": user.name, "package": settings.package, "company_id": company_id, "company_name": comp.name, }, "next": { "type": "url", "url": "/ui#name=%s" % action, }, "login_action": action, } finally: set_active_user(user_id) audit_log("Login")
def get(self): self.get_argument("token") # TODO: check token dbname=database.get_active_db() db=database.get_connection() try: db.begin() set_active_user(None) user_id=1 user=get_model("base.user").browse(user_id) t=time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog":t}) comp=get_model("company").browse(1) set_active_user(user_id) audit_log("Login token") url="http://nf1.netforce.com/update_lastlogin?dbname=%s"%dbname req=urllib.request.Request(url) try: urllib.request.urlopen(req).read() except: print("ERROR: failed to update last login time") token=new_token(dbname,user_id) self.set_cookie("dbname",dbname) self.set_cookie("user_id",str(user_id)) self.set_cookie("token",token) self.set_cookie("user_name",quote(user.name)) # XXX: space self.set_cookie("company_name",quote(comp.name)) self.set_cookie("package",comp.package) self.redirect("http://%s.my.netforce.com/action#name=account_board"%dbname.replace("_","-")) db.commit() except: db.rollback()
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()
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 payment_received(self,context={}): res=super().payment_received(context=context) if res: return res transaction_no=context.get("transaction_no") audit_log("Payment received: transaction_no=%s"%transaction_no) amount=context.get("amount") currency_id=context.get("currency_id") pay_type=context.get("type") res=get_model("ecom2.cart").search([["transaction_no","=",transaction_no]]) if not res: print("Cart not found for transaction_no=%s"%transaction_no) return cart_id=res[0] print("Found cart %d for transaction_no=%s"%(cart_id,transaction_no)) cart=get_model("ecom2.cart").browse(cart_id) if cart.state=="waiting_payment": if currency_id and currency_id!=cart.currency_id.id: raise Exception("Received cart payment in wrong currency (pmt: %s, cart: %s)"%(currency_id,cart.currency_id.id)) method=cart.pay_method_id if not method: raise Exception("Missing cart payment method") if method.type!=pay_type: raise Exception("Received cart payment with wrong method (pmt: %s, cart: %s)"%(pay_type,method.type)) audit_log("Creating payment for cart %s: transaction_no=%s"%(cart.number,transaction_no)) cart.payment_received() settings=get_model("ecom2.settings").browse(1) if settings.ecom_return_url: url=settings.ecom_return_url+str(cart_id) else: url="/ui#name=ecom2_cart&mode=form&active_id=%d"%cart_id return { "next_url": url, }
def create_orders(self,ids,context={}): print("create_orders",ids) obj=self.browse(ids[0]) res=obj.create_po() num_po=res["num_orders"] res=obj.create_mo() num_mo=res["num_orders"] msg="Stock ordering: %d purchase orders and %s production orders created"%(num_po,num_mo) audit_log(msg) return { "flash": msg, }
def logout(self, context={}): print("logout1") audit_log("Logout") print("logout2") return { "cookies": { "dbname": None, "user_id": None, "user_name": None, "company_name": None, "package": None, "company_id": None, "token": None, }, "next": { "name": "login", } }
def payment_received(self, context={}): transaction_no = context.get("transaction_no") amount = context.get("amount") currency_id = context.get("currency_id") pay_type = context.get("type") res = get_model("account.invoice").search( [["transaction_no", "=", transaction_no]]) if not res: print("Invoice not found for transaction_no=%s" % transaction_no) return inv_id = res[0] print("Found invoice %d for transaction_no=%s" % (inv_id, transaction_no)) inv = get_model("account.invoice").browse(inv_id) if currency_id and currency_id != inv.currency_id.id: raise Exception( "Received invoice payment in wrong currency (pmt: %s, inv: %s)" % (currency_id, inv.currency_id.id)) method = inv.pay_method_id if not method: raise Exception("Missing invoice payment method") if method.type != pay_type: raise Exception( "Received invoice payment with wrong method (pmt: %s, inv: %s)" % (pay_type, method.type)) audit_log("Payment received: transaction_no=%s" % transaction_no) res = get_model("account.payment").search( [["transaction_no", "=", transaction_no]]) if res: audit_log("Payment already recorded: transaction_no=%s" % transaction_no) pmt_id = res[0] else: audit_log("Recording new payment: transaction_no=%s" % transaction_no) if not method.account_id: raise Exception("Missing account for payment method %s" % method.name) pmt_vals = { "type": "in", "pay_type": "invoice", "contact_id": inv.contact_id.id, "account_id": method.account_id.id, "lines": [], "company_id": inv.company_id.id, "transaction_no": transaction_no, } line_vals = { "invoice_id": inv_id, "amount": amount, } pmt_vals["lines"].append(("create", line_vals)) pmt_id = get_model("account.payment").create( pmt_vals, context={"type": "in"}) get_model("account.payment").post([pmt_id]) return { "next_url": "/ui#name=payment&mode=form&active_id=%d" % pmt_id, }
def payment_received(self,context={}): transaction_no=context.get("transaction_no") amount=context.get("amount") currency_id=context.get("currency_id") pay_type=context.get("type") res=get_model("account.invoice").search([["transaction_no","=",transaction_no]]) if not res: print("Invoice not found for transaction_no=%s"%transaction_no) return inv_id=res[0] print("Found invoice %d for transaction_no=%s"%(inv_id,transaction_no)) inv=get_model("account.invoice").browse(inv_id) if currency_id and currency_id!=inv.currency_id.id: raise Exception("Received invoice payment in wrong currency (pmt: %s, inv: %s)"%(currency_id,inv.currency_id.id)) method=inv.pay_method_id if not method: raise Exception("Missing invoice payment method") if method.type!=pay_type: raise Exception("Received invoice payment with wrong method (pmt: %s, inv: %s)"%(pay_type,method.type)) audit_log("Payment received: transaction_no=%s"%transaction_no) res=get_model("account.payment").search([["transaction_no","=",transaction_no]]) if res: audit_log("Payment already recorded: transaction_no=%s"%transaction_no) pmt_id=res[0] else: audit_log("Recording new payment: transaction_no=%s"%transaction_no) if not method.account_id: raise Exception("Missing account for payment method %s"%method.name) pmt_vals={ "type": "in", "pay_type": "invoice", "contact_id": inv.contact_id.id, "account_id": method.account_id.id, "lines": [], "company_id": inv.company_id.id, "transaction_no": transaction_no, } line_vals={ "invoice_id": inv_id, "amount": amount, } pmt_vals["lines"].append(("create",line_vals)) pmt_id=get_model("account.payment").create(pmt_vals,context={"type": "in"}) get_model("account.payment").post([pmt_id]) return { "next_url": "/ui#name=payment&mode=form&active_id=%d"%pmt_id, }
def _import_data(self, ids, context={}): obj = self.browse(ids[0]) count = 0 if obj.import_type == 'auto': if not obj.machine_id: raise Exception("Select device to import from") context = ({"machine_id": obj.machine_id.id, "date": obj.date}) count = self.import_auto(ids, context=context) else: if not obj.file: raise Exception("Please give csv file for import data") dbname = get_active_db() data = open(os.path.join("static", "db", dbname, "files", obj.file), "rb").read().decode(obj.encoding) found_delim = False for delim in (",", ";", "\t"): try: try: rd = csv.reader(StringIO(data), delimiter=delim) except: raise Exception("Invalid CSV file") headers = next(rd) headers = [h.strip() for h in headers] for h in ["id", "date"]: if not h in headers: raise Exception("Missing header: '%s'" % h) found_delim = True break except: pass if not found_delim: raise Exception("Failed to open CSV file") rows = [r for r in rd] if not rows: raise Exception("Statement is empty") formats = ["%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S", "%d/%m/%y %H:%M:%S", "%m/%d/%y %H:%M:%S"] date_fmt = None for fmt in formats: fmt_ok = True for row in rows: vals = dict(zip(headers, row)) date = vals["date"].strip() if not date: continue try: datetime.strptime(date, fmt) except: fmt_ok = False break if fmt_ok: date_fmt = fmt break if not date_fmt: raise Exception("Could not detect date format") for i, row in enumerate(rows): vals = dict(zip(headers, row)) try: date = vals["date"].strip() if not date: raise Exception("Missing date") date = datetime.strptime(date, date_fmt).strftime("%Y-%m-%d %H:%M:%S") date_in = datetime.strptime(date, date_fmt).strftime("%Y-%m-%d 00:00:00") date_out = datetime.strptime(date, date_fmt).strftime("%Y-%m-%d 23:59:59") id_employee = vals["id"].strip().replace(",", "") if not id_employee: raise Exception("missing employeeid") attendance_id = get_model("hr.employee").search([["attendance_id", "=", id_employee]]) if attendance_id: employee = get_model("hr.employee").browse(attendance_id)[0] have_id = [] have_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", "=", date]]) check = False if not have_id: bf_id = [] bf_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", ">=", date_in], ["time", "<=", date_out], ["time", "<", date]]) if not bf_id: action = "sign_in" elif bf_id: attend = get_model("hr.attendance").browse(bf_id)[0] date_get = datetime.strptime(attend.time, date_fmt) dt = date_get + timedelta(minutes=1) date_check = datetime.strptime(str(dt), date_fmt).strftime("%Y-%m-%d %H:%M:%S") if date <= date_check: check = True if attend.action == "sign_out": action = "sign_in" elif attend.action == "sign_in": action = "sign_out" if check is False: count += 1 vals = { "time": date, "employee_id": employee.id, "action": action, } get_model("hr.attendance").create(vals) except Exception as e: audit_log("Failed to get attendance orders", details=e) raise Exception("Error on line %d (%s)" % (i + 2, e)) return { "next": { "name": "attend", "mode": "list", }, "flash": "Import : %s records" % (count) }
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()
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()
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()
def login(self, context={}): set_active_user(None) data = context["data"] db_name = data.get("db_name") if not db_name: raise Exception("Missing db name") database.set_active_db(db_name) login = data["login"] password = data["password"] user_id = get_model("base.user").check_password(login, password) if not user_id: audit_log("Invalid login (%s)" % login) db = database.get_connection() db.commit() raise Exception("Invalid login") try: print("login ok", login) set_active_user(1) user = get_model("base.user").browse(user_id) if user.profile_id.prevent_login or not user.active: raise Exception("User not allowed to login") t = time.strftime("%Y-%m-%d %H:%M:%S") user.write({"lastlog": t}) profile = user.profile_id action = profile.home_action or "account_board" token = new_token(db_name, user_id) db = database.get_connection() res = db.get("SELECT * FROM pg_class WHERE relname='settings'") settings = get_model("settings").browse(1) version = settings.version mod_version = get_module_version_name() if version != mod_version: raise Exception( "Database version (%s) is different than modules version (%s), please upgrade database before login." % (version, mod_version)) company_id = user.company_id.id or profile.login_company_id.id if not company_id: res = get_model("company").search([["parent_id", "=", None]]) if not res: raise Exception("No company found") company_id = res[0] comp = get_model("company").browse(company_id) return { "cookies": { "dbname": database.get_active_db(), "user_id": user_id, "token": token, "user_name": user.name, "package": settings.package, "company_id": company_id, "company_name": comp.name, }, "next": { "type": "url", "url": "/ui#name=%s" % action, }, "login_action": action, } finally: set_active_user(user_id) audit_log("Login")
def _import_data(self, ids, context={}): obj = self.browse(ids[0]) count = 0 if obj.import_type == 'auto': if not obj.machine_id: raise Exception("Select device to import from") context = ({"machine_id": obj.machine_id.id, "date": obj.date}) count = self.import_auto(ids, context=context) else: if not obj.file: raise Exception("Please give csv file for import data") dbname = get_active_db() data = open( os.path.join("static", "db", dbname, "files", obj.file), "rb").read().decode(obj.encoding) found_delim = False for delim in (",", ";", "\t"): try: try: rd = csv.reader(StringIO(data), delimiter=delim) except: raise Exception("Invalid CSV file") headers = next(rd) headers = [h.strip() for h in headers] for h in ["id", "date"]: if not h in headers: raise Exception("Missing header: '%s'" % h) found_delim = True break except: pass if not found_delim: raise Exception("Failed to open CSV file") rows = [r for r in rd] if not rows: raise Exception("Statement is empty") formats = [ "%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S", "%d/%m/%y %H:%M:%S", "%m/%d/%y %H:%M:%S" ] date_fmt = None for fmt in formats: fmt_ok = True for row in rows: vals = dict(zip(headers, row)) date = vals["date"].strip() if not date: continue try: datetime.strptime(date, fmt) except: fmt_ok = False break if fmt_ok: date_fmt = fmt break if not date_fmt: raise Exception("Could not detect date format") for i, row in enumerate(rows): vals = dict(zip(headers, row)) try: date = vals["date"].strip() if not date: raise Exception("Missing date") date = datetime.strptime( date, date_fmt).strftime("%Y-%m-%d %H:%M:%S") date_in = datetime.strptime( date, date_fmt).strftime("%Y-%m-%d 00:00:00") date_out = datetime.strptime( date, date_fmt).strftime("%Y-%m-%d 23:59:59") id_employee = vals["id"].strip().replace(",", "") if not id_employee: raise Exception("missing employeeid") attendance_id = get_model("hr.employee").search( [["attendance_id", "=", id_employee]]) if attendance_id: employee = get_model("hr.employee").browse( attendance_id)[0] have_id = [] have_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", "=", date]]) check = False if not have_id: bf_id = [] bf_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", ">=", date_in], ["time", "<=", date_out], ["time", "<", date]]) if not bf_id: action = "sign_in" elif bf_id: attend = get_model("hr.attendance").browse( bf_id)[0] date_get = datetime.strptime( attend.time, date_fmt) dt = date_get + timedelta(minutes=1) date_check = datetime.strptime( str(dt), date_fmt).strftime("%Y-%m-%d %H:%M:%S") if date <= date_check: check = True if attend.action == "sign_out": action = "sign_in" elif attend.action == "sign_in": action = "sign_out" if check is False: count += 1 vals = { "time": date, "employee_id": employee.id, "action": action, } get_model("hr.attendance").create(vals) except Exception as e: audit_log("Failed to get attendance orders", details=e) raise Exception("Error on line %d (%s)" % (i + 2, e)) return { "next": { "name": "attend", "mode": "list", }, "flash": "Import : %s records" % (count) }
def import_auto(self, ids, context={}): obj = self.browse(ids)[0] date = context.get('date', datetime.today()) lines = obj.get_data(context=context) current_date = datetime.today() date_in = date.strftime("%Y-%m-%d 00:00:00") date_out = current_date.strftime("%Y-%m-%d 23:59:59") count = 0 detail = [] st = "" for line in lines: if line: st += line.replace("\t", ",") st += '\n' line = line.split('\t') if len(line) > 1: if line[1] >= date_in and line[1] <= date_out: attendance_id = get_model("hr.employee").search( [["attendance_id", "=", line[0]]]) dt_time = datetime.strptime(str(line[1]), "%Y-%m-%d %H:%M:%S") dt_in = dt_time.strftime("%Y-%m-%d 00:00:00") dt_out = dt_time.strftime("%Y-%m-%d 23:59:59") if attendance_id: employee = get_model("hr.employee").browse( attendance_id)[0] have = [] have = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", "=", line[1]]]) check = False if not have: bf_id = [] bf_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", ">=", dt_in], ["time", "<=", dt_out], ["time", "<", line[1]]]) if not bf_id: action = "sign_in" elif bf_id: attend = get_model("hr.attendance").browse( bf_id)[0] date_get = datetime.strptime( attend.time, "%Y-%m-%d %H:%M:%S") dt = date_get + timedelta(minutes=1) date_check = datetime.strptime( str(dt), "%Y-%m-%d %H:%M:%S").strftime( "%Y-%m-%d %H:%M:%S") if line[1] <= date_check: check = True if attend.action == "sign_out": action = "sign_in" elif attend.action == "sign_in": action = "sign_out" if check is False: count += 1 detail.append({ "name": employee.first_name + " " + employee.last_name, "date": line[1], "action": action }) vals = { "employee_id": employee.id, "time": line[1], "action": action, } get_model("hr.attendance").create(vals) audit_log("Add attendance %s record at %s employee: %s " % (count, date, str(detail))) open("/tmp/res.csv", "w").write(st) # XXX return count
def import_auto(self, ids, context={}): obj = self.browse(ids)[0] date = context.get('date', datetime.today()) lines = obj.get_data(context=context) current_date = datetime.today() date_in = date.strftime("%Y-%m-%d 00:00:00") date_out = current_date.strftime("%Y-%m-%d 23:59:59") count = 0 detail = [] st = "" for line in lines: if line: st += line.replace("\t", ",") st += '\n' line = line.split('\t') if len(line) > 1: if line[1] >= date_in and line[1] <= date_out: attendance_id = get_model("hr.employee").search([["attendance_id", "=", line[0]]]) dt_time = datetime.strptime(str(line[1]), "%Y-%m-%d %H:%M:%S") dt_in = dt_time.strftime("%Y-%m-%d 00:00:00") dt_out = dt_time.strftime("%Y-%m-%d 23:59:59") if attendance_id: employee = get_model("hr.employee").browse(attendance_id)[0] have = [] have = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", "=", line[1]]]) check = False if not have: bf_id = [] bf_id = get_model("hr.attendance").search( [["employee_id", "=", employee.id], ["time", ">=", dt_in], ["time", "<=", dt_out], ["time", "<", line[1]]]) if not bf_id: action = "sign_in" elif bf_id: attend = get_model("hr.attendance").browse(bf_id)[0] date_get = datetime.strptime(attend.time, "%Y-%m-%d %H:%M:%S") dt = date_get + timedelta(minutes=1) date_check = datetime.strptime( str(dt), "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S") if line[1] <= date_check: check = True if attend.action == "sign_out": action = "sign_in" elif attend.action == "sign_in": action = "sign_out" if check is False: count += 1 detail.append( {"name": employee.first_name + " " + employee.last_name, "date": line[1], "action": action}) vals = { "employee_id": employee.id, "time": line[1], "action": action, } get_model("hr.attendance").create(vals) audit_log("Add attendance %s record at %s employee: %s " % (count, date, str(detail))) open("/tmp/res.csv", "w").write(st) # XXX return count