def __init__(self, cursor, uid, report_id, context): "constructor" self.cursor = cursor self.uid = uid self.pool = yuancloud.registry(self.cursor.dbname) self.report_id = report_id self.context = context
def __init__(self, session, record): self.cr = session.cr self.uid = session.uid self.model = record.model self.id = record.id self.ids = [record.id] self.obj = yuancloud.registry(self.cr.dbname)[self.model]
def create(self, cursor, uid, ids, data, context=None): """We override the create function in order to handle generator Code taken from report openoffice. Thanks guys :) """ pool = yuancloud.registry(cursor.dbname) ir_obj = pool['ir.actions.report.xml'] report_xml_ids = ir_obj.search(cursor, uid, [('report_name', '=', self.name[7:])], context=context) if report_xml_ids: report_xml = ir_obj.browse(cursor, uid, report_xml_ids[0], context=context) else: return super(WebKitParser, self).create(cursor, uid, ids, data, context) setattr(report_xml, 'use_global_header', self.header if report_xml.header else False) if report_xml.report_type != 'webkit': return super(WebKitParser, self).create(cursor, uid, ids, data, context) result = self.create_source_pdf(cursor, uid, ids, data, report_xml, context) if not result: return (False, False) return result
def handler_text(self, jsonStr, cr, context, component_appid, appid, component_sercret, wXBizMsgCrypt, nonce): dbname = cr.dbname uid = SUPERUSER_ID context = context.copy() #component_sercret="d4624c36b6795d1d99dcf0547af5443d" with api.Environment.manage(): with registry(dbname).cursor() as new_cr: env = Environment(new_cr, uid, context) content = unquote(jsonStr['Content'].decode('utf-8')) print content if content.startswith('QUERY_AUTH_CODE'): query_auth_code = content.replace('QUERY_AUTH_CODE:', '') key = component_appid + "ticket" ticket = cache.redis.get(key) publicsdk = public_sdk.public_sdk(component_appid, component_sercret) token = publicsdk.api_query_auth(query_auth_code, ticket) reply_content = query_auth_code + "_from_api" custom_manager.sendText_custommessage_access_token( jsonStr['FromUserName'], reply_content, "", token['authorization_info']['authorizer_access_token']) return key = component_appid + "ticket" ticket = cache.redis.get(key) publicsdk = public_sdk.public_sdk(component_appid, component_sercret) refresh_token_key = appid + "authorizer_refresh_token" refresh_token = cache.redis.get(refresh_token_key) api_authorizer_token = publicsdk.api_authorizer_token( ticket, appid, refresh_token) print "api_authorizer_token:" + str(api_authorizer_token) #custom_manager.sendText_custommessage_access_token(jsonStr['FromUserName'],"测试","",api_authorizer_token) return env['receive_message'].accept_message( 'wx.message_text', jsonStr)
def __init__(self, cr, module, id_map, mode, filename, report=None, noupdate=False, loglevel=logging.DEBUG): self.cr = cr self.module = module self.id_map = id_map self.mode = mode self.filename = filename if report is None: report = assertion_report.assertion_report() self.assertion_report = report self.noupdate = noupdate self.loglevel = loglevel self.pool = yuancloud.registry(cr.dbname) self.uid = 1 self.context = {} # opererp context self.eval_context = { 'ref': self._ref(), '_ref': self._ref(), # added '_ref' so that record['ref'] is possible 'time': time, 'datetime': datetime, 'timedelta': timedelta } self.env = yuancloud.api.Environment(self.cr, self.uid, self.context)
def __init__(self, cr, module, idref, mode, report=None, noupdate=False, xml_filename=None): self.mode = mode self.module = module self.cr = cr self.idref = idref self.pool = yuancloud.registry(cr.dbname) self.uid = 1 if report is None: report = assertion_report.assertion_report() self.assertion_report = report self.noupdate = noupdate self.xml_filename = xml_filename self._tags = { 'record': self._tag_record, 'delete': self._tag_delete, 'function': self._tag_function, 'menuitem': self._tag_menuitem, 'template': self._tag_template, 'workflow': self._tag_workflow, 'report': self._tag_report, 'ir_set': self._tag_ir_set, # deprecated:: 9.0 'act_window': self._tag_act_window, 'assert': self._tag_assert, }
def exp_render_report(db, uid, object, ids, datas=None, context=None): if not datas: datas={} if not context: context={} self_id_protect.acquire() global self_id self_id += 1 id = self_id self_id_protect.release() self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None} cr = yuancloud.registry(db).cursor() try: result, format = yuancloud.report.render_report(cr, uid, ids, object, datas, context) if not result: tb = sys.exc_info() self_reports[id]['exception'] = yuancloud.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb) self_reports[id]['result'] = result self_reports[id]['format'] = format self_reports[id]['state'] = True except Exception, exception: _logger.exception('Exception: %s\n', exception) if hasattr(exception, 'name') and hasattr(exception, 'value'): self_reports[id]['exception'] = yuancloud.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value)) else: tb = sys.exc_info() self_reports[id]['exception'] = yuancloud.exceptions.DeferredException(tools.exception_to_unicode(exception), tb) self_reports[id]['state'] = True
def __init__(self, cr, uid, datas, func=False): # create a new document self.cr = cr self.pool = yuancloud.registry(cr.dbname) self.func = func or {} self.datas = datas self.uid = uid self.bin_datas = {}
def create(self, cr, uid, ids, datas, context=None): if not context: context={} self.cr=cr self.context = context self.groupby = context.get('group_by',[]) self.groupby_no_leaf = context.get('group_by_no_leaf',False) registry = yuancloud.registry(cr.dbname) model = registry[datas['model']] model_id = registry['ir.model'].search(cr, uid, [('model','=',model._name)]) model_desc = model._description if model_id: model_desc = registry['ir.model'].browse(cr, uid, model_id[0], context).name self.title = model_desc datas['ids'] = ids result = model.fields_view_get(cr, uid, view_type='tree', context=context) fields_order = self.groupby + self._parse_string(result['arch']) if self.groupby: rows = [] def get_groupby_data(groupby = [], domain = []): records = model.read_group(cr, uid, domain, fields_order, groupby , 0, None, context) for rec in records: rec['__group'] = True rec['__no_leaf'] = self.groupby_no_leaf rec['__grouped_by'] = groupby[0] if (isinstance(groupby, list) and groupby) else groupby for f in fields_order: if f not in rec: rec.update({f:False}) elif isinstance(rec[f], tuple): rec[f] = rec[f][1] rows.append(rec) inner_groupby = (rec.get('__context', {})).get('group_by',[]) inner_domain = rec.get('__domain', []) if inner_groupby: get_groupby_data(inner_groupby, inner_domain) else: if self.groupby_no_leaf: continue child_ids = model.search(cr, uid, inner_domain) res = model.read(cr, uid, child_ids, result['fields'].keys(), context) res.sort(lambda x,y: cmp(ids.index(x['id']), ids.index(y['id']))) rows.extend(res) dom = [('id','in',ids)] if self.groupby_no_leaf and len(ids) and not ids[0]: dom = datas.get('_domain',[]) get_groupby_data(self.groupby, dom) else: rows = model.read(cr, uid, datas['ids'], result['fields'].keys(), context) ids2 = map(itemgetter('id'), rows) # getting the ids from read result if datas['ids'] != ids2: # sorted ids were not taken into consideration for print screen rows_new = [] for id in datas['ids']: rows_new += [elem for elem in rows if elem['id'] == id] rows = rows_new res = self._create_table(uid, datas['ids'], result['fields'], fields_order, rows, context, model_desc) return self.obj.get(), 'pdf'
def create_source_pdf(self, cr, uid, ids, data, report_xml, context=None): if not context: context={} registry = yuancloud.registry(cr.dbname) attach = report_xml.attachment if attach: objs = self.getObjects(cr, uid, ids, context) results = [] for obj in objs: aname = eval(attach, {'object':obj, 'time':time}) result = False if report_xml.attachment_use and aname and context.get('attachment_use', True): aids = registry['ir.attachment'].search(cr, uid, [('datas_fname','=',aname+'.pdf'),('res_model','=',self.table),('res_id','=',obj.id)]) if aids: brow_rec = registry['ir.attachment'].browse(cr, uid, aids[0]) if not brow_rec.datas: continue d = base64.decodestring(brow_rec.datas) results.append((d,'pdf')) continue result = self.create_single_pdf(cr, uid, [obj.id], data, report_xml, context) if not result: return False if aname: try: name = aname+'.'+result[1] # Remove the default_type entry from the context: this # is for instance used on the account.account_invoices # and is thus not intended for the ir.attachment type # field. ctx = dict(context) ctx.pop('default_type', None) registry['ir.attachment'].create(cr, uid, { 'name': aname, 'datas': base64.encodestring(result[0]), 'datas_fname': name, 'res_model': self.table, 'res_id': obj.id, }, context=ctx ) except AccessError: #TODO: should probably raise a proper osv_except instead, shouldn't we? see LP bug #325632 _logger.info('Could not create saved report attachment', exc_info=True) results.append(result) if results: if results[0][1]=='pdf': from pyPdf import PdfFileWriter, PdfFileReader output = PdfFileWriter() for r in results: reader = PdfFileReader(cStringIO.StringIO(r[0])) for page in range(reader.getNumPages()): output.addPage(reader.getPage(page)) s = cStringIO.StringIO() output.write(s) return s.getvalue(), results[0][1] return self.create_single_pdf(cr, uid, ids, data, report_xml, context)
def execute(db, uid, obj, method, *args, **kw): threading.currentThread().dbname = db with yuancloud.registry(db).cursor() as cr: if method.startswith('_'): raise UserError( _('Private methods (such as %s) cannot be called remotely.') % (method, )) res = execute_cr(cr, uid, obj, method, *args, **kw) if res is None: _logger.info( 'The method %s of the object %s can not return `None` !', method, obj) return res
def receive(self, req): """ End-point to receive mail from an external SMTP server. """ dbs = req.jsonrequest.get('databases') for db in dbs: message = dbs[db].decode('base64') try: registry = yuancloud.registry(db) with registry.cursor() as cr: mail_thread = registry['mail.thread'] mail_thread.message_process(cr, SUPERUSER_ID, None, message) except psycopg2.Error: pass return True
def create(self, cr, uid, ids, data, context=None): context = dict(context or {}) if self.internal_header: context.update(internal_header=self.internal_header) # skip osv.fields.sanitize_binary_value() because we want the raw bytes in all cases context.update(bin_raw=True) registry = yuancloud.registry(cr.dbname) ir_obj = registry['ir.actions.report.xml'] registry['res.font'].font_scan(cr, SUPERUSER_ID, lazy=True, context=context) report_xml_ids = ir_obj.search(cr, uid, [('report_name', '=', self.name[7:])], context=context) if report_xml_ids: report_xml = ir_obj.browse(cr, uid, report_xml_ids[0], context=context) else: title = '' report_file = tools.file_open(self.tmpl, subdir=None) try: rml = report_file.read() report_type= data.get('report_type', 'pdf') class a(object): def __init__(self, *args, **argv): for key,arg in argv.items(): setattr(self, key, arg) report_xml = a(title=title, report_type=report_type, report_rml_content=rml, name=title, attachment=False, header=self.header) finally: report_file.close() # We add an attribute on the ir.actions.report.xml instance. # This attribute 'use_global_header' will be used by # the create_single_XXX function of the report engine. # This change has been done to avoid a big change of the API. setattr(report_xml, 'use_global_header', self.header if report_xml.header else False) report_type = report_xml.report_type if report_type in ['sxw','odt']: fnct = self.create_source_odt elif report_type in ['pdf','raw','txt','html']: fnct = self.create_source_pdf elif report_type=='html2html': fnct = self.create_source_html2html elif report_type=='mako2html': fnct = self.create_source_mako2html else: raise NotImplementedError(_('Unknown report type: %s') % report_type) fnct_ret = fnct(cr, uid, ids, data, report_xml, context) if not fnct_ret: return False, False return fnct_ret
def calc_date(self, cr, uid, context=None): """Compute the limit date for a given date""" if context is None: context = {} if not context.get('product_id', False): date = False else: product = yuancloud.registry(cr.dbname)['product.product'].browse( cr, uid, context['product_id']) duration = getattr(product, dtype) # set date to False when no expiry time specified on the product date = duration and (datetime.datetime.today() + datetime.timedelta(days=duration)) return date and date.strftime('%Y-%m-%d %H:%M:%S') or False
def wkf_expr_execute_action(self, activity): """ Evaluate the ir.actions.server action specified in the activity. """ context = { 'active_model': self.record.model, 'active_id': self.record.id, 'active_ids': [self.record.id] } ir_actions_server = yuancloud.registry(self.session.cr.dbname)['ir.actions.server'] result = ir_actions_server.run(self.session.cr, self.session.uid, [activity['action_id']], context) return result
def create(self, cr, uid, ids, datas, context=None): if not context: context = {} datas['ids'] = ids registry = yuancloud.registry(cr.dbname) model = registry[datas['model']] # title come from description of model which are specified in py file. self.title = model._description result = model.fields_view_get(cr, uid, view_type='form', context=context) fields_order = self._parse_string(result['arch']) rows = model.read(cr, uid, datas['ids'], result['fields'].keys()) self._create_table(uid, datas['ids'], result['fields'], fields_order, rows, context, model._description) return self.obj.get(), 'pdf'
def run_scheduler(self, cr, uid, use_new_cursor=False, company_id=False, context=None): ''' Call the scheduler in order to check the running procurements (super method), to check the minimum stock rules and the availability of moves. This function is intended to be run for all the companies at the same time, so we run functions as SUPERUSER to avoid intercompanies and access rights issues. @param self: The object pointer @param cr: The current row, from the database cursor, @param uid: The current user ID for security checks @param ids: List of selected IDs @param use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement. This is appropriate for batch jobs only. @param context: A standard dictionary for contextual values @return: Dictionary of values ''' super(procurement_order, self).run_scheduler(cr, uid, use_new_cursor=use_new_cursor, company_id=company_id, context=context) if context is None: context = {} try: if use_new_cursor: cr = yuancloud.registry(cr.dbname).cursor() move_obj = self.pool.get('stock.move') #Minimum stock rules self._procure_orderpoint_confirm(cr, SUPERUSER_ID, use_new_cursor=use_new_cursor, company_id=company_id, context=context) #Search all confirmed stock_moves and try to assign them confirmed_ids = move_obj.search(cr, uid, [('state', '=', 'confirmed')], limit=None, order='priority desc, date_expected asc', context=context) for x in xrange(0, len(confirmed_ids), 100): move_obj.action_assign(cr, uid, confirmed_ids[x:x + 100], context=context) if use_new_cursor: cr.commit() if use_new_cursor: cr.commit() finally: if use_new_cursor: try: cr.close() except Exception: pass return {}
def processmessage(self, openid, cr, uid, context, content, wxOfficeAccountInfo): dbname = cr.dbname uid = uid context = context.copy() with api.Environment.manage(): with registry(dbname).cursor() as new_cr: context.update({"openid": openid}) env = Environment(new_cr, uid, context) wxOfficeAccountInfo = env['wx.officialaccount'].search([ ('id', '=', wxOfficeAccountInfo.id) ]) #currentContext={} model_instances = [] model_instance = {} model_instance.update({"id": "", "model_value": ""}) model_instances.append(model_instance) env['wx.message.send_event'].sendmessage_TriggeredbyCommand( content, model_instances, wxOfficeAccountInfo)
def wkf_expr_check(self, transition, signal): """ Test if a transition can be taken. The transition can be taken if: - the signal name matches, - the uid is SUPERUSER_ID or the user groups contains the transition's group, - the condition evaluates to a truish value. """ if transition['signal'] and signal != transition['signal']: return False if self.session.uid != yuancloud.SUPERUSER_ID and transition['group_id']: registry = yuancloud.registry(self.session.cr.dbname) user_groups = registry['res.users'].read(self.session.cr, self.session.uid, [self.session.uid], ['groups_id'])[0]['groups_id'] if transition['group_id'] not in user_groups: return False return self.wkf_expr_eval_expr(transition['condition'])
def scanbarcode(eventKey, cr, uid, context, fromUser, wxOfficeAccountInfo): dbname = cr.dbname uid = uid context = context.copy() with api.Environment.manage(): with registry(dbname).cursor() as new_cr: context.update({"openid": fromUser}) new_env = Environment(new_cr, uid, context) # scanvalues={} # scanvalues['scene']="subscribe" # scanvalues['scancode_key']=eventKey # qr_management = new_env['ycloud.qr.management'].search(['|', ('scene_str', '=', eventKey), ('scene_id', '=', int(eventKey) if eventKey.isdigit() else -1)]) # if len(qr_management) > 0: # scanvalues['scene']=qr_management[0]['qr_scene'] # print scanvalues['scene'] # scanvalues['openid']=fromUser # scanvalues['officialaccount_appid']=wxOfficeAccountInfo['wx_appid'] # scancode_help=scancode.scancode(new_cr,uid,context) # scancode_help.create_scancode(scanvalues) # qr_key=qr_management[0]['qr_key'] # qr_models = qr_management[0]['qr_models'] qr_key = eventKey qr_models_values = [] # for qr_model in qr_models: # model_info=qr_model['model_id']['model'] # model_id_value=qr_model['model_id_value'] # model_column=qr_model['model_column']['name'] # orderinfo=new_env[model_info].search([(model_column,'=',model_id_value)])[0] # value={} # value.update({ # 'id':qr_model['model_id']['id'], # 'model_value':orderinfo # }) # qr_models_values.append(value) #currentContext={} if len(qr_models_values) == 0: new_env['receive_message'].process_clickkey( qr_key, jsonStr) else: new_env[ 'wx.message.send_event'].sendmessage_TriggeredbyCommand( qr_key, qr_models_values)
def go(id, uid, ids, datas, context): with yuancloud.api.Environment.manage(): cr = yuancloud.registry(db).cursor() try: result, format = yuancloud.report.render_report(cr, uid, ids, object, datas, context) if not result: tb = sys.exc_info() self_reports[id]['exception'] = yuancloud.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb) self_reports[id]['result'] = result self_reports[id]['format'] = format self_reports[id]['state'] = True except Exception, exception: _logger.exception('Exception: %s\n', exception) if hasattr(exception, 'name') and hasattr(exception, 'value'): self_reports[id]['exception'] = yuancloud.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value)) else: tb = sys.exc_info() self_reports[id]['exception'] = yuancloud.exceptions.DeferredException(tools.exception_to_unicode(exception), tb) self_reports[id]['state'] = True cr.commit() cr.close()
def create(self, cr, uid, ids, datas, context): registry = yuancloud.registry(cr.dbname) xml = self.create_xml(cr, uid, ids, datas, context) xml = tools.ustr(xml).encode('utf8') report_type = datas.get('report_type', 'pdf') if report_type == 'raw': return xml, report_type registry['res.font'].font_scan(cr, SUPERUSER_ID, lazy=True, context=context) rml = self.create_rml(cr, xml, uid, context) ir_actions_report_xml_obj = registry['ir.actions.report.xml'] report_xml_ids = ir_actions_report_xml_obj.search( cr, uid, [('report_name', '=', self.name[7:])], context=context) self.title = report_xml_ids and ir_actions_report_xml_obj.browse( cr, uid, report_xml_ids)[0].name or 'YuanCloud Report' create_doc = self.generators[report_type] pdf = create_doc(rml, title=self.title) return pdf, report_type
def __init__(self, cr, uid, name, parents=rml_parents, tag=rml_tag, context=None): if not context: context={} self.cr = cr self.uid = uid self.pool = yuancloud.registry(cr.dbname) user = self.pool['res.users'].browse(cr, uid, uid, context=context) self.localcontext = { 'user': user, 'setCompany': self.setCompany, 'repeatIn': self.repeatIn, 'setLang': self.setLang, 'setTag': self.setTag, 'removeParentNode': self.removeParentNode, 'format': self.format, 'formatLang': self.formatLang, 'lang' : user.company_id.partner_id.lang, 'translate' : self._translate, 'setHtmlImage' : self.set_html_image, 'strip_name' : self._strip_name, 'time' : time, 'display_address': self.display_address, # more context members are setup in setCompany() below: # - company_id # - logo } self.setCompany(user.company_id) self.localcontext.update(context) self.name = name self._node = None self.parents = parents self.tag = tag self._lang_cache = {} self.lang_dict = {} self.default_lang = {} self.lang_dict_called = False self._transl_regex = re.compile('(\[\[.+?\]\])')
def run_scheduler(self, cr, uid, use_new_cursor=False, company_id=False, context=None): ''' Call the scheduler to check the procurement order. This is intented to be done for all existing companies at the same time, so we're running all the methods as SUPERUSER to avoid intercompany and access rights issues. @param self: The object pointer @param cr: The current row, from the database cursor, @param uid: The current user ID for security checks @param ids: List of selected IDs @param use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement. This is appropriate for batch jobs only. @param context: A standard dictionary for contextual values @return: Dictionary of values ''' if context is None: context = {} try: if use_new_cursor: cr = yuancloud.registry(cr.dbname).cursor() # Run confirmed procurements dom = [('state', '=', 'confirmed')] if company_id: dom += [('company_id', '=', company_id)] prev_ids = [] while True: ids = self.search(cr, SUPERUSER_ID, dom, context=context) if not ids or prev_ids == ids: break else: prev_ids = ids self.run(cr, SUPERUSER_ID, ids, autocommit=use_new_cursor, context=context) if use_new_cursor: cr.commit() # Check if running procurements are done offset = 0 dom = [('state', '=', 'running')] if company_id: dom += [('company_id', '=', company_id)] prev_ids = [] while True: ids = self.search(cr, SUPERUSER_ID, dom, offset=offset, context=context) if not ids or prev_ids == ids: break else: prev_ids = ids self.check(cr, SUPERUSER_ID, ids, autocommit=use_new_cursor, context=context) if use_new_cursor: cr.commit() finally: if use_new_cursor: try: cr.close() except Exception: pass return {}
def check(db, uid, passwd): res_users = yuancloud.registry(db)['res.users'] return res_users.check(db, uid, passwd)
def login(db, login, password): res_users = yuancloud.registry(db)['res.users'] return res_users._login(db, login, password)
def getObjects(self, cr, uid, ids, context): table_obj = yuancloud.registry(cr.dbname)[self.table] return table_obj.browse(cr, uid, ids, context=context)
def _procure_orderpoint_confirm(self, cr, uid, use_new_cursor=False, company_id=False, context=None): ''' Create procurement based on Orderpoint :param bool use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement. This is appropriate for batch jobs only. ''' if context is None: context = {} if use_new_cursor: cr = yuancloud.registry(cr.dbname).cursor() orderpoint_obj = self.pool.get('stock.warehouse.orderpoint') procurement_obj = self.pool.get('procurement.order') product_obj = self.pool.get('product.product') dom = company_id and [('company_id', '=', company_id)] or [] orderpoint_ids = orderpoint_obj.search( cr, uid, dom, order="location_id, purchase_calendar_id, calendar_id") prev_ids = [] tot_procs = [] while orderpoint_ids: ids = orderpoint_ids[:1000] del orderpoint_ids[:1000] dates_dict = {} product_dict = {} ops_dict = {} ops = orderpoint_obj.browse(cr, uid, ids, context=context) #Calculate groups that can be executed together for op in ops: key = (op.location_id.id, op.purchase_calendar_id.id, op.calendar_id.id) res_groups = [] if not dates_dict.get(key): date_groups = self._get_group(cr, uid, op, context=context) for date, group in date_groups: if op.calendar_id and op.calendar_id.attendance_ids: date1, date2 = self._get_next_dates( cr, uid, op, date, group, context=context) res_groups += [ (group, date1, date2, date) ] #date1/date2 as deliveries and date as purchase confirmation date else: res_groups += [(group, date, False, date)] dates_dict[key] = res_groups product_dict[key] = [op.product_id] ops_dict[key] = [op] else: product_dict[key] += [op.product_id] ops_dict[key] += [op] for key in product_dict.keys(): for res_group in dates_dict[key]: ctx = context.copy() ctx.update({'location': ops_dict[key][0].location_id.id}) if res_group[2]: ctx.update({ 'to_date': res_group[2].strftime( DEFAULT_SERVER_DATETIME_FORMAT) }) prod_qty = product_obj._product_available( cr, uid, [x.id for x in product_dict[key]], context=ctx) group = res_group[0] date = res_group[1] subtract_qty = orderpoint_obj.subtract_procurements_from_orderpoints( cr, uid, [x.id for x in ops_dict[key]], context=context) first_op = True ndelivery = date and self._convert_to_UTC( cr, uid, date, context=context) or False npurchase = res_group[3] and self._convert_to_UTC( cr, uid, res_group[3], context=context) or False for op in ops_dict[key]: try: prods = prod_qty[ op.product_id.id]['virtual_available'] if prods is None: continue if float_compare(prods, op.product_min_qty, precision_rounding=op.product_uom. rounding) < 0: qty = max(op.product_min_qty, op.product_max_qty) - prods reste = op.qty_multiple > 0 and qty % op.qty_multiple or 0.0 if float_compare(reste, 0.0, precision_rounding=op. product_uom.rounding) > 0: qty += op.qty_multiple - reste if float_compare(qty, 0.0, precision_rounding=op. product_uom.rounding) <= 0: continue qty -= subtract_qty[op.id] qty_rounded = float_round( qty, precision_rounding=op.product_uom.rounding) if qty_rounded > 0: proc_id = procurement_obj.create( cr, uid, self._prepare_orderpoint_procurement( cr, uid, op, qty_rounded, date=ndelivery, purchase_date=npurchase, group=group, context=context), context=context) tot_procs.append(proc_id) orderpoint_obj.write( cr, uid, [op.id], { 'last_execution_date': datetime.utcnow().strftime( DEFAULT_SERVER_DATETIME_FORMAT) }, context=context) if use_new_cursor: cr.commit() except OperationalError: if use_new_cursor: orderpoint_ids.append(op.id) cr.rollback() continue else: raise try: tot_procs.reverse() self.run(cr, uid, tot_procs, context=context) tot_procs = [] if use_new_cursor: cr.commit() except OperationalError: if use_new_cursor: cr.rollback() continue else: raise if use_new_cursor: cr.commit() if prev_ids == ids: break else: prev_ids = ids if use_new_cursor: cr.commit() cr.close() return {}
def _create_bars(self, cr, uid, ids, report, fields, results, context): pool = yuancloud.registry(cr.dbname) pdf_string = cStringIO.StringIO() can = canvas.init(fname=pdf_string, format='pdf') can.show(80,380,'/16/H'+report['title']) process_date = { 'D': lambda x: reduce(lambda xx, yy: xx + '-' + yy, x.split('-')[1:3]), 'M': lambda x: x.split('-')[1], 'Y': lambda x: x.split('-')[0] } order_date = { 'D': lambda x: time.mktime((2005, int(x.split('-')[0]), int(x.split('-')[1]), 0, 0, 0, 0, 0, 0)), 'M': lambda x: x, 'Y': lambda x: x } ar = area.T(size=(350,350), x_axis = axis.X(label = fields[0]['name'], format="/a-30{}%s"), y_axis = axis.Y(label = ', '.join(map(lambda x : x['name'], fields[1:])))) idx = 0 date_idx = None fct = {} for f in fields: field_id = (f['field_child3'] and f['field_child3'][0]) or (f['field_child2'] and f['field_child2'][0]) or (f['field_child1'] and f['field_child1'][0]) or (f['field_child0'] and f['field_child0'][0]) if field_id: type = pool['ir.model.fields'].read(cr, uid, [field_id],['ttype']) if type[0]['ttype'] == 'date': date_idx = idx fct[idx] = process_date[report['frequency']] else: fct[idx] = lambda x : x else: fct[idx] = lambda x : x idx+=1 # plot are usually displayed year by year # so we do so if the first field is a date data_by_year = {} if date_idx is not None: for r in results: key = process_date['Y'](r[date_idx]) if key not in data_by_year: data_by_year[key] = [] for i in range(len(r)): r[i] = fct[i](r[i]) data_by_year[key].append(r) else: data_by_year[''] = results nb_bar = len(data_by_year)*(len(fields)-1) colors = map(lambda x:fill_style.Plain(bgcolor=x), misc.choice_colors(nb_bar)) abscissa = {} for line in data_by_year.keys(): fields_bar = [] # sum data and save it in a list. An item for a fields for d in data_by_year[line]: for idx in range(len(fields)-1): fields_bar.append({}) if d[0] in fields_bar[idx]: fields_bar[idx][d[0]] += d[idx+1] else: fields_bar[idx][d[0]] = d[idx+1] for idx in range(len(fields)-1): data = {} for k in fields_bar[idx].keys(): if k in data: data[k] += fields_bar[idx][k] else: data[k] = fields_bar[idx][k] data_cum = [] prev = 0.0 keys = data.keys() keys.sort() # cumulate if necessary for k in keys: data_cum.append([k, float(data[k])+float(prev)]) if fields[idx+1]['cumulate']: prev += data[k] idx0 = 0 plot = bar_plot.T(label=fields[idx+1]['name']+' '+str(line), data = data_cum, cluster=(idx0*(len(fields)-1)+idx,nb_bar), fill_style=colors[idx0*(len(fields)-1)+idx]) ar.add_plot(plot) abscissa.update(fields_bar[idx]) idx0 += 1 abscissa = map(lambda x : [x, None], abscissa) abscissa.sort() ar.x_coord = category_coord.T(abscissa,0) ar.draw(can) can.close() self.obj = external_pdf(pdf_string.getvalue()) self.obj.render() pdf_string.close() return True
def create(self, cr, uid, ids, datas, context=None): if not context: context={} self.pool = yuancloud.registry(cr.dbname) report = self.pool['ir.report.custom'].browse(cr, uid, [datas['report_id']])[0] datas['model'] = report.model_id.model if report.menu_id: ids = self.pool[report.model_id.model].search(cr, uid, []) datas['ids'] = ids report_id = datas['report_id'] report = self.pool['ir.report.custom'].read(cr, uid, [report_id], context=context)[0] fields = self.pool['ir.report.custom.fields'].read(cr, uid, report['fields_child0'], context=context) fields.sort(lambda x,y : x['sequence'] - y['sequence']) if report['field_parent']: parent_field = self.pool['ir.model.fields'].read(cr, uid, [report['field_parent'][0]], ['model']) model_name = self.pool['ir.model'].read(cr, uid, [report['model_id'][0]], ['model'], context=context)[0]['model'] fct = { 'id': lambda x: x, 'gety': lambda x: x.split('-')[0], 'in': lambda x: x.split(',') } new_fields = [] new_cond = [] for f in fields: row = [] cond = [] for i in range(4): field_child = f['field_child'+str(i)] if field_child: row.append( self.pool['ir.model.fields'].read(cr, uid, [field_child[0]], ['name'], context=context)[0]['name'] ) if f['fc'+str(i)+'_operande']: fct_name = 'id' cond_op = f['fc'+str(i)+'_op'] if len(f['fc'+str(i)+'_op'].split(',')) == 2: cond_op = f['fc'+str(i)+'_op'].split(',')[1] fct_name = f['fc'+str(i)+'_op'].split(',')[0] cond.append((fct[fct_name], f['fc'+str(i)+'_operande'][1], cond_op, f['fc'+str(i)+'_condition'])) else: cond.append(None) new_fields.append(row) new_cond.append(cond) objs = self.pool[model_name].browse(cr, uid, ids) # Group by groupby = None idx = 0 for f in fields: if f['groupby']: groupby = idx idx += 1 results = [] if report['field_parent']: level = [] def build_tree(obj, level, depth): res = self._row_get(cr, uid,[obj], new_fields, new_cond) level.append(depth) new_obj = eval('obj.'+report['field_parent'][1],{'obj': obj}) if not isinstance(new_obj, list) : new_obj = [new_obj] for o in new_obj: if o: res += build_tree(o, level, depth+1) return res for obj in objs: results += build_tree(obj, level, 0) else: results = self._row_get(cr, uid,objs, new_fields, new_cond, group_by=groupby) fct = { 'calc_sum': lambda l: reduce(lambda x,y: float(x)+float(y), filter(None, l), 0), 'calc_avg': lambda l: reduce(lambda x,y: float(x)+float(y), filter(None, l), 0) / (len(filter(None, l)) or 1.0), 'calc_max': lambda l: reduce(lambda x,y: max(x,y), [(i or 0.0) for i in l], 0), 'calc_min': lambda l: reduce(lambda x,y: min(x,y), [(i or 0.0) for i in l], 0), 'calc_count': lambda l: len(filter(None, l)), 'False': lambda l: '\r\n'.join(filter(None, l)), 'groupby': lambda l: reduce(lambda x,y: x or y, l) } new_res = [] prev = None if groupby is not None: res_dic = {} for line in results: if not line[groupby] and prev in res_dic: res_dic[prev].append(line) else: prev = line[groupby] res_dic.setdefault(line[groupby], []) res_dic[line[groupby]].append(line) #we use the keys in results since they are ordered, whereas in res_dic.heys() they aren't for key in filter(None, [x[groupby] for x in results]): row = [] for col in range(len(fields)): if col == groupby: row.append(fct['groupby'](map(lambda x: x[col], res_dic[key]))) else: row.append(fct[str(fields[col]['operation'])](map(lambda x: x[col], res_dic[key]))) new_res.append(row) results = new_res if report['type']=='table': if report['field_parent']: res = self._create_tree(uid, ids, report, fields, level, results, context) else: sort_idx = 0 for idx in range(len(fields)): if fields[idx]['name'] == report['sortby']: sort_idx = idx break try : results.sort(lambda x,y : cmp(float(x[sort_idx]),float(y[sort_idx]))) except : results.sort(lambda x,y : cmp(x[sort_idx],y[sort_idx])) if report['limitt']: results = results[:int(report['limitt'])] res = self._create_table(uid, ids, report, fields, None, results, context) elif report['type'] in ('pie','bar', 'line'): results2 = [] prev = False for r in results: row = [] for j in range(len(r)): if j == 0 and not r[j]: row.append(prev) elif j == 0 and r[j]: prev = r[j] row.append(r[j]) else: try: row.append(float(r[j])) except Exception: row.append(r[j]) results2.append(row) if report['type']=='pie': res = self._create_pie(cr,uid, ids, report, fields, results2, context) elif report['type']=='bar': res = self._create_bars(cr,uid, ids, report, fields, results2, context) elif report['type']=='line': res = self._create_lines(cr,uid, ids, report, fields, results2, context) return self.obj.get(), 'pdf'