def create_lead(self, *args): lead_enable = self.env.user.has_group('crm.group_use_lead') if lead_enable: record_set = () for arg in args: record_set = self.browse(arg[0]) length = len(record_set) if length == 1: if record_set.parent_type == 'Contact': parent = self.env["crm.lead"].create({ 'name': record_set.peer_name if record_set.peer_name != '' else record_set.phone, 'phone': record_set.phone }) record_set.write({ 'parent_type': 'Lead', 'parent_id': parent.id }) return { 'name': 'crm.lead.form', 'type': 'ir.actions.act_window', 'views': [[False, "form"]], 'res_id': parent.id, 'res_model': 'crm.lead', 'target': 'new', } else: raise osv.except_osv( _('Forbbiden to create Lead'), _('Something got wrong!! Cannot create Lead')) else: raise osv.except_osv(_('Forbbiden to create Lead'), _('Leads are not enable from CRM'))
def new_post_up(self): if self.RAMP_ID.ramp_state == "deactivated" or self.RAMP_ID.ramp_state == "not_added": raise exceptions.except_orm(_('The ramp is not active.'), _("Admin should activate the ramp!")) if self.RAMP_ID.state == 'up': raise osv.except_osv(('Repeated action'), ("The ramp is already UP!")) if self.RAMP_ID.state == 'error': raise osv.except_osv(('Error occured'), ("Please press ALERT!")) url = self.env['ir.values'].get_default('ramp.config.settings', 'InitAction_url') r_post = requests.post(url, json={ "RampId": self.RAMP_ID.ramp_number, "Action": "1", "User": "", "Latitude": "123", "Longitude": "243" }) if r_post.status_code == 200 and json.loads(str( r_post._content))['Success']: self.RAMP_ID.state = 'up' time.sleep(3) else: self.RAMP_ID.state = "error"
def check_format_file_excel(self, file_name): if file_name == False: raise osv.except_osv("Warning!", ("File name not found")) if file_name.endswith('.xls') == False and file_name.endswith( '.xlsx') == False: self.file_import = None self.file_import_name = None raise osv.except_osv("Error!", ("Change the file type as .xlsx or .xls"))
def send_pick(self): order = self.env['sale.order'].search([('name', '=', self.origin)]) secret = order.shop_id.secret appkey = order.shop_id.appkey sessionkey = order.shop_id.sessionkeysecret = order.shop_id.appsecret url = order.shop_id.apiurl carrier_tracking_ref = self.carrier_tracking_ref port = 80 # 对接菜鸟面单获取运单号 tid = order.order_num if "," in tid: x_a = tid.split(",") x = 0 for x in x_a: if carrier_tracking_ref: # 根据获取的运单号进行自动发货 setDefaultAppInfo(appkey, secret) req = LogisticsOfflineSendRequest(url, port) req.tid = x_a[x] req.out_sid = carrier_tracking_ref # 运单号 req.company_code = self.carrier_id.taob_code resp = req.getResponse(sessionkey) if "error_response" in resp: raise osv.except_osv(u'警告', resp['error_response']['sub_msg']) else: jieguo = resp.get( 'logistics_offline_send_response').get( 'shipping', False) succes = jieguo.get('is_success') if succes: super(stock_picking, self).do_new_transfer() else: raise osv.except_osv(u'警告', u"自动发货失败,请查看是否有异常数据") else: raise osv.except_osv(u'警告', u"运单号异常,请进行查看") else: # 根据获取的运单号进行自动发货 setDefaultAppInfo(appkey, secret) req = LogisticsOfflineSendRequest(url, port) req.tid = order.name req.out_sid = carrier_tracking_ref # 运单号 req.company_code = self.carrier_id.taob_code resp = req.getResponse(sessionkey) if "error_response" in resp: raise osv.except_osv(u'警告', resp['error_response']['sub_msg']) else: jieguo = resp.get('logistics_offline_send_response').get( 'shipping', False) succes = jieguo.get('is_success') if succes: super(stock_picking, self).do_new_transfer() else: raise osv.except_osv(u'警告', u"自动发货失败,请查看是否有异常数据")
def action_buy_postge(self): """ This function is used to Re-credit Endicia Account parameters: No Parameters """ post_balance = 1 ship_endicia = self.env['shipping.usps'].get_endicia_info() requester_id = ship_endicia.requester_id account_id = ship_endicia.account_id passphrase = ship_endicia.passphrase debug = ship_endicia.test tot_rate = self.name if tot_rate < 10.00: raise osv.except_osv(_('Warning'), _('You cannot buy postage less than $10')) try: # request = endicia.RecreditRequest(requester_id, account_id, passphrase, tot_rate, debug=debug) # response = request.send() # buy_postage_resp = response._get_value() res = self.buying_soap(requester_id, account_id, passphrase, str(tot_rate)) response = json.loads(res) # buy_postage_resp = response.text.encode('utf8') recredit_req = response.get("soap:Envelope").get("soap:Body").get( "BuyPostageResponse").get("RecreditRequestResponse") if 'ErrorMessage' in recredit_req: print("There is an error") Certified_Intermediary = recredit_req.get( "CertifiedIntermediary") post_balance = Certified_Intermediary.get('PostageBalance') print(post_balance) else: Certified_Intermediary = recredit_req.get( "CertifiedIntermediary") post_balance = Certified_Intermediary.get('PostageBalance') print(post_balance) except Exception as e: raise osv.except_osv(_('Error'), _('Error buying postage')) message = _( 'Remaining postage balance: %s\nTotal amount of postage printed:' % (post_balance)) if message: raise osv.except_osv(_('Message'), _(message)) # message = _('Remaining postage balance: %s\nTotal amount of postage printed: %s' % ( # buy_postage_resp['postage_balance'], buy_postage_resp['postage_printed'])) # if message: # raise osv.except_osv(_('Message'), _(message)) return {'type': 'ir.actions.act_window_close'}
def import_shipping_fee_return(self, context=None): # kiểm tra file có rỗng if self.file_import is None: raise osv.except_orm('Error', 'File is not empty') # Kiểm tra định dạng file self.check_format_file_excel(self.file_import_name) # tiến hành đọc file file_import = self.file_import data = base64.decodestring(file_import) excel = xlrd.open_workbook(file_contents=data) sheet = excel.sheet_by_index(0) try: index = 1 so_obj = self.env['sale.order'] excep_so = [] dublicate_ship = [] index2 = 1 while index2 < sheet.nrows: shipping_id2 = sheet.cell(index2, 1).value if self.is_number(shipping_id2) == True: shipping_id2 = str(int(shipping_id2)) sale_order = so_obj.search( [('shipping_id_return', '=', shipping_id2)], limit=1) if sale_order: dublicate_ship.append(shipping_id2) index2 = index2 + 1 if dublicate_ship: message = "Mã Vận Đơn Hoàn Đã Tồn Tại : " + str( ",".join(dublicate_ship)) raise osv.except_osv("Cảnh báo !", message) while index < sheet.nrows: name = sheet.cell(index, 0).value shipping_id = sheet.cell(index, 1).value if self.is_number(shipping_id) == True: value_shipping = str(int(shipping_id)) else: value_shipping = shipping_id if self.is_number(name) == True: message = "Tên SO không thể là số: " + str(index + 1) raise osv.except_osv("Cảnh báo !", message) sale_order = so_obj.search([('name', '=', name)], limit=1) if sale_order: sale_order.write({'shipping_id_return': value_shipping}) else: excep_so.append(name) index = index + 1 if excep_so: message = "Không tìm thấy SO : " + str(",".join(excep_so)) raise osv.except_osv("Cảnh báo !", message) self.file_import = None except IndexError: raise osv.except_orm("Error", "Thiếu cột dữ liệu")
def create(self, data): config_value = self.config_value config_query = config_value['config_query'] delimiter = str(config_value['delimiter']) quotechar = str(config_value['quotechar']) header = config_value['header'] query_type = config_value['query_type'] active_ids = self.env.context.get('active_ids', []) if query_type != 'sql': raise osv.except_osv(('Error !'), ("Not supported yet! Use SQL instead")) if '%s' in config_query and 'ea_export.config' not in [ self.env.context.get('active_model'), self.env.context.get('filter_model') ] and active_ids: format_param = str(tuple(active_ids)) if len(active_ids) > 1 else ( '(' + str(active_ids[0]) + ')') variables_count = config_query.count('%s') if variables_count > 1: format_param = tuple(format_param for variable in xrange(variables_count)) query = config_query % format_param elif '%s' in config_query and 'ea_export.config' in [ self.env.context.get('active_model'), self.env.context.get('filter_model') ]: raise osv.except_osv(('Error !'), ( "You can execute query with '%s' formatting from {model} model only!" .format(model=config_value.get('related_model')))) else: query = config_query if re.match(r'CREATE|DROP|UPDATE|DELETE', query, re.IGNORECASE): raise osv.except_osv(('Error !'), ("Operation prohibitet!")) try: self._cr.execute(query) except: raise osv.except_osv(('Error !'), ("Invalid Query")) output = cStringIO.StringIO() csvwriter = csv.writer(output, delimiter=delimiter, quotechar=quotechar) if header: csvwriter.writerow([i[0] for i in self._cr.description]) # heading row out = self._cr.fetchall() csvwriter.writerows(out) output_string = output.getvalue() output.close() return output_string, 'csv'
def check_lock_name(self, vals): # Check if name is allowed to be modified acc_move_line_obj = self.env['account.move.line'] if vals.get('customer', self.customer): if self.customer_type.lock_partner_name \ and acc_move_line_obj.search([('account_id', '=', self.property_account_receivable_id.id)]): raise osv.except_osv(_('Error'), _('You cannot change partner\'s name when his account has moves')) if vals.get('supplier',self.supplier): if self.supplier_type.lock_partner_name \ and acc_move_line_obj.search([('account_id', '=', self.property_account_payable_id.id)]): raise osv.except_osv(_('Error'), _('You cannot change partner\'s name when his account has moves'))
def activate(self): if self.ramp_state == "activated": raise osv.except_osv(('The ramp is already activated!'), ("Please calm down :) !")) if self.ramp_state == "deactivated" or self.ramp_state == "not_added": url = self.env['ir.values'].get_default('ramp.config.settings', 'AddRamp_url') r_put = requests.put(url, json={"RampId": self.ramp_number, "Action": "1", "User": "", "Latitude": "123", "Longitude": "243"}) if r_put.status_code == 200 and json.loads(str(r_put._content))['Success']: self.ramp_state = 'activated' else: raise osv.except_osv(('ERROR!'), ("Something is not right!"))
def oke(self): parent_id = self._context['parent_obj'] chil = self.env['itb.plan_wizard_find_child'].search([ ('wiz_find_id', '=', self.id), ('total', '>', 0) ]) parent = self.env['itb.plan_request'].search([('id', '=', parent_id)]) if chil: tot = sum(chil.mapped('total')) if self.total == tot: parent.write({ 'alocation_total': self.total, }) parent.write({ 'source_total': self.total, }) child_taken = self.env['itb.plan_request_line'] child_alo = self.env['itb.plan_request_alocation'] for rec in chil: child_taken.create({ 'request_id': parent_id, 'spending_actual_id': rec.sp_act_id.id, 'total': rec.total, }) #self.env['itb.plan_request_line'].create({'request_id' : rec.parent_id.id, 'spending_actual_id' : rec.sp_act_id.id, 'total' : rec.total,}) alo = self.env['itb.plan_allocation'].search( [('spending_id', '=', rec.spending_id.id)], limit=1) if alo: #self.env['itb.plan_request_alocation'].create({'request_alo_id' : rec.parent_id.id, 'spending_id' : alo.spending_id_int.id, 'total_alo' : rec.total,}) child_alo.create({ 'request_alo_id': parent_id, 'spending_id': alo.spending_id_int.id, 'total_alo': rec.total, }) else: raise osv.except_osv('Total Request no equal with total Taken')
def generate_csv(self): for config in self: if not config.ir_act_report_id: raise osv.except_osv(('Error !'), ("Create report first")) name = 'report.' + config.ir_act_report_id.report_name config_value = { 'report_name': config.ir_act_report_id.report_name, 'config_id': config.id, 'related_model': config.model_id.name, 'config_query': config.query, 'delimiter': config.delimiter, 'quotechar': config.quotechar, 'header': config.header, 'query_type': config.query_type } export_class = CsvExportOpenERPInterface(name, config_value) output, format = export_class.with_context(active_ids=[]).with_context( active_model='ea_export.config').create({'report_type': u'csv'}) if output: return { 'type': 'ir.actions.report.xml', 'report_name': config.ir_act_report_id.report_name, }
def quickly_create_user(self, cr, uid, ids, context=None): res_users = self.pool.get('res.users') # Make this an option context = dict(context or {}, no_reset_password=True) # TODO Pasar argumentos para activar o desactivar create_user = True for partner in self.browse(cr, SUPERUSER_ID, ids, context): group_ids = [] if not partner.template_user_id: raise osv.except_osv(_('Non template user selected!'), _('Please define a template user for this partner: "%s" (id:%d).') % (partner.name, partner.id)) group_ids = [x.id for x in partner.template_user_id.groups_id] user_ids = self.retrieve_user(cr, SUPERUSER_ID, partner, context) if create_user: # create a user if necessary, and make sure it is in the portal # group if not user_ids: user_ids = [ self._create_user(cr, SUPERUSER_ID, partner, context)] res_users.write( cr, SUPERUSER_ID, user_ids, {'active': True, 'groups_id': [(6, 0, group_ids)]}) # prepare for the signup process # TODO make an option of this # partner.signup_prepare() # TODO option to send or not email # self._send_email(cr, uid, partner, context) elif user_ids: # deactivate user res_users.write(cr, SUPERUSER_ID, user_ids, {'active': False})
def create_contact(self, *args): record_set = () for arg in args: record_set = self.browse(arg[0]) length = len(record_set) if length == 1: if record_set.parent_type: raise osv.except_osv( _('Forbbiden to create Contact'), _('Something got wrong!! Cannot create contact')) else: parent = self.env["res.partner"].create({ 'name': record_set.peer_name if record_set.peer_name != '' else record_set.phone, 'phone': record_set.phone }) record_set.write({ 'parent_type': 'Contact', 'parent_id': parent.id }) return { 'type': 'ir.actions.act_window', 'views': [[False, "form"]], 'res_id': parent.id, 'res_model': 'res.partner', 'target': 'new', }
def _next(self): force_company = self._context.get('force_company') if not force_company: force_company = self.env['res.users'].browse().company_id.id sequences = self.read( ['name', 'company_id', 'implementation', 'number_next', 'prefix', 'suffix', 'padding', 'number_increment', 'auto_reset', 'reset_period', 'reset_time', 'reset_init_number']) preferred_sequences = [s for s in sequences if s['company_id'] and s['company_id'][0] == force_company] seq = preferred_sequences[0] if preferred_sequences else sequences[0] if seq['implementation'] == 'standard': current_time = ':'.join([seq['reset_period'], self._interpolation_dict().get(seq['reset_period'])]) if seq['auto_reset'] and current_time != seq['reset_time']: self._cr.execute("UPDATE ir_sequence SET reset_time=%s WHERE id=%s ", (current_time, seq['id'])) _alter_sequence(self._cr, 'ir_sequence_%03d' % self.id, seq['number_increment'], seq['reset_init_number']) self._cr.commit() number_next = _select_nextval(self._cr, 'ir_sequence_%03d' % self.id) # self._cr.execute("SELECT nextval('%s')" % seq['name']) seq['number_next'] = number_next else: self._cr.execute("SELECT number_next FROM ir_sequence WHERE id=%s FOR UPDATE NOWAIT", (seq['id'],)) self._cr.execute("UPDATE ir_sequence SET number_next=number_next+number_increment WHERE id=%s ", (seq['id'],)) d = self._interpolation_dict() try: interpolated_prefix = self._interpolate(seq['prefix'], d) interpolated_suffix = self._interpolate(seq['suffix'], d) except ValueError: raise osv.except_osv(_('Warning'), _('Invalid prefix or suffix for sequence \'%s\'') % (seq.get('name'))) return interpolated_prefix + '%%0%sd' % seq['padding'] % seq['number_next'] + interpolated_suffix
def yes(self): part_id = self._context['parent_id'] parent = self.env['itb.plan_request'].search([('id', 'in', part_id)]) reim = self.env['itb.plan_reimburse'] tgl = date.today() if self.existing == False: nama = 'Reimburse - (' + str(tgl.year) + '-' + str( tgl.month) + '-' + str(tgl.day) + ')' reim.create({ 'name': nama, 'date_reimburse': tgl, 'state': 'draft', }) reimburse = self.env['itb.plan_reimburse'].search( [('name', '=', nama), ('date_reimburse', '=', tgl), ('state', '=', 'draft')], order='id desc', limit=1) reim_id = reimburse.id else: reim_id = self.reimburse_id.id if reim_id: #raise osv.except_osv(str(reim_id)) parent.write({ 'reimburse_id': reim_id, 'is_reconciled': True, }) else: raise osv.except_osv('Not Valid Data Reimbuse Not Selected')
def create(self,vals): """ create sms and send to twilio """ try: account_id = vals.get('account_id') sms_body = vals.get('sms_body', '') sms_to = vals.get('sms_to') sms_from = vals.get('sms_from') if not account_id: twilio_account_obj = self.env['twilio.accounts'] account_id = twilio_account_obj.get_account_id()[0] message = self.send_sms() msg_send_id = super(twilio_sms_send, self).create(vals) # NOTE: prepare vals for successful send sms update_vals = { 'message_sid': message.sid, 'account_id': account_id, 'account_sid': message.account_sid, 'direction': message.direction, 'status': message.status, 'price': message.price, 'price_unit': message.price_unit, 'error_msg': message.error_message, 'error_code': message.error_code, } res = super(twilio_sms_send, self).write(msg_send_id,update_vals) return msg_send_id except TwilioRestException as e: raise osv.except_osv(_('Warning!'), _('Error Code: ' + str(e.code) + '\n Error Message: ' + e.msg))
def action_view_commission_invoice(self): if self.supplier_invoice: imd = self.env['ir.model.data'] action = imd.xmlid_to_object('account.action_invoice_tree2') form_view_id = imd.xmlid_to_res_id('account.invoice_supplier_form') result = { 'name': action.name, 'help': action.help, 'type': action.type, 'views': [[False, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'], [False, 'calendar'], [False, 'pivot']], 'target': action.target, 'context': action.context, 'res_model': action.res_model, } result['views'] = [(form_view_id, 'form')] result['res_id'] = self.supplier_invoice.id return result else: raise osv.except_osv(_('Warning'), ("Order has no related commission record!"))
def action_view_commission(self): commission_ids = self.env['commission.commission'].search([ ('sale_order', '=', self.id) ]) if commission_ids: imd = self.env['ir.model.data'] action = imd.xmlid_to_object( 'sale_consignment.wk_commission_action') form_view_id = imd.xmlid_to_res_id( 'sale_consignment.commission_from_view') result = { 'name': action.name, 'help': action.help, 'type': action.type, 'views': [[False, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'], [False, 'calendar'], [False, 'pivot']], 'target': action.target, 'context': action.context, 'res_model': action.res_model, } result['views'] = [(form_view_id, 'form')] result['res_id'] = commission_ids and commission_ids.id or False return result else: raise osv.except_osv(_('Warning'), ("Order has no related commission record!"))
def action_apply(self): """ Convert lead to opportunity or merge lead and opportunity and open the freshly created opportunity view. """ quo = self.pool.get('sale.quotation') check = self.pool.get('cam.engineering.check') quo_line_pool = self.pool.get('sale.quotation.line') w = self.browse(self.ids)[0] lead_ids = self.env.context.get('active_ids', []) lead_id = self.env.context.get('active_id') row_lead_id = quo.browse(lead_id).lead_id.id self._convert_sale_order({'lead_ids': [row_lead_id]}) data = quo.browse(lead_id) partner = data.lead_id.partner_id and data.lead_id.partner_id.id #partner = w.partner_id and w.partner_id.id quo.write(lead_id, {'partner_id':partner,'partner_invoice_id':partner,'partner_shipping_id':partner}) for row in data.quotation_line: check.write(row.cam_check.id, {'partner_id':partner}) for row in w.confirm_line: quo_l_rows = quo_line_pool.search([('quotation_id','=',lead_id),('customer_file_name','=',row.customer_file_name)]) if len(quo_l_rows) >1: raise osv.except_osv(_('Customer File Name Error!'), _('Find the same file name!')) #quo_l_rows = quo_line_pool.browse(cr, uid, quo_l_rows, context=context) quo_line_pool.write(quo_l_rows[0], {'product_no':row.product_no}) q_row = quo_line_pool.browse(quo_l_rows[0]) self.pool.get('cam.engineering.check').write(q_row.cam_check.id, {'product_no':row.product_no}) quo.onchange_partner_id(lead_ids, partner) #return self.pool.get('sale.quotation').redirect_quotation_view(cr, uid, lead_ids[0], context=context) return self.pool.get('sale.quotation').action_done(lead_ids)
def deactivate(self): if self.ramp_state == "deactivated": raise osv.except_osv(('The ramp is already deactivated!'), ("Please calm down :) !")) if self.ramp_state == "activated" or self.ramp_state == "not_added": url = self.env['ir.values'].get_default('ramp.config.settings', 'RemoveRamp_url') r_delete = requests.delete(url, json={"RampId": self.ramp_number, "Action": "0", "User": "", "Latitude": "123", "Longitude": "243"}) if r_delete.status_code == 200: self.ramp_state = 'deactivated' self.state = 'down' else: raise osv.except_osv(('ERROR!'), ("Something is not right!"))
def unlink(self): for line in self: if line.move_id.automove and not line.move_id.fixable_automatic_asset: raise osv.except_osv(_('User Error!'), _('You cannot delete any line of an automatic entry "%s".') % \ line.move_id['name']) return super(AccountMoveLine, self).unlink()
def refuse_money(self): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') url = self.acquirer_id.form_url valus = { '_input_charset': 'UTF-8', 'notify_url': '%s' % urlparse.urljoin(base_url, '/payment/chanpay/refuse/'), 'orig_outer_trade_no': self.acquirer_reference, 'outer_trade_no': self.reference, 'partner_id': self.acquirer_id.partner_id, 'refund_amount': self.amount, 'service': 'cjt_create_refund', 'sign_type': 'RSA', 'version': '1.0', } params, sign = func.buildRequestMysign(valus, self.acquirer_id.private_key) valus.update({ 'sign': sign, }) _, prestr = func.params_filter_add(valus) geturl = url + prestr # raise osv.except_osv(u'警告', geturl) request = urllib2.Request(geturl) data = urllib2.urlopen(request).read() get_data = json.loads(data) if get_data: if 'error_message' in get_data: raise osv.except_osv(u'警告', get_data.get('error_message') + "====" + get_data.get('memo')) else: self.refund_status = '1'
def install_report(self, cr, uid, ids, context=None): report_obj = self.pool.get('ir.actions.report') this = self.browse(cr, uid, ids[0], context=context) if report_obj.search(cr, uid, [('report_name', '=', this.name)], context=context): raise osv.except_osv( _('Warning!'), _('Report with service name "%s" already exist in system!') % this.name) fd = StringIO() fd.write(base64.decodestring(this.file)) fd.seek(0) convert_xml_import(cr, 'report_aeroo', fd, {}, 'init', noupdate=True) fd.close() self.write(cr, uid, ids, {'state': 'done'}, context=context) report_id = report_obj.search(cr, uid, [('report_name', '=', this.name)], context=context)[-1] report = report_obj.browse(cr, uid, report_id, context=context) event_id = self.pool.get('ir.values').set_action( cr, uid, report.report_name, 'client_print_multi', report.model, 'ir.actions.report,%d' % report_id) if report.report_wizard: report._set_report_wizard(report.id) mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') mod_id = mod_obj.search( cr, uid, [('name', '=', 'action_aeroo_report_xml_tree')])[0] res_id = mod_obj.read(cr, uid, mod_id, ['res_id'])['res_id'] act_win = act_obj.read(cr, uid, res_id, []) act_win['domain'] = [('id', '=', report_id)] return act_win
def send_info(self): feedback_demo = self.feedback_demo dbname = self.feedback_demo username = '******' pwd = 'aaa123' common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format( self.feedback_url)) models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format( self.feedback_url)) uid = common.authenticate(feedback_demo, username, pwd, {}) if uid: print self.info_num # 查询一条或多条记录,返回id args_id = models.execute(dbname, uid, pwd, 'question.info', 'search', [('info_num', '=', self.info_num)]) values = {'result_info': self.result_info} result1 = models.execute(self.feedback_demo, uid, pwd, 'question.info', 'write', args_id, values) if result1: return True else: return False else: raise osv.except_osv( u'警告', "该问题的反馈者的身份存在问题,请联系管理员进行处理," "\n 地址:" + self.feedback_url + " \n 反馈账套:" + self.feedback_demo + " \n 反馈者:" + self.feedback_submitter)
def get_most_used_parts(self, date_range, top_no): work_order_obj = self.env['task.line'] part_list_data = [] used_dict = {} work_order_ids = \ work_order_obj.search( [('date_issued', '>=', date_range.get('date_from')), ('date_issued', '<=', date_range.get('date_to'))]) if work_order_ids: for p_line in work_order_ids: if p_line.fleet_service_id and \ p_line.fleet_service_id.state == 'done': if used_dict.get(p_line.product_id.id, False): used_dict[p_line.product_id.id]['qty'] += \ p_line.qty or 0.0 used_dict[p_line.product_id.id]['total_cost'] = \ used_dict[p_line.product_id.id]['qty'] * \ p_line.product_id.standard_price else: used_dict[p_line.product_id.id] = \ { 'part_no': p_line.product_id and p_line.product_id.default_code or '', 'part_name': p_line.product_id and p_line.product_id.name or '', 'vehicle_make': p_line.product_id and p_line.product_id.vehicle_make_id and p_line.product_id.vehicle_make_id.name or '', 'qty': p_line.qty or 0.0, 'qty_available': p_line.product_id and p_line.product_id.qty_available, 'uom': p_line.product_id and p_line.product_id.uom_id and p_line.product_id.uom_id.name or '', 'unit_cost': p_line.product_id and p_line.product_id.standard_price or 0.0, 'total_cost': p_line.qty * p_line.product_id.standard_price, } for part_data in used_dict.itervalues(): part_list_data.append(part_data) if part_list_data: part_list_data = sorted(part_list_data, key=lambda k: k['qty'], reverse=True) else: raise osv.except_osv(('Warning!'), ("No parts were used in selected date.")) flag = 1 final_data = [] for data in part_list_data: if flag <= top_no: self.most_part_used_garnd_total += data.get('total_cost') final_data.append(data) else: break flag += 1 return final_data
def invoice_refund(self): """ Create a invoice refund """ context = self._context or {} inv_obj = self.env['account.invoice'] #period_obj = self.env['account.period'] wzr_brw = self.browse(self._ids)[0] date = wzr_brw.date and wzr_brw.date.split('-') #period = wzr_brw and wzr_brw.period and wzr_brw.period.id #period_ids = date and len(date) == 3 and period_obj.search( # [('code', '=', '%s/%s' % (date[1], date[0]))]) #if period not in period_ids: # raise osv.except_osv( # _('Error !'), # _('The date should be chosen to belong to the period')) if not self.validate_wh(): inv = inv_obj.browse(context.get('active_ids'))[0] raise osv.except_osv( _('Error !'), _('There are non-valid withholds for the document %s which' ' refund is being processed!' % inv and inv.wh_iva_id.code or "vacio")) self.unreconcile_paid_invoices(context.get('active_ids')) data_refund = self.browse(self._ids)[0].filter_refund return self.compute_refund(data_refund)
def recognise(self, id): """查询输出数据""" # url = 'http://testapi.kdniao.cc:8081/Ebusiness/EbusinessOrderHandle.aspx' url = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx" valus = self.env['stock.picking'].search([('id', '=', id)]) expresscode = valus.carrier_tracking_ref data = self.get_default_appid(fields) key = data['key'] EBusinessID = data['customer'] if valus.carrier_id: trace_data = self.get_traces(expresscode, valus.carrier_id.code, EBusinessID, key, url) else: data = self.get_company(expresscode, EBusinessID, key, url) trace_data = {} if data['ShipperCode']: if data['Success'] == False: Reason = data['Reason'] else: trace_data = self.get_traces( expresscode, data['Shippers'][0]['ShipperCode'], EBusinessID, key, url) else: raise osv.except_osv(u'警告', "未能识别该单号") return trace_data
def unlink(self): for move in self: if move.automove and not move.fixable_automatic_asset: raise osv.except_osv(_('User Error!'), _('You cannot delete an automatic entry "%s".') % \ move['name']) return super(AccountMove, self).unlink()
def check_di(self): company = self.env['res.company']._company_default_get('mapamas') if company.partner_id.x_mapama_usuario == False or company.partner_id.x_mapama_pw == False: raise osv.except_osv( ('Usuario plataforma'), ('Usuario o Contraseña para el servicio no definida')) if company.partner_id.x_tipocentro_id.x_codigo == False or company.partner_id.x_nima_mapama == False: raise osv.except_osv(('Tipo de Centro y NIMA'), ('Tipo de Centro o NIMA no deffinido')) if self.x_di_id.x_operador_autorizacion_id.x_name == False or self.x_di_id.x_operador_tipo_mapama_id == False: raise osv.except_osv(('Autorización'), ('Código o Número de autorización deffinido')) result = self.send2mapama() if result != 0: self.x_estado = "El servidor ha rechazado la comuniación"
def button_cancel(self): for move in self: if move.automove and not move.fixable_automatic_asset: raise osv.except_osv( _('Error!'), _('You cannot modify an automatic entry.\nOtherwise you can revert it.' )) return super(AccountMove, self).button_cancel()