def get_rate(self, ids, date=None, rate_type="buy", context={}): obj_id = ids[0] dbname = database.get_active_db() company_id = access.get_active_company() key = (dbname, company_id, obj_id, date, rate_type) if key in _cache and not context.get("no_cache"): return _cache[key] obj = self.browse(obj_id) res = None for rate in obj.rates: if rate.company_id.id != company_id: continue if date and rate.date > date: continue if rate_type == "buy": res = rate.buy_rate break else: res = rate.sell_rate break if res is None: for rate in obj.rates: if date and rate.date > date: continue if rate_type == "buy": res = rate.buy_rate break else: res = rate.sell_rate break _cache[key] = res return res
def create_thumbnails(self,ids,context={}): print("Product.create_thumbnails",ids) for obj in self.browse(ids): if not obj.image: continue dbname = database.get_active_db() if not dbname: return None fdir = os.path.join(os.getcwd(), "static", "db", dbname, "files") path=os.path.join(fdir,obj.image) basename,ext=os.path.splitext(obj.image) res = "," in basename if not res: rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(obj.image) basename, ext = res fname2 = basename + "," + rand + ext #rename image dest_path=fdir+"/"+fname2 print("destination path and file name ",dest_path) cmd="cp %s %s"%(path, dest_path) os.system(cmd) obj.write({ 'image': fname2, }) utils.create_thumbnails(fname2) else: print ("called",obj.image) utils.create_thumbnails(obj.image)
def cal_dimension(self, ids, context={}): all_vals = {} dbname = database.get_active_db() for obj in self.browse(ids): master_img = obj.product_id.image master_path = os.path.join("static/db/", dbname, "files", master_img) frame = int(obj.get("rotate_frame")) column = int(obj.get("rotate_footage")) row = 1 if frame and column: row = frame / column vals = {} im_path = obj.image if im_path and frame and column: filename = os.path.join("static/db/", dbname, "files", im_path) img = Image.open(filename) (width, height) = img.size swidth = math.floor(width / column) sheight = math.floor(height / row) vals["rotate_width"] = swidth vals["rotate_height"] = sheight vals["master_image"] = master_path all_vals[obj.id] = vals else: print("Not enough arguments given") return all_vals
def _get_cache(self): global _cache dbname = get_active_db() cache = _cache.get(dbname) if cache is None: cache = self._load_cache() return cache
def get_ratio(self, uom_id): dbname = database.get_active_db() if (dbname, uom_id) in _cache: return _cache[(dbname, uom_id)] obj = self.browse(uom_id) _cache[(dbname, uom_id)] = obj.ratio return obj.ratio
def generals(self, params,context={}): print_color("interface.generals.params%s" % params, "yellow") company_id = params.get("company_id") cashier_id = params.get("cashier_id") url = params.get("url") cashier_name = None if cashier_id: cs = get_model("pos.register").browse(int(cashier_id)) cashier_name = cs.name theme = 'blue' if company_id: for c in get_model("pos.shop").search_browse([['company_id','=',company_id]]): theme = c.theme st = get_model("settings").browse(1) pos_st = get_model("pos.settings").browse(1) version=st.version menu=[ {'key': 'current_sale', 'value' : 'Current Sale', 'active' : False}, {'key': 'retreive_sale', 'value' : 'Retreive Sale', 'active' : False}, {'key': 'complete_sale', 'value' : 'Complete Sale', 'active' : False}, ] for m in menu: if m['key'] == url: m['active']=True return { 'version' : version, 'pos_theme' : pos_st.pos_theme, 'theme' : theme, 'dbname': get_active_db(), 'cashier_name':cashier_name, 'menu':menu }
def get_rate(self, ids, date=None, rate_type="buy", context={}): obj_id = ids[0] if not obj_id: return dbname = database.get_active_db() company_id = access.get_active_company() key = (dbname, company_id, obj_id, date, rate_type) if key in _cache and not context.get("no_cache"): return _cache[key] obj = self.browse(obj_id) res = None for rate in obj.rates: if rate.company_id.id != company_id: continue if date and rate.date > date: continue if rate_type == "buy": res = rate.buy_rate break else: res = rate.sell_rate break if res is None: for rate in obj.rates: if date and rate.date > date: continue if rate_type == "buy": res = rate.buy_rate break else: res = rate.sell_rate break _cache[key] = res return res
def export_static_files(self, ids, context={}): obj = self.browse(ids)[0] theme = obj.name dbname = get_active_db() if obj.file: zip_path = utils.get_file_path(obj.file) zf = zipfile.ZipFile(zip_path) for n in zf.namelist(): if not n.startswith("static/"): continue if n[-1] == "/": continue n2 = n[7:] if n2.find("..") != -1: continue data = zf.read(n) f_path = "static/db/" + dbname + "/themes/" + theme + "/" + n2 dir_path = os.path.dirname(f_path) if not os.path.exists(dir_path): os.makedirs(dir_path) print("export file", f_path) open(f_path, "wb").write(data) else: export_module_file_all("themes/" + theme + "/static", "static/db/" + dbname + "/themes/" + theme)
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 create_thumbnails(self, ids, context={}): print("Product.create_thumbnails", ids) for obj in self.browse(ids): if not obj.image: continue dbname = database.get_active_db() if not dbname: return None fdir = os.path.join(os.getcwd(), "static", "db", dbname, "files") path = os.path.join(fdir, obj.image) basename, ext = os.path.splitext(obj.image) res = "," in basename if not res: rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(obj.image) basename, ext = res fname2 = basename + "," + rand + ext #rename image dest_path = fdir + "/" + fname2 print("destination path and file name ", dest_path) cmd = "cp %s %s" % (path, dest_path) os.system(cmd) obj.write({ 'image': fname2, }) utils.create_thumbnails(fname2) else: print("called", obj.image) utils.create_thumbnails(obj.image)
def get(self): raise Exception("Polling is disabled") # XXX #print("ListenPoll.get",os.getpid()) global sending_notifs t=time.strftime("%Y-%m-%d %H:%M:%S") dbname=get_active_db() if not dbname: raise Exception("Missing dbname in long poll request") db=None try: db=get_connection() user_id=self.get_cookie("user_id",None) if user_id: user_id=int(user_id) res=db.get("INSERT INTO ws_listener (user_id,last_check_time) VALUES (%s,%s) RETURNING id",user_id,t) self.listener_id=res.id self.dbname=dbname listen_handlers[self.listener_id]=self if not sending_notifs: io_loop=tornado.ioloop.IOLoop.instance() io_loop.add_timeout(time.time()+POLL_WAIT,send_notifs) # XXX: should start this directly when process is started? sending_notifs=True db.commit() except: print("#########################################################") print("ERROR: ListenPoll.get failed") if db: db.rollback() import traceback 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() 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 post(self): fname = self.get_argument("filename", None) print(">>> upload %s" % fname) if self.request.headers.get("Content-Type") == "image/jpeg": data = self.request.body else: info = self.request.files["file"] data = info[0]["body"] if not fname: fname = info[0]["filename"] print("data size: %s" % len(data)) rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(fname) basename, ext = res fname2 = basename + "," + rand + ext dbname = get_active_db() fdir = os.path.join("static", "db", dbname, "files") if not os.path.exists(fdir): os.makedirs(fdir) path = os.path.join(fdir, fname2) open(path, "wb").write(data) self.write(fname2) if ext.lower() in (".jpg", ".jpeg", ".png", ".gif"): fname3 = basename + "-resize-256" + "," + rand + ext path_thumb = os.path.join(fdir, fname3) os.system(r"convert -resize 256x256\> '%s' '%s'" % (path, path_thumb)) fname4 = basename + "-resize-512" + "," + rand + ext path_thumb2 = os.path.join(fdir, fname4) os.system(r"convert -resize 512x512\> '%s' '%s'" % (path, path_thumb2)) fname5 = basename + "-resize-128" + "," + rand + ext path_thumb3 = os.path.join(fdir, fname5) os.system(r"convert -resize 128x128\> '%s' '%s'" % (path, path_thumb3)) print("<<< upload %s" % fname)
def _replace(m): cid = m.group(1) cid = "<" + cid + ">" if cid not in content_ids: return m.group(0) fname = content_ids[cid][0] dbname = get_active_db() return "/static/db/" + dbname + "/files/" + fname
def _file_path(data, val, options={}): if val is None: return "" try: dbname = database.get_active_db() return "/static/db/" + dbname + "/files/" + val except: return val
def get_file_path(fname): if not fname: return None dbname = database.get_active_db() if not dbname: return None path = os.path.join(os.getcwd(), "static", "db", dbname, "files", fname) return path
def get_ratio(self, uom_id, context={}): dbname = database.get_active_db() if not context.get("no_cache"): if (dbname, uom_id) in _cache: return _cache[(dbname, uom_id)] obj = self.browse(uom_id) if not context.get("no_cache"): _cache[(dbname, uom_id)] = obj.ratio return obj.ratio
def prepare(self): print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print("prepare") super(BaseController, self).prepare() website_id = self.request.headers.get("X-Website-ID") if website_id: website_id = int(website_id) else: res = get_model("website").search([["state", "=", "active"]]) if not res: raise Exception("No website found") website_id = res[0] self.website_id = website_id website = get_model("website").browse(website_id) template.set_active_theme(website.theme_id.id) browse_ctx = { "website_id": website.id, "theme_id": website.theme_id.id, "sale_channel_id": website.sale_channel_id.id, "pricelist_id": website.sale_channel_id.pricelist_id.id if website.sale_channel_id else None, } lang = self.get_argument("set_lang", None) if lang: set_active_locale(lang) self.set_cookie("locale", lang) ctx = {} ctx["website"] = website ctx["database"] = get_active_db() ctx["locale"] = get_active_locale() ctx["ga_script"] = website.ga_script ctx["linklists"] = get_model("cms.linklist").search_browse([]) ctx["product_groups"] = get_model("product.group").search_browse( [], context=browse_ctx) ctx["countries"] = get_model("country").search_browse([]) # XXX cart_id = self.get_cookie("cart_id", None) if cart_id: cart_id = int(cart_id) res = get_model("ecom.cart").search([["id", "=", cart_id]]) if res: ctx["cart"] = get_model("ecom.cart").browse(cart_id) else: # handle invalid cart_id cookie self.clear_cookie("cart_id") user_id = self.get_cookie("user_id", None) if user_id: user_id = int(user_id) user = get_model("base.user").browse(user_id) ctx["customer"] = user.contact_id offset = self.get_argument("offset", None) if offset: ctx["offset"] = int(offset) ctx["url"] = self.request.uri self.context = ctx
def view_link(self, ids, context={}): obj = self.browse(ids)[0] uuid = obj.uuid dbname = get_active_db() return { "next": { "type": "url", "url": "/view_quot?dbname=%s&uuid=%s" % (dbname, uuid), } }
def emit(self, record): msg = self.format(record) dbname = database.get_active_db() if dbname: dir_path = os.path.join("static", "db", dbname, "log") if not os.path.exists(dir_path): os.makedirs(dir_path) day = time.strftime("%Y-%m-%d") log_path = os.path.join(dir_path, "netforce-rpc-%s.log" % day) open(log_path, "a").write(msg + "\n")
def gen_qrcode(self, id, password): print("GENERATE QRCODE!") link=HOST+"/inspectionreport/checkqr?id=%s&password=%s"%(id, password) url=pyqrcode.create(link) fname="%s.png"%(id) dbname=get_active_db() path="static/db/"+dbname+"/files" fpath=path+"/"+fname url.png(fpath,scale=8) print("FNAME => ", fname) return fname
def _load_cache(self): global _cache dbname = get_active_db() print("Loading translations (%s)" % dbname) db = get_connection() res = db.query( "SELECT t.original,l.code AS lang,t.translation FROM translation t, language l WHERE t.lang_id=l.id") cache = {} for r in res: cache[(r.original, r.lang)] = r.translation _cache[dbname] = cache return cache
def report_render_to_file(model, ids, method="get_report_data", template=None, template_format=None, out_format="pdf", context={}): print("report_render_to_file", model, ids, method, template, template_format, out_format) m = get_model(model) f = getattr(m, method, None) if not f: raise Exception("Invalid method %s of %s" % (method, model)) if template_format in ("odt", "jrxml", "docx"): # XXX: deprecated ctx = { "ids": ids, "refer_id": ids[0], } in_data = f(context=ctx) else: in_data = f(ids, context=context) if template_format == "odt": # XXX: deprecated out_data = report_render_odt(template, in_data) if out_format == "pdf": out_data = convert_to_pdf(out_data, "odt") elif template_format == "odt2": out_data = report_render_odt(template, in_data) if out_format == "pdf": out_data = convert_to_pdf(out_data, "odt") elif template_format == "docx": # XXX: deprecated out_data = report_render_doc(template, in_data) if out_format == "pdf": out_data = convert_to_pdf(out_data, "docx") elif template_format == "jrxml": # XXX: deprecated out_data = get_report(template, in_data, format=out_format) elif template_format == "jrxml2": out_data = get_report(template, in_data, format=out_format) else: raise Exception("Invalid template format: %s" % template_format) fname = "%s.%s" % (template, out_format) rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(fname) fname2 = res[0] + "," + rand + res[1] dbname = database.get_active_db() fdir = os.path.join("static", "db", dbname, "files") if not os.path.exists(fdir): os.makedirs(fdir) path = os.path.join(fdir, fname2) f = open(path, "wb") f.write(out_data) f.close() return fname2
def do_import(self, ids, context={}): obj = self.browse(ids[0]) dbname = get_active_db() data = open(os.path.join("static", "db", dbname, "files", obj.file), "rU", errors="replace").read() m = get_model(obj.model) m.import_data(data) if obj.next: return { "next": { "name": obj.next, }, "flash": "Data imported successfully", }
def create_thumbnails(fname): print("create_thumbnails", fname) dbname = database.get_active_db() if not dbname: return None fdir = os.path.join(os.getcwd(), "static", "db", dbname, "files") path = os.path.join(fdir, fname) basename, ext = os.path.splitext(fname) fname, rand = basename.split(",") for s in [512, 256, 128, 64, 32]: fname_thumb = fname + "-resize-%s" % s + "," + rand + ext path_thumb = os.path.join(fdir, fname_thumb) os.system(r"convert -resize %sx%s\> '%s' '%s'" % (s, s, path, path_thumb))
def login(self,email,password,context={}): print("EcomInterface.login",email,password) user_id=get_model("base.user").check_password(email,password) if not user_id: raise Exception("Invalid login") user=get_model("base.user").browse(user_id) contact=user.contact_id dbname=database.get_active_db() return { "user_id": user_id, "token": utils.new_token(dbname,user_id), "contact_id": contact.id, }
def prepare(self): print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print("prepare") super(BaseController,self).prepare() website_id=self.request.headers.get("X-Website-ID") if website_id: website_id=int(website_id) else: res=get_model("website").search([["state","=","active"]]) if not res: raise Exception("No website found") website_id=res[0] self.website_id=website_id website=get_model("website").browse(website_id) template.set_active_theme(website.theme_id.id) browse_ctx={ "website_id": website.id, "theme_id": website.theme_id.id, "sale_channel_id": website.sale_channel_id.id, "pricelist_id": website.sale_channel_id.pricelist_id.id if website.sale_channel_id else None, } lang=self.get_argument("set_lang",None) if lang: set_active_locale(lang) self.set_cookie("locale",lang) ctx={} ctx["website"]=website ctx["database"]=get_active_db() ctx["locale"]=get_active_locale() ctx["ga_script"]=website.ga_script ctx["linklists"]=get_model("cms.linklist").search_browse([]) ctx["product_groups"]=get_model("product.group").search_browse([],context=browse_ctx) ctx["countries"]=get_model("country").search_browse([]) # XXX cart_id=self.get_cookie("cart_id",None) if cart_id: cart_id=int(cart_id) res=get_model("ecom.cart").search([["id","=",cart_id]]) if res: ctx["cart"]=get_model("ecom.cart").browse(cart_id) else: # handle invalid cart_id cookie self.clear_cookie("cart_id") user_id=self.get_cookie("user_id",None) if user_id: user_id=int(user_id) user=get_model("base.user").browse(user_id) ctx["customer"]=user.contact_id offset=self.get_argument("offset",None) if offset: ctx["offset"]=int(offset) ctx["url"]=self.request.uri self.context=ctx
def post(self): db = get_connection() try: try: print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print(self.request.protocol) print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") fields = ["email", "password"] field_errors = {} form_vals = {} for n in fields: v = self.get_argument(n, None) form_vals[n] = v if not v: field_errors[n] = True if field_errors: raise Exception("Some required fields are missing") user_id = get_model("base.user").check_password( form_vals["email"], form_vals["password"]) if not user_id: raise Exception("Invalid login") set_active_user(user_id) dbname = get_active_db() token = new_token(dbname, user_id) self.set_cookie("user_id", str(user_id)) self.set_cookie("token", token) cart_id = self.get_cookie("cart_id") if cart_id: cart_id = int(cart_id) get_model("ecom.cart").set_default_address([cart_id]) db.commit() url = self.get_argument("return_url", None) if not url: url = "/cms_account" self.redirect(url) except Exception as e: db = get_connection() error_message = str(e) ctx = self.context ctx["form_vals"] = form_vals ctx["error_message"] = error_message ctx["field_errors"] = field_errors content = render("cms_login", ctx) ctx["content"] = content html = render("cms_layout", ctx) self.write(html) db.commit() except: import traceback traceback.print_exc() db.rollback()
def _file_path(this, context, thumbnail=None): if context is None: return "" try: dbname = database.get_active_db() if thumbnail: basename, ext = os.path.splitext(context) basename2, _, rand = basename.rpartition(",") fname = basename2 + "-resize-256," + rand + ext else: fname = context return "/static/db/" + dbname + "/files/" + fname except: return ""
def sign_up(self,vals,context={}): print("EcomInterface.sign_up",vals,context) res=get_model("base.user").search([["email","=",vals["email"]]]) if res: raise Exception("User already exists with same email") res=get_model("contact").search([["email","=",vals["email"]]]) if res: raise Exception("Contact already exists with same email") cont_vals={ "first_name": vals["first_name"], "last_name": vals["last_name"], "email": vals["email"], "customer":True, } contact_id=get_model("contact").create(cont_vals) res=get_model("profile").search([["code","=","ECOM_CUSTOMER"]]) if not res: raise Exception("Customer user profile not found") profile_id=res[0] user_vals={ "name": "%s %s"%(vals["first_name"],vals["last_name"]), "login": vals["email"], "profile_id": profile_id, "contact_id": contact_id, "password": vals["password"], } user_id=get_model("base.user").create(user_vals) addr_vals = { "first_name": vals["first_name"], "last_name": vals["last_name"], "province_id": vals["province_id"], "type": "billing", "postal_code" : vals["postal_code_id"], "address": vals["address"], "contact_id": contact_id, "mobile": vals["mobile"], "instructions_messenger" :vals['messenger'], } if vals.get("subdistrict_id"): subdistrict_id = vals["subdistrict_id"] if subdistrict_id: addr_vals['subdistrict_id'] = subdistrict_id get_model("address").create(addr_vals) get_model("contact").trigger([contact_id],"ecom_sign_up") dbname=database.get_active_db() return { "user_id": user_id, "token": utils.new_token(dbname,user_id), "contact_id" : contact_id, }
def post(self): db=get_connection() try: try: print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") print(self.request.protocol) print("CHECK protocol XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") fields=["email","password"] field_errors={} form_vals={} for n in fields: v=self.get_argument(n,None) form_vals[n]=v if not v: field_errors[n]=True if field_errors: raise Exception("Some required fields are missing") user_id=get_model("base.user").check_password(form_vals["email"],form_vals["password"]) if not user_id: raise Exception("Invalid login") set_active_user(user_id) dbname=get_active_db() token=new_token(dbname,user_id) self.set_cookie("user_id",str(user_id)) self.set_cookie("token",token) cart_id=self.get_cookie("cart_id") if cart_id: cart_id=int(cart_id) get_model("ecom.cart").set_default_address([cart_id]) db.commit() url=self.get_argument("return_url",None) if not url: url="/cms_account" self.redirect(url) except Exception as e: db=get_connection() error_message=str(e) ctx=self.context ctx["form_vals"]=form_vals ctx["error_message"]=error_message ctx["field_errors"]=field_errors content=render("cms_login",ctx) ctx["content"]=content html=render("cms_layout",ctx) self.write(html) db.commit() except: import traceback traceback.print_exc() db.rollback()
def get(self): db = get_connection() if db: db.begin() ctx = { "dbname": get_active_db(), "locale": netforce.locale.get_active_locale(), "css_file": static.get_css_file(), "js_file": static.get_js_file(), } static.check_ui_params_db() html = netforce.template.render("action_local", {"context": ctx}) self.write(html) db = get_connection() if db: db.commit() # XXX
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)
def post(self): info = self.request.files["upload"] fname = info[0]["filename"] print(">>> ck_upload %s" % fname) data = info[0]["body"] print("data size: %s" % len(data)) rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(fname) fname2 = res[0] + "," + rand + res[1] dbname = get_active_db() fdir = os.path.join("static", "db", dbname, "files") if not os.path.exists(fdir): os.makedirs(fdir) open(os.path.join(fdir, fname2), "wb").write(data) func = self.get_argument("CKEditorFuncNum") url = "/static/db/%s/files/%s" % (dbname, fname2) self.write("<script>window.parent.CKEDITOR.tools.callFunction(%s,\"%s\");</script>" % (func, url)) print("<<< ck_upload %s" % fname)
def post(self): self.set_header("Access-Control-Allow-Origin", "*") fname = self.get_argument("filename", None) print(">>> upload %s" % fname) if self.request.headers.get("Content-Type") == "image/jpeg": data = self.request.body else: info = self.request.files["file"] data = info[0]["body"] if not fname: fname = info[0]["filename"] print("data size: %s" % len(data)) rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(fname) basename, ext = res fname2 = basename + "," + rand + ext dbname = get_active_db() fdir = os.path.join("static", "db", dbname, "files") if not os.path.exists(fdir): os.makedirs(fdir) path = os.path.join(fdir, fname2) open(path, "wb").write(data) self.write(fname2) if ext.lower() in (".jpg", ".jpeg", ".png", ".gif"): fname4 = basename + "-resize-512" + "," + rand + ext path_thumb2 = os.path.join(fdir, fname4) os.system(r"convert -resize 512x512\> '%s' '%s'" % (path, path_thumb2)) fname3 = basename + "-resize-256" + "," + rand + ext path_thumb = os.path.join(fdir, fname3) os.system(r"convert -resize 256x256\> '%s' '%s'" % (path, path_thumb)) fname5 = basename + "-resize-128" + "," + rand + ext path_thumb3 = os.path.join(fdir, fname5) os.system(r"convert -resize 128x128\> '%s' '%s'" % (path, path_thumb3)) fname6 = basename + "-resize-64" + "," + rand + ext path_thumb6 = os.path.join(fdir, fname6) os.system(r"convert -resize 64x64\> '%s' '%s'" % (path, path_thumb6)) fname7 = basename + "-resize-32" + "," + rand + ext path_thumb7 = os.path.join(fdir, fname7) os.system(r"convert -resize 32x32\> '%s' '%s'" % (path, path_thumb7)) print(fname4,fname3,fname5,fname6,fname7) print (path_thumb2,path_thumb,path_thumb3,path_thumb6) print("<<< upload %s" % fname)
def post(self): info = self.request.files["upload"] fname = info[0]["filename"] print(">>> ck_upload %s" % fname) data = info[0]["body"] print("data size: %s" % len(data)) rand = base64.urlsafe_b64encode(os.urandom(8)).decode() res = os.path.splitext(fname) fname2 = res[0] + "," + rand + res[1] dbname = get_active_db() fdir = os.path.join("static", "db", dbname, "files") if not os.path.exists(fdir): os.makedirs(fdir) open(os.path.join(fdir, fname2), "wb").write(data) func = self.get_argument("CKEditorFuncNum") url = "/static/db/%s/files/%s" % (dbname, fname2) self.write( "<script>window.parent.CKEDITOR.tools.callFunction(%s,\"%s\");</script>" % (func, url)) print("<<< ck_upload %s" % fname)
def get_block(self, name, page_id=None, post_id=None, context={}): # print("get_block",name,page_id,post_id) dbname = get_active_db() lang = get_active_locale() key = (dbname, name, page_id, post_id, lang) if key in _block_cache: #print("...cache hit") return _block_cache[key] #print("...cache miss") cond = [["name", "=", name]] if page_id: cond.append(["related_id", "=", "cms.page,%d" % page_id]) if post_id: cond.append(["related_id", "=", "cms.blog.post,%d" % post_id]) res = self.search(cond) if res: block = self.read(res, ["html"])[0] else: block = None _block_cache[key] = block return block
def get_template(name): dbname=database.get_active_db() key=(dbname,_active_theme_id,name) tmpl=_template_cache.get(key) if tmpl: return tmpl tmpl_src = get_module_template_src(name) if tmpl_src is None: tmpl_src=get_db_template_src(name) if tmpl_src is None: raise Exception("Template not found: %s (active_theme_id=%s)" % (name,_active_theme_id)) try: compiler = hbs_compiler.Compiler() py_src = compiler.compile(tmpl_src) tmpl = Template() exec(py_src, tmpl.__dict__) except Exception as e: print("Template source:") print(tmpl_src) raise Exception("Failed to compile template: %s" % name) _template_cache[key] = tmpl return tmpl
def export_zip(self, ids, context={}): t = time.strftime("%Y-%m-%dT%H:%M:%S") if len(ids) == 1: obj = self.browse(ids)[0] fname = obj.name + "-" + t + ".zip" else: fname = "modules-" + t + ".zip" dbname = database.get_active_db() fdir = "static/db/" + dbname + "/files" if not os.path.exists(fdir): os.makedirs(fdir) zpath = fdir + "/" + fname zf = zipfile.ZipFile(zpath, "w") for obj in self.browse(ids): vals = OrderedDict() vals["name"] = obj.name if obj.description: vals["description"] = obj.description if obj.version: vals["version"] = obj.version if obj.author: vals["author"] = obj.author data = json.dumps(vals, indent=4, separators=(',', ': ')) path = obj.name + "/module.json" zf.writestr(path, data) for action in obj.actions: vals = OrderedDict() vals["name"] = action.name if action.view: vals["view"] = action.view if action.string: vals["string"] = action.string if action.model_id: vals["model"] = action.model_id.name if action.view_layout_id: vals["view_layout"] = action.view_layout_id.name if action.menu_id: vals["menu"] = action.menu_id.name if action.options: vals["options"] = json.loads(action.options) data = json.dumps(vals, indent=4, separators=(',', ': ')) path = obj.name + "/actions/" + action.name + ".json" zf.writestr(path, data) for layout in obj.view_layouts: root = etree.fromstring(layout.layout) if layout.model_id: root.attrib["model"] = layout.model_id.name if layout.inherit: root.attrib["inherit"] = layout.inherit data = etree.tostring(root, pretty_print=True) path = obj.name + "/layouts/" + layout.name + ".xml" zf.writestr(path, data) for template in obj.templates: data = template.template path = obj.name + "/templates/" + template.name + ".hbs" zf.writestr(path, data) for model in obj.models: root = etree.Element("model") root.attrib["name"] = model.name if model.string: root.attrib["string"] = model.string if model.order: root.attrib["order"] = model.order for field in model.fields: if field.module_id and field.module_id.id != obj.id: continue el = etree.SubElement(root, "field") el.attrib["name"] = field.name el.attrib["string"] = field.string el.attrib["type"] = field.type if field.relation_id: el.attrib["relation"] = field.relation_id.name if field.relfield_id: el.attrib["relfield"] = field.relfield_id.name if field.selection: el.attrib["selection"] = field.selection if field.required: el.attrib["required"] = "1" if field.readonly: el.attrib["readonly"] = "1" if field.search: el.attrib["search"] = "1" if field.function: el.attrib["function"] = field.function if field.default: el.attrib["default"] = field.default if field.condition: el.attrib["condition"] = field.condition data = etree.tostring(root, pretty_print=True) path = obj.name + "/models/" + model.name.replace(".", "_") + ".xml" zf.writestr(path, data) for script in obj.scripts: if script.language == "js": path = obj.name + "/scripts/" + script.name + ".js" elif script.language == "py": path = obj.name + "/scripts/" + script.name + ".py" else: raise Exception("Invalid language in script %s" % script.name) zf.writestr(path, script.code) zf.close() return { "next": { "type": "download", "url": zpath, } }
def import_data(self, ids, context={}): obj = self.browse(ids[0]) acc_id = obj.account_id.id 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 [ "Date", "Description", "Spent", "Received", "Balance" ]: 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", "%d/%m/%Y", "%m/%d/%Y", "%d/%m/%y", "%m/%d/%y", "%d-%m-%y", "%m-%d-%y" ] 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") lines = [] 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") if date < obj.date_start: raise Exception( "Transaction date is before start date: %s" % date) if date > obj.date_end: raise Exception("Transaction date is after end date: %s" % date) balance = vals["Balance"].strip().replace(",", "") if not balance: raise Exception("missing balance") try: balance = float(balance) except: raise Exception("Failed to read Balance amount") description = vals.get("Description").strip() try: spent = vals["Spent"].strip().replace(",", "") spent = float(spent) if spent else 0 except: raise Exception("Failed to read Spent amount") try: received = vals["Received"].strip().replace(",", "") received = float(received) if received else 0 except: raise Exception("Failed to read Received amount") if not spent and not received: raise Exception("No spent or received amount") if spent and received: raise Exception( "Can not have both Spent and Received amounts on the same line" ) line_vals = { "date": date, "balance": balance, "description": description, "spent": spent, "received": received, } lines.append(line_vals) except Exception as e: raise Exception("Error on line %d (%s)" % (i + 2, e)) if not lines: raise Exception("Empty statement") first_bal = lines[0]["balance"] + lines[0]["spent"] - lines[0][ "received"] first_date = lines[0]["date"] res = get_model("account.statement.line").search( [["statement_id.account_id", "=", acc_id], ["date", "<", first_date]], order="date desc,id desc", limit=1) if res: prev_line = get_model("account.statement.line").browse(res[0]) prev_bal = prev_line.balance if abs(first_bal - prev_bal) > 0.001: raise Exception("Invalid balance: previous balance is %.2f" % prev_bal) st_vals = { "account_id": acc_id, "date_start": obj.date_start, "date_end": obj.date_end, "balance_start": first_bal, "lines": [("create", v) for v in lines], } stmt_id = get_model("account.statement").create(st_vals) return { "next": { "name": "statement", "mode": "page", "active_id": stmt_id, } }
def get_data_form(self, context={}): inv_id = context.get("invoice_id") # XXX: old, move this if not inv_id: inv_id = context["refer_id"] inv_id = int(inv_id) inv = get_model("account.invoice").browse(inv_id) dbname = database.get_active_db() company = inv.company_id settings = get_model("settings").browse(1) comp_addr = settings.get_address_str() comp_name = company.name comp_phone = settings.phone comp_fax = settings.fax comp_tax_no = settings.tax_no contact = inv.contact_id cust_addr = contact.get_address_str() cust_name = contact.name cust_fax = contact.fax cust_phone = contact.phone cust_tax_no = contact.tax_no data = { "comp_name": comp_name, "comp_addr": comp_addr, "comp_phone": comp_phone or "-", "comp_fax": comp_fax or "-", "comp_tax_no": comp_tax_no or "-", "cust_name": cust_name, "cust_addr": cust_addr, "cust_phone": cust_phone or "-", "cust_fax": cust_fax or "-", "cust_tax_no": cust_tax_no or "-", "date": inv.date or "-", "due_date": inv.due_date or "-", "number": inv.number or "-", "ref": inv.ref or "-", "memo": inv.memo or "", "lines": [], } if settings.logo: data["logo"] = get_file_path(settings.logo) for line in inv.lines: data["lines"].append({ "description": line.description, "code": line.product_id.code, "qty": line.qty, "uom": line.uom_id.name, "unit_price": line.unit_price, "discount": line.discount, "tax_rate": line.tax_id.rate, "amount": line.amount, }) is_cash = 'No' is_cheque = 'No' for obj in inv.payments: account_type = obj.payment_id.account_id.type if account_type in ("bank", "cash"): is_cash = 'Yes' if account_type in ("cheque"): is_cheque = 'Yes' data.update({ "amount_subtotal": inv.amount_subtotal, "amount_discount": inv.amount_discount, "amount_tax": inv.amount_tax, "amount_total": inv.amount_total, "amount_paid": inv.amount_paid, "payment_terms": inv.related_id.payment_terms or "-", "is_cash": is_cash, "is_cheque": is_cheque, "currency_code": inv.currency_id.code, "tax_rate": round(inv.amount_tax * 100.0 / inv.amount_subtotal or 0, 2), "qty_total": inv.qty_total, "memo": inv.memo, }) if inv.credit_alloc: data.update({ "original_inv_subtotal": inv.credit_alloc[0].invoice_id.amount_subtotal, }) return data
def get_data_purchase_form(self, context={}): obj_id = int(context["refer_id"]) obj = get_model("purchase.order").browse(obj_id) dbname = database.get_active_db() settings = get_model("settings").browse(1) comp_name = settings.name comp_phone = settings.phone comp_fax = settings.fax comp_addr = settings.get_address_str() comp_tax_no = settings.tax_no contact = obj.contact_id cust_name = contact.name cust_fax = contact.fax cust_phone = contact.phone cust_tax_no = contact.tax_no cust_addr = contact.get_address_str() data = { "comp_name": comp_name, "comp_addr": comp_addr, "comp_phone": comp_phone or "-", "comp_fax": comp_fax or "-", "comp_tax_no": comp_tax_no or "-", "cust_name": cust_name, "cust_addr": cust_addr, "cust_phone": cust_phone or "-", "cust_fax": cust_fax or "-", "cust_tax_no": cust_tax_no or "-", "date": obj.date or "-", "number": obj.number or "-", "ref": obj.ref or "-", "delivery_date": obj.delivery_date or "-", "ship_method": obj.ship_method_id.name or "-", "payment_terms": obj.payment_terms or "-", "lines": [], } index = 0 for line in obj.lines: if line.tax_id: break index += 1 if not index: tax_rate = obj.lines[index].tax_id.rate tax_rate = tax_rate and tax_rate or "0" else: tax_rate = "0" if settings.logo: data["logo"] = get_file_path(settings.logo) for line in obj.lines: data["lines"].append({ "code": line.product_id.code, "description": line.description, "qty": line.qty, "uom": line.uom_id.name, "unit_price": line.unit_price, "tax_rate": line.tax_id.rate, "amount": line.amount, }) data.update({ "amount_subtotal": obj.amount_subtotal, "amount_tax": obj.amount_tax, "amount_total": obj.amount_total, "amount_total_words": utils.num2word(obj.amount_total), "currency_code": obj.currency_id.code, "tax_rate": int(tax_rate), "qty_total": obj.qty_total }) return data