def get_patient_info(self, *args, **kw): patient_id = kw.get('patient_id') # TODO: add a check if is None (?) cr, uid, context = request.cr, request.uid, request.context api_pool = request.registry('nh.eobs.api') patient_info = api_pool.get_patients(cr, uid, [int(patient_id)], context=context) if len(patient_info) > 0: response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title=patient_info[0]['full_name'], description='Information on {0}'.format( patient_info[0]['full_name'] ), data=patient_info[0] ) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE ) else: response_data = {'error': 'Patient not found.'} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_ERROR, title='Patient not found', description='Unable to get patient with ID provided', data=response_data ) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE )
def cancel_clinical(self, *args, **kw): task_id = kw.get('task_id') # TODO: add a check if is None (?) cr, uid = request.cr, request.uid api_pool = request.registry('nh.eobs.api') kw_copy = kw.copy() if kw else {} data_timestamp = kw_copy.get('startTimestamp', None) data_task_id = kw_copy.get('taskId', None) if data_timestamp is not None: del kw_copy['startTimestamp'] if data_task_id is not None: del kw_copy['taskId'] for key, value in kw_copy.items(): if not value: del kw_copy[key] # Try to get the cancel reason and add it to the dict if successful. cancel_reason = kw_copy.get('reason') if cancel_reason: kw_copy['reason'] = int(cancel_reason) try: api_pool.cancel(cr, uid, int(task_id), kw_copy) except osv.except_osv: response_data = { 'error': 'The server returned an error while trying ' 'to cancel the task.' } response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_ERROR, title='Cancellation unsuccessful', description='Unable to cancel the notification', data=response_data ) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE ) response_data = {'related_tasks': [], 'status': 4} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Cancellation successful', description='The notification was successfully cancelled', data=response_data ) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE )
def rhwl_weixin_bind(self,**kw): para={} if request.httprequest.data: para = eval(request.httprequest.data) if kw: para.update(kw) if para.get("openid") and para.get("uid"): registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: obj = registry.get("gbsoft.weixin") obj.action_user_bind(cr,para.get("code"),para.get("openid"),para.get("uid")) response = request.make_response(json.dumps({"statu":200},ensure_ascii=False), [('Content-Type', 'application/json')]) else: response = request.make_response(json.dumps({"statu":500},ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def report_productivity(self, course_id=None, report_type=None, parameter_id=None, direction_work_id=None, **kw): local_tz = pytz.timezone('America/Guayaquil') utc_dt = datetime.datetime.utcnow() local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) flag = 0 filename = '' full_path = '' p_report = productivity_report.ProductivityReport(local_tz, local_dt, course_id, parameter_id, direction_work_id) if report_type == 'D': flag = 1 filename, full_path = p_report.get_detail_productivity() elif report_type == 'S': flag = 1 filename, full_path = p_report.get_summary_productivity() if flag: file_content = self.print_report(full_path, filename) if not file_content: return request.not_found() else: if not filename: filename = '%s.pdf' % 'report' return request.make_response(file_content, headers=[('Content-Disposition', 'attachment; filename=%s Export' % filename), ('Content-Type', 'application/pdf')])
def list_holidays(self, **kw): res = wb.WebClient().check_userinfo(kw) registry = RegistryManager.get(request.session.db) if res["statu"] == 200: uid = res["userid"] res["data"] = [] with registry.cursor() as cr: try: hr_holidays = registry.get("hr.holidays") emp_obj = registry.get("hr.employee") emp_id = emp_obj.search(cr, SUPERUSER_ID, [("user_id", "=", uid)]) if not emp_id: res["statu"] = 500 res["errtext"] = u"当前用户没有关联员工信息。" else: ids = hr_holidays.search( cr, uid, [("employee_id", "in", emp_id), ("type", "=", "remove")], order="id desc" ) sel_state = hr_holidays.get_select_state(cr, uid, self.CONTEXT) for i in hr_holidays.browse(cr, uid, ids, context=self.CONTEXT): df = self.dateTimeTZ(i.date_from, 8) dt = self.dateTimeTZ(i.date_to, 8) res["data"].append((i.id, df, dt, i.holiday_status_id.name, i.name, sel_state.get(i.state))) except: res["statu"] = 500 response = request.make_response(json.dumps(res, ensure_ascii=False), [("Content-Type", "application/json")]) return response.make_conditional(request.httprequest)
def planpdf(self, product_id): """ Download the plan of a product - used in the fractions table """ if not product_id: return request.not_found() res = request.env['product.product'].browse(product_id) if not res or not res.exists(): _logger.warning('Someone tried to fetch the plan product #%i which was not found. Returning 404.', product_id) return request.not_found() if not res.plan_visible_in_website: _logger.warning('Someone tried to fetch the plan of product #%i that has the `plan_visible_in_website` set to False. Returning 404.', res.id) return request.not_found() filecontent = base64.b64decode(res.plan_pdf_file) if not filecontent: _logger.warning('Could not retrieve the plan of product #%i - filecontent is empty.', res.id) return request.not_found() filename = res.plan_pdf_filename if not filename: filename = 'plan.pdf' return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', 'attachment; filename={0}'.format(filename))])
def _rhwl_web_material_detail(self,**kw): res = self.check_userinfo(kw) data = [] if res.get('statu')==200: uid = res.get("userid") id = int(res.get("params").get("id")) registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: material = registry.get("rhwl.web.material") for i in material.browse(cr,uid,id,context=self.CONTEXT): data = [i.wh_level, i.hospital.id if i.hospital else 0, i.address_id.id if i.address_id else 0, i.state, i.receiver_user, i.receiver_address, i.receiver_tel ] detail=[] for d in i.line: detail.append([d.product_id.id,d.product_id.name,d.product_id.uom_id.name,round(d.qty,2)]) data.append(detail) else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def download_file(self, **kargs): file_id = kargs['file_id'] Model = request.session.model('abc_ipt.com_file') files = Model.search_read([('id', '=', file_id)]) if files: file = files[0] else: return '未发现该文件' tmp_file_name = file['tmp_file_name'] file_name = file['file_name'] path = os.path.abspath(os.path.dirname(sys.argv[0])) filepath = path.replace('\\', '/') + '/myaddons/abc_ipt/com_files/{}'.format(tmp_file_name) try: # 默认模式为‘r’,只读模式 with open(filepath, 'rb') as f: contents = f.read() except Exception as e: _logger = logging.getLogger(__name__) _logger.error(str(e)) return '读取文件失败' fo = StringIO() fo.write(contents) fo.seek(0) data = fo.read() fo.close() return request.make_response(data, headers=[('Content-Disposition', content_disposition(file_name)), ('Content-Type', 'application/octet-stream')], )
def _get_menu(self,**kw): db = self._get_cursor() content = db.products.find() res=[] """["泰济生","泰济生",[("CN","中文",[("tjs_quantaoxi","全套系",[("yunmataocan","孕妈套餐")])])]]""" languages = self._get_common().get("languages") val={} for i in content: #第一层客户 if not val.has_key(i.get("belongsto")): val[i.get("belongsto")]={ "id":i.get("belongsto"), "name":i.get("belongsto"), "sub":{} } for k in languages.keys(): if not val[i.get("belongsto")]["sub"].has_key(k): val[i.get("belongsto")]["sub"][k]={"id":k,"name":languages.get(k),"sub":[]} if i.has_key(k): tc=[] for s in i.get(k).get("sets").keys(): tc.append((s,i.get(k).get("sets").get(s).get("name"))) val[i.get("belongsto")]["sub"][k]["sub"].append((i.get("_id"),i.get(k).get("name"),tc)) for k,v in val.items(): lang=[] for k1,v1 in val.get(k)["sub"].items(): lang.append((v1["id"],v1["name"],v1["sub"])) res.append((v["id"],v["name"],lang)) response = request.make_response(json.dumps(res,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def _get_rhwl_api_report_img(self,**kw): res = self.check_userinfo(kw) data = [] if res.get('statu')==200: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: sample = registry.get("rhwl.easy.genes") id = sample.search(cr,SUPERUSER_ID,[("name","=",res.get("params").get("id"))]) if id: obj=sample.browse(cr,SUPERUSER_ID,id) png_path = os.path.join("/data/odoo/file/report",obj.name) if not os.path.exists(png_path): os.mkdir(png_path) ps=int(res.get("params").get("ps")) pe=int(res.get("params").get("pe")) for i in range(ps,pe+1): if not os.path.exists(os.path.join(png_path,"pg_"+str(i).zfill(4)+".pdf")): shutil.copy(os.path.join("/data/odoo/file/report",obj.name+".pdf"),os.path.join(png_path,obj.name+".pdf")) os.system("cd "+png_path+";pdftk "+obj.name+".pdf burst") if not os.path.exists(os.path.join(png_path,"pg_"+str(i).zfill(4)+".png")): os.system("cd "+png_path+";convert -density 100 pg_"+str(i).zfill(4)+".pdf pg_"+str(i).zfill(4)+".png") data.append("/rhwl_gene/static/local/report/"+obj.name.encode("utf-8")+"/pg_"+str(i).zfill(4)+".png") else: data=res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def html_page(self, model, field, id=None, filename_field=None, **kw): """ Download link for files stored as binary fields. If the ``id`` parameter is omitted, fetches the default value for the binary field (via ``default_get``), otherwise fetches the field for that precise record. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename_field: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry[model] cr, uid, context = request.cr, request.uid, request.context fields = [field] if filename_field: fields.append(filename_field) if id: res = Model.read(cr, uid, [int(id)], fields, context)[0] else: res = Model.default_get(cr, uid, fields, context) filecontent = base64.b64decode(res.get(field) or '') if not filecontent: return request.not_found() else: filename = '%s_%s' % (model.replace('.', '_'), id) if filename_field: filename = res.get(filename_field, '') or filename return request.make_response(filecontent, [('Content-Type', 'text/html')])
def _post_detail(self,**kw): db = self._get_cursor() contents = db.products.find_one({"_id":kw.get("id").encode("utf-8")}) #取套餐数据 no = contents.get(kw.get("lang")).get("sets").get(kw.get("tc")).get("list").get(kw.get("no")) pd = db.prodata.find_one({"_id":no}) for k,v in kw.items(): if(k in ["lang","id","tc","no"]):continue key=k.split("_") if(len(key)==1): if(key[0]=="pic"): mimetype=kw.get("pic").mimetype fs=base64.encodestring(kw.get("pic").stream.read()) if not (mimetype and fs):continue if not pd[kw.get("lang")].has_key(key[0]): pd[kw.get("lang")][key[0]]={"base64":"","mimetype":""} if not isinstance(pd[kw.get("lang")][key[0]],(dict,)): pd[kw.get("lang")][key[0]]={"base64":"","mimetype":""} pd[kw.get("lang")][key[0]]["base64"]=fs pd[kw.get("lang")][key[0]]["mimetype"]=mimetype elif(key[0]=="sex"): pd["sex"]=kw.get("sex") else: pd[kw.get("lang")][key[0]]=v elif(len(key)==2): if not pd[kw.get("lang")].has_key(key[0]): pd[kw.get("lang")][key[0]]={} pd[kw.get("lang")][key[0]][key[1]]=v db.prodata.update({"_id":no},pd) response = request.make_response("数据提交成功,<a href=\"javascript:history.back(-2);\">后退</a>") return response.make_conditional(request.httprequest)
def get_detail(self,**kw): registry = RegistryManager.get(request.session.db) obj = registry.get("rhwl.easy.genes.new") sexdict={'M':u'男','F':u'女'} with registry.cursor() as cr: id = obj.search(cr,request.uid,[("name","=",kw.get("no"))]) if not id: data={} else: res = obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) data={ "batch_no":res.batch_no, "name":res.name, "date":res.date, "cust_name":res.cust_name, "sex": sexdict.get(res.sex,""), "identity":res.identity and res.identity or "", "mobile":res.mobile and res.mobile or "", "birthday":res.birthday and res.birthday or "", "hospital":res.hospital.name, "package":res.package_id.name, "gene_id":res.id, } response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def _get_detail(self,**kw): db = self._get_cursor() content = db.products.find_one({"_id":kw.get("id").encode("utf-8")}) #取套餐数据 tc = content.get(kw.get("lang").encode("utf-8"),{}).get("sets",{}).get(kw.get("tc").encode("utf-8"),{}) #取指定套餐内容 no = tc.get("list").get(kw.get("no")) pd = db.prodata.find_one({"_id":no}) template = db.pagemodes.find_one({"_id":pd.get("pagemode")}) # 取套餐模板 res=[] susceptibility_db = self._get_cursor("susceptibility") genes_db = self._get_cursor("genes") for r in susceptibility_db.relations.find({'itm': pd.get("_id")}): rsid= [r.get("rsid")] genes=[] rsid_ids = genes_db.rsid2genes.find({"_id":{'$in':rsid}}) for i in rsid_ids: genes = genes + i.get("gene") if genes: for i in genes_db.geneFunctions.find({"_id":{'$in':genes}}): res.append([r.get("gtid"),i["_id"],i["fullname"],i["function"]["pathway_go"],i["function"]["summary"]]) data = pd.get(kw.get("lang").encode("utf-8")) data["sex"] = pd.get("sex") res = [template.get("itms"),data,res] response = request.make_response(json.dumps(res,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def _get_list(self,**kw): db = self._get_cursor() susceptibility_db = self._get_cursor("susceptibility") genes_db = self._get_cursor("genes") content = db.products.find_one({"_id":kw.get("id").encode("utf-8")}) #取套餐数据 tc = content.get(kw.get("lang").encode("utf-8"),{}).get("sets",{}).get(kw.get("tc").encode("utf-8"),{}) #取指定套餐内容 #template = db.pagemodes.find_one({"_id":tc.get("xmlmode")}) # 取套餐模板 category = self._get_common().get("category") res=[] result={} snp_result=[] for k,v in tc.get("list").items(): pd = db.prodata.find_one({"_id":v}) if not pd:continue if not result.has_key(pd["category"]): result[pd["category"]]=[] result[pd["category"]].append([k,pd.get(kw.get("lang")).get("title",""),pd.get("sex"),int(pd.get(kw.get("lang")).get("subclass").get("order"))*100+int(pd.get(kw.get("lang")).get("order")),pd.get(kw.get("lang")).get("subclass").get("name")]) for r in susceptibility_db.relations.find({'itm': pd.get("_id")}): rsid= [r.get("rsid")] genes=[] rsid_ids = genes_db.rsid2genes.find({"_id":{'$in':rsid}}) for i in rsid_ids: for g in i.get("gene"): snp_result.append([pd.get(kw.get("lang")).get("title",""),r.get("gtid"),g]) for i in tc.get("region"): result[i].sort(lambda x,y:cmp(x[3],y[3])) res.append([i,category.get(kw.get("lang")).get(i),result[i]]) response = request.make_response(json.dumps([tc["name"],res,snp_result],ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def download_document(self,model,field,id,filename=None, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry['labpal.experiment'] cr, uid, context = request.cr, request.uid, request.context fields = [field] res = Model.read(cr, uid, [int(id)], fields, context)[0] csv_file = StringIO() csv_writer = csv.writer(csv_file) csv_writer.writerow(["1","a","b","c"]) filecontent = base64.b64decode(csv_file) if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), id) return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def app_today_deliver(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("parentID") detail = eval(res.get("params").get("datas")) #[{ "code":"X140545" , "preCode":"X145655" },{ "code":"4X32871" , "preCode":"" },{ "code":"4Y45474" , "preCode":"" } ]}'; uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: obj = registry.get('sale.sampleone.days') dobj =registry.get("sale.sampleone.days.line") vals={ "partner_id":id, "user_id":uid } mid = obj.create(cr,uid,vals,context=self.CONTEXT) did=[] for j in detail: did.append( dobj.create(cr,uid,{"parent_id":mid,"sample_no":j.get("code"),"name":j.get("name")},context=self.CONTEXT)) obj.write(cr,uid,mid,{'detail_ids':[[6, False, did]]}) data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def livechat_lib(self, ext, **kwargs): asset = AssetsBundle("im_livechat.external_lib") # can't use /web/content directly because we don't have attachment ids (attachments must be created) status, headers, content = binary_content(id=getattr(asset, ext)().id, unique=asset.checksum) content_base64 = base64.b64decode(content) headers.append(('Content-Length', len(content_base64))) return request.make_response(content_base64, headers)
def report_integrator(self, course_id=None, report_type=None, parameter_id=None, war_games_report=None, war_games_id=None, judge_id=None, student_id=None, **kw): local_tz = pytz.timezone('America/Guayaquil') utc_dt = datetime.datetime.utcnow() local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) flag = 0 filename = '' full_path = '' i_report = student_integrator_report.StudentIntegratorReport(local_tz, local_dt,course_id, parameter_id, war_games_report, war_games_id, judge_id, student_id) if report_type == 'D': flag = 1 filename, full_path = i_report.get_detail_integrator() elif report_type == 'S': flag = 1 filename, full_path = i_report.get_summary_integrator() if flag: file_content = self.print_report(full_path, filename) if not file_content: return request.not_found() else: if not filename: filename = '%s.pdf' % 'report' return request.make_response(file_content, headers=[('Content-Disposition', 'attachment; filename=%s Export' % filename), ('Content-Type', 'application/pdf')])
def rhwl_weixin_jsapi(self,**kw): para={} if request.httprequest.data: para = eval(request.httprequest.data) if kw: para.update(kw) url=para.get("url","").encode('utf-8') code=para.get("code","").encode('utf-8') s='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' noncestr=''.join([s[random.randrange(0,s.__len__()-1)] for i in range(1,21)]) timestamp=time.time().__trunc__().__str__() registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: b = registry.get('gbsoft.weixin.base') ids =b.search(cr,SUPERUSER_ID,[("code","=",code)],limit=1) appid = b.browse(cr,SUPERUSER_ID,ids).original_id jsapi_ticket= b._get_ticket(cr,SUPERUSER_ID,code,context=self.CONTEXT) str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"×tamp="+timestamp+"&url="+url sha = hashlib.sha1(str) s = sha.hexdigest() data={ "noncestr":noncestr, "timestamp":timestamp, "signature":s, "appid":appid } response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def avatar(self, res_model, res_id, partner_id): headers = [[("Content-Type", "image/png")]] content = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule("read") if ( partner_id in request.env[res_model].browse(res_id).sudo().exists().message_ids.mapped("author_id").ids ): status, headers, content = binary_content( model="res.partner", id=partner_id, field="image_medium", default_mimetype="image/png", env=request.env(user=openerp.SUPERUSER_ID), ) if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass image_base64 = base64.b64decode(content) headers.append(("Content-Length", len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def detail_get(self,**kw): dbport=kw.get("dbport") conn = pymongo.Connection(self.DBIP,int(dbport)) db = conn.disease #连接库 res=db.disease.find_one({"_id":kw.get("id").encode("utf-8")}) response = request.make_response(json.dumps(res,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def app_reuse(self,**kw): res = self.check_userinfo(kw) data = {} state={ "draft": u"未通知", "done": u"已通知", "cancel": u"孕妇放弃", "reuse": u"已重采血" } if res.get('statu')==200: uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: sampleone = registry.get('sale.sampleone.reuse') reuseid = sampleone.search(cr,uid,[('state','not in',['cancel','reuse'])],order="id desc") data=[] for i in sampleone.browse(cr,uid,reuseid,context=self.CONTEXT): data.append({ "time":i.cx_date, "name":i.yfxm, "numbers":i.name.yftelno, "id":i.name.name, "status":state.get(i.state) }) cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def comments_per_product(self, **post): cr, uid, pool = request.cr, request.uid, request.registry message_qty = pool.get( 'mail.message')._get_product_comments_qty(cr, uid, post.get('product_id')) return request.make_response(json.dumps(message_qty))
def report_academic_achievement(self, course_id=None, report_type=None, subject_id=None, student_id=None, **kw): local_tz = pytz.timezone('America/Guayaquil') utc_dt = datetime.datetime.utcnow() local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) flag = 0 filename = '' full_path = '' s_report = student_score_report.StudentScoreReport(local_tz, local_dt, subject_id, course_id, student_id) if report_type == 'D': flag = 1 filename, full_path = s_report.get_detail_academic_achievement() elif report_type == 'S': flag = 1 filename, full_path = s_report.get_summary_academic_achievement() elif report_type == 'F': flag = 1 filename, full_path = s_report.get_summary_academic_final() if flag: file_content = self.print_report(full_path, filename) if not file_content: return request.not_found() else: if not filename: filename = '%s.pdf' % 'report' return request.make_response(file_content, headers=[('Content-Disposition', 'attachment; filename=%s Export' % filename), ('Content-Type', 'application/pdf')])
def status_http(self): resp = '<html>\n<body>\n<h1>Hardware Proxy Status</h1>\n' statuses = self.get_status() for driver in statuses: status = statuses[driver] if status['status'] == 'connecting': color = 'black' elif status['status'] == 'connected': color = 'green' else: color = 'red' resp += "<h2 style='color:"+color+";'>"+driver+' : '+status['status']+"</h2>\n" resp += "<ul>\n" for msg in status['messages']: resp += '<li>'+msg+'</li>\n' resp += "</ul>\n" resp += "<script>\n\tsetTimeout(function(){window.location.reload();},30000);\n</script>\n</body>\n</html>\n\n" return request.make_response(resp,{ 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', })
def app_express(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: startTime = res.get("params").get("startTime") endTime = res.get("params").get("endTime") uid = res.get("userid") if not startTime:startTime=(datetime.datetime.today() - datetime.timedelta(100)).strftime("%Y-%m-%d") if not endTime:endTime=(datetime.datetime.today() + datetime.timedelta(1)).strftime("%Y-%m-%d") if startTime and endTime: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: express = registry.get('stock.picking.express') ids = express.search(cr,uid,[('date','>=',startTime),('date','<=',endTime)],order="date desc",context=self.CONTEXT) data=[] for i in express.browse(cr,uid,ids,self.CONTEXT): data.append({ "time":i.date[0:10], "logIdCompany": [i.num_express,i.deliver_id.name], "state": STATE.get(i.state), "is_deliver":i.is_deliver, "is_receiv":i.is_receiv }) cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def app_receive(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("goodsId") uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: express = registry.get('stock.picking.express') ids = express.search(cr,uid,[('num_express','=',id),('state','not in',['done','cancel'])],context=self.CONTEXT) data = { "receiv_real_qty":res.get("params").get("actualNumber"), "receiv_real_user": uid, "receiv_real_date": datetime.datetime.now(), } express.write(cr,uid,ids,data,context=self.CONTEXT) express.action_ok(cr,uid,ids,context=self.CONTEXT) data={} data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def app_notice(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("id") #样品编码 btn = res.get("params").get("btn") uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: reuse_obj = registry.get('sale.sampleone.reuse') reuseid = reuse_obj.search(cr,uid,[('name.name','=',id)]) if reuseid: if btn=="1": vals = {'notice_user':uid,'notice_date':datetime.datetime.now(),'state':'done'} else: vals = {'state':'draft'} reuse_obj.write(cr,SUPERUSER_ID,reuseid,vals,context=self.CONTEXT) else: except_obj = registry.get('sale.sampleone.exception') expid = except_obj.search(cr,uid,[('name.name','=',id)]) if btn=="1": vals = {'notice_user':uid,'notice_date':datetime.datetime.now(),'state':'notice',"is_notice":True} else: vals = {'state':'draft',"is_notice":False} if expid: except_obj.write(cr,SUPERUSER_ID,expid,vals,context=self.CONTEXT) data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def reject_shared_patients(self, *args, **kw): activity_id = kw.get('activity_id') # TODO: add a check if is None (?) cr, uid, context = request.cr, request.uid, request.context api = request.registry['nh.eobs.api'] activities = api.get_assigned_activities( cr, uid, activity_type='nh.clinical.patient.follow', context=context) res = {} for a in activities: if a['id'] == int(activity_id): res = a res['status'] = True break response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Successfully rejected stand-in invite', description='You are not following {0} patient(s) from {1}'.format( res['count'], res['user']), data=res) try: api.cancel(cr, uid, int(activity_id), {}, context=context) except osv.except_osv: res = {'reason': 'Unable to cancel the activity.'} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_ERROR, title='Unable to reject stand-in invite', description='An error occurred when trying to ' 'reject the stand-in invite', data=res) return request.make_response(response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def download_vat_diary(self, debug=1, wizard_id=0, filename=''): # pragma: no cover """ Descarga un documento cuando se accede a la url especificada en http route. :param debug: Si esta o no en modo debug. :param int wizard_id: Id del modelo que contiene el documento. :param filename: Nombre del archivo. :returns: :class:`werkzeug.wrappers.Response`, descarga del archivo excel. """ filecontent = base64.b64decode(request.env['wizard.vat.diary'].browse(int(wizard_id)).report or '') return request.make_response(filecontent, [('Content-Type', 'application/excel'), ('Content-Disposition', content_disposition(filename))])
def download_season(self, inventory_id, season_id, **post): env = request.env inventory, season = self._get_inventory_season(inventory_id, season_id) if not (inventory and season): return request.render('website.404') pdf = env['report'].sudo().get_pdf( season, 'website_myaccount_stock_inventory.report_season') pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders)
def image(self, uuid, user_id): registry, cr, context, uid = request.registry, request.cr, request.context, request.session.uid # get the image Session = registry.get("im_chat.session") image_b64 = Session.get_image(cr, openerp.SUPERUSER_ID, uuid, simplejson.loads(user_id), context) # built the response image_data = base64.b64decode(image_b64) headers = [('Content-Type', 'image/png')] headers.append(('Content-Length', len(image_data))) return request.make_response(image_data, headers)
def order_download(self, order_id, **post): env = request.env order = env['sale.order'].browse(order_id) if order.exists() and order.partner_id.id == env.user.partner_id.id: pdf = env['report'].get_pdf(order, 'sale.report_saleorder') pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return ''
def take_task_ajax(self, *args, **kw): task_id = kw.get('task_id') # TODO: add a check if is None (?) cr, uid, context = request.cr, request.uid, request.context task_id = int(task_id) activity_reg = request.registry['nh.activity'] api_reg = request.registry['nh.eobs.api'] task = activity_reg.read(cr, uid, task_id, ['user_id'], context=context) if task and task.get('user_id') and task['user_id'][0] != uid: response_data = {'reason': 'Task assigned to another user.'} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_FAIL, title='Unable to take task', description='This task is already assigned to another user', data=response_data) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE) else: try: api_reg.assign(cr, uid, task_id, {'user_id': uid}, context=context) except osv.except_osv: response_data = {'reason': 'Unable to assign to user.'} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_ERROR, title='Unable to take task', description='An error occurred when ' 'trying to take the task', data=response_data) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE) response_data = {'reason': 'Task was free to take.'} response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Task successfully taken', description='You can now perform this task', data=response_data) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def livechat_lib(self, ext, **kwargs): asset = AssetsBundle("im_livechat.external_lib") mock_attachment = getattr(asset, ext)() if isinstance(mock_attachment, list): # suppose that CSS asset will not required to be split in pages mock_attachment = mock_attachment[0] # can't use /web/content directly because we don't have attachment ids (attachments must be created) status, headers, content = binary_content(id=mock_attachment.id, unique=asset.checksum) content_base64 = base64.b64decode(content) if content else '' headers.append(('Content-Length', len(content_base64))) return request.make_response(content_base64, headers)
def products_per_attr(self, **post): """This method main purpose is to get asynchronously all the wether the customer purchased or not the product he commented. """ cr, uid, pool = request.cr, request.uid, request.registry author_ids = ast.literal_eval(post.get('author_ids')) product_id = int(post.get('product_id')) product_obj = pool.get('product.template') res = product_obj.comment_bought(cr, uid, product_id, tuple(author_ids)) return request.make_response(json.dumps(res))
def product_qty_import(self, stmt=None): pdf = modules.get_module_path( 'api_inventory') + "/controller/product_qty_import_file.xlsx" f = open(pdf, 'rb') image_base64 = f.read() response = request.make_response( image_base64, headers=[('Content-Type', 'application/xlsx'), ('Content-Disposition', 'attachment; filename=product_qty_import_file.xlsx;')]) return response
def agent_download_invoice(self, invoice_id, **post): env = request.env invoice = self._prepare_agent_invoices(invoice_id=invoice_id, limit=1) if invoice: pdf = env['report'].sudo().get_pdf(invoice, 'account.report_invoice') pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return ''
def export_xls_view(self, model=False, res_id=None): records = res_id if res_id else request.registry[model].search(request.cr,request.uid,[]) document = etree.tostring(export_xml(get_related(request.registry[model].browse(request.cr,request.uid,records),0)),pretty_print=True,encoding="utf-8") return request.make_response( document, headers=[ ('Content-Disposition', 'attachment; filename="%s.xml"' % model), ('Content-Type', 'application/rdf+xml'), ('Content-Length', len(document)), ] )
def get_colleagues(self, *args, **kw): cr, uid, context = request.cr, request.uid, request.context api = request.registry['nh.eobs.api'] colleagues = api.get_share_users(cr, uid, context=context) response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Colleagues on shift', description='Choose colleagues for stand-in', data={'colleagues': colleagues}) return request.make_response(response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def cancel_reasons(self, *args, **kw): cr, uid, context = request.cr, request.uid, request.context api_pool = request.registry('nh.eobs.api') response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Reason for cancelling task?', description='Please state reason for cancelling task', data=api_pool.get_cancel_reasons(cr, uid, context=context)) return request.make_response(response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def rhwl_weixin_bind(self, **kw): para = {} if request.httprequest.data: para = eval(request.httprequest.data) if kw: para.update(kw) if para.get("openid") and para.get("uid"): registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: obj = registry.get("rhwl.weixin") obj.action_user_bind(cr, para.get("code"), para.get("openid"), para.get("uid")) response = request.make_response( json.dumps({"statu": 200}, ensure_ascii=False), [('Content-Type', 'application/json')]) else: response = request.make_response( json.dumps({"statu": 500}, ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def css_bundle(self, xmlid, version=None, page=None, **kw): try: bundle = AssetsBundle(xmlid) except QWebTemplateNotFound: return request.not_found() e_tag = request.httprequest.headers.get('If-None-Match') if e_tag and e_tag == bundle.checksum: return werkzeug.wrappers.Response(status=304) else: response = request.make_response(bundle.css(page), [('Content-Type', 'text/css')]) return make_conditional(response, bundle.last_modified, etag=bundle.checksum, max_age=BUNDLE_MAXAGE)
def followup(self, partners, token, **kw): uid = request.session.uid try: context_obj = request.env['account.report.context.followup'] partners = request.env['res.partner'].browse( [int(i) for i in partners.split(',')]) context_ids = context_obj.search([('partner_id', 'in', partners.ids), ('create_uid', '=', uid)]) response = request.make_response( context_ids.with_context(public=True).get_pdf(log=True), headers=[('Content-Type', 'application/pdf'), ('Content-Disposition', 'attachment; filename=payment_reminder.pdf;')]) response.set_cookie('fileToken', token) return response except Exception, e: se = _serialize_exception(e) error = {'code': 200, 'message': 'Odoo Server Error', 'data': se} return request.make_response(html_escape(json.dumps(error)))
def voip_messagebank_client(self, voip_call_client_id): """ Allow listen to call in browser """ voip_call_client = request.env['voip.call.client'].browse( int(voip_call_client_id)) voip_call = voip_call_client.vc_id headers = [] audio_stream = base64.b64decode(voip_call_client.audio_stream) #Add a RIFF wrapper to the raw file so we can play the audio in the browser, this is just a crude solution for those that don't have transcoding installed if voip_call_client.vc_id.media_filename == "call.raw": #"RIFF" riff_wrapper = "52 49 46 46" #File Size riff_wrapper += " " + struct.pack( '<I', len(audio_stream) - 8).encode('hex') #"WAVE" riff_wrapper += " 57 41 56 45" #"fmt " riff_wrapper += " 66 6D 74 20" #Subchunk1Size(18) riff_wrapper += " 12 00 00 00" #AudioFormat (7) ulaw #riff_wrapper += " 07 00" riff_wrapper += struct.pack( '<H', voip_call.codec_id.riff_audio_encoding_value).encode('hex') #NumChannels(1) riff_wrapper += " 01 00" #Sample rate (8000) riff_wrapper += " 40 1F 00 00" #ByteRate (SampleRate[8000] * NumChannels[1] * BitsPerSample[8]/8 = 16000) riff_wrapper += " 40 1F 00 00" #BlockAlign (NumChannels[1] * BitsPerSample[8]/8) riff_wrapper += " 01 00" #BitsPerSample(8) riff_wrapper += " 08 00" #No idea riff_wrapper += " 00 00" #Subchunk2ID "data" riff_wrapper += "64 61 74 61" #Subchunk2Size (NumSamples * NumChannels[1] * BitsPerSample[8]) riff_wrapper += " " + struct.pack( '<I', len(audio_stream) - 46).encode('hex') media = riff_wrapper.replace(" ", "").decode('hex') + audio_stream headers.append(('Content-Length', len(media))) headers.append(('Content-Type', 'audio/x-wav')) response = request.make_response(media, headers) return response
def invoice_download(self, invoice_id, **post): env = request.env invoice = env['account.invoice'].browse(invoice_id) if (invoice.exists() and invoice.partner_id.id == env.user.partner_id.id): pdf = env['report'].get_pdf(invoice, 'account.report_invoice') pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return ''
def voip_ringtone(self, ringtone, filename): """Return the ringtone file to be used by javascript""" voip_ringtone = request.env['voip.ringtone'].browse(int(ringtone)) headers = [] ringtone_base64 = base64.b64decode(voip_ringtone.media) headers.append(('Content-Length', len(ringtone_base64))) response = request.make_response(ringtone_base64, headers) return response
def get_partial_reasons(self, *args, **kw): observation = kw.get('observation') obs_pool = request.registry( 'nh.clinical.patient.observation.{0}'.format(observation)) response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Reason for partial observation', description='Please state reason for submitting ' 'partial observation', data=obs_pool._partial_reasons) return request.make_response(response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def export_xls_view(self, data, token): data = json.loads(data) model = data.get('model', []) columns_headers = data.get('headers', []) rows = data.get('rows', []) return request.make_response( self.from_data(columns_headers, rows), headers=[('Content-Disposition', 'attachment; filename="%s"' % self.filename(model)), ('Content-Type', self.content_type)], cookies={'fileToken': token})
def image(self, uuid, user_id): request_uid = self._default_request_uid() # anonymous will have a user_id = False, interpreted by string if isinstance(user_id, (basestring, unicode)): user_id = False # get image for the people in the channel image_b64 = request.env['im_chat.session'].sudo( request_uid).session_user_image(uuid, user_id) image_data = base64.b64decode(image_b64) headers = [('Content-Type', 'image/png')] headers.append(('Content-Length', len(image_data))) return request.make_response(image_data, headers)
def _get_rs_from_gt(self, **kw): snps_db = self._get_cursor("snps") res = [] for i in snps_db.snps.find( {"gtid": { "$in": [re.compile(kw.get("rs").encode("utf-8"))] }}): res.append([i.get("_id"), i.get("gtid")]) response = request.make_response(json.dumps( res, ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def dochelp(self, xpath=None, **kw): s = os.path.dirname(__file__) if xpath is None: xpath = 'index.html' ss = os.path.join(s, 'build', 'html', xpath) f = open(ss) t = os.path.getmtime(ss) last_modified = datetime.datetime.fromtimestamp(t) mimetype = mimetypes.guess_type(xpath)[0] ret = f.read() response = request.make_response(ret, [('Content-Type', mimetype)]) return make_conditional(response, last_modified, max_age=BUNDLE_MAXAGE)
def dispatch_file(self, data, token): _data = json.loads(data) obj = request.env[_data['model']] obj.init(_data['record_id']) response = request.make_response( obj.get_content(), headers=[('Content-Type', 'application/octet-stream;charset=utf-8;'), ('Content-Disposition', u'attachment; filename={};'.format(obj.get_filename()))], cookies={'fileToken': token}) return response
def download_saleorder(self, saleorder_id, **post): env = request.env saleorder = self._prepare_saleorders( saleorder_id=saleorder_id, limit=1) if (saleorder): pdf = env['report'].sudo().get_pdf( saleorder, 'sale.report_saleorder') pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return ''
def invoice_download(self, claim_id, **post): env = request.env claim = env['crm.claim'].browse(claim_id) partner = self._get_partner_company() if not claim.exists() or claim.partner_sat_id.id != partner.id: return '' if not claim.print_date: claim.print_date = datetime.now() pdf = env['report'].get_pdf( claim, 'print_formats_claim.report_crm_claim') return request.make_response(pdf, headers=[ ('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))])
def va_event_report(self, event_id, type, **kw): task = request.env['project.task'].sudo().search([('id', '=', event_id) ]) if type == 'executive': pdf = request.env['report'].sudo().get_pdf( task.audit_id, task.audit_id.ex_rpt_id.report_name) else: pdf = request.env['report'].sudo().get_pdf( task.audit_id, task.audit_id.gn_rpt_id.report_name) pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders)
def process_ajax_form(self, *args, **kw): observation = kw.get('observation') # TODO: add a check if is None (?) task_id = kw.get('task_id') # TODO: add a check if is None (?) cr, uid, context = request.cr, request.uid, request.context api = request.registry('nh.eobs.api') activity_api = request.registry('nh.activity') ob_str = 'nh.clinical.patient.observation.' + observation ob_pool = request.registry(ob_str) converter_pool = request.registry('ir.fields.converter') converter = converter_pool.for_model(cr, uid, ob_pool, str, context=context) kw_copy = kw.copy() if kw else {} data_timestamp = kw_copy.get('startTimestamp', None) data_task_id = kw_copy.get('taskId', None) data_device_id = kw_copy.get('device_id', None) if data_timestamp is not None: del kw_copy['startTimestamp'] if data_task_id is not None: del kw_copy['taskId'] if task_id is not None: del kw_copy['task_id'] if observation is not None: del kw_copy['observation'] if data_device_id is not None: del kw_copy['device_id'] for key, value in kw_copy.items(): if not value: del kw_copy[key] converted_data = converter(kw_copy, _logger.debug) if data_timestamp is not None: converted_data['date_started'] = \ datetime.fromtimestamp(int(data_timestamp)).strftime(DTF) if data_device_id is not None: converted_data['device_id'] = data_device_id api.complete(cr, uid, int(task_id), converted_data, context) activity = activity_api.browse(cr, uid, int(task_id)) obs = activity.data_ref description = self.get_submission_message(obs) response_data = obs.get_submission_response_data() response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Successfully Submitted{0} {1}'.format( ' Partial' if obs.is_partial else '', ob_pool.get_description()), description=description, data=response_data) return request.make_response( response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def cancel_reasons(self, *args, **kw): cr, uid, context = request.cr, request.uid, request.context api_pool = request.registry('nh.eobs.api') response_json = ResponseJSON.get_json_data( status=ResponseJSON.STATUS_SUCCESS, title='Why is this action not required?', description='Please state the reason ' 'why this action is not required', data=api_pool.get_cancel_reasons(cr, uid, context=context)) return request.make_response(response_json, headers=ResponseJSON.HEADER_CONTENT_TYPE)
def slide_download(self, slide): if slide.download_security == 'public' or (slide.download_security == 'user' and request.session.uid): filecontent = base64.b64decode(slide.datas) disposition = 'attachment; filename=%s.pdf' % werkzeug.urls.url_quote(slide.name) return request.make_response( filecontent, [('Content-Type', 'application/pdf'), ('Content-Length', len(filecontent)), ('Content-Disposition', disposition)]) elif not request.session.uid and slide.download_security == 'user': return werkzeug.utils.redirect('/web?redirect=/slides/slide/%s' % (slide.id)) return request.website.render("website.403")