def check_vat(self): for rec in self: # rec.vat can be False if not rec.vat or len(rec.vat) < 2: raise osv.except_orm( _(u"Error !"), _(u"Your vat number length is less than 3")) return super(res_partner_vat, self).check_vat()
def create(self, cr, uid, vals, context=None): if vals['parent_id']: this = self.browse(cr, uid, vals['parent_id'], context=None) policy_obj = this.policy_id vals.update({ 'policy_id': policy_obj.id, 'insurance_period_start': policy_obj.insurance_period_start, 'insurance_period_end': policy_obj.insurance_period_end, }) if policy_obj.policy_category_id.name == 'Individual': #import pdb;pdb.set_trace() if policy_obj.individual_member_limit > 0: if len(this.family_ids ) == policy_obj.individual_member_limit - 1: raise osv.except_orm( ('Warning!'), ("Member limit excessed. Cannot add more than " + str(policy_obj.individual_member_limit) + " member(s) to this Policy.")) if not vals['member_no']: vals.update({ 'member_no': self.pool.get('ir.sequence').get(cr, uid, 'member_seq') or '/', }) return super(netpro_member, self).create(cr, uid, vals, context=context)
def confirm(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context): if self.check_active(cr, uid, context): raise osv.except_orm( 'Error!', 'No pueden haber dos tablas de impuestos activas') self.write(cr, uid, [rec.id], {'state': 'confirm'})
def execute_sql_2_export(self, cr, uid, ids, context=None): condition = self.browse(cr, uid, ids)[0] sql_string = condition.sql_string file_save_path = condition.file_save_path if file_save_path[-4:] != '.xls': raise osv.except_orm('提示!', '文件保存地址不合法,请以“.xls”结尾') connection = psycopg2.connect(database=DATABASE_NAME, user=DATABASE_USER, password=DATABASE_PWD, host=DATABASE_HOST, port=DATABASE_PORT) try: df = pandas.read_sql(sql_string, connection) except Exception, e: raise osv.except_orm('查询失败,请检查SQL语句', '')
def send_email_with_file(self, cr, uid, ids, context=None): condition = self.browse(cr, uid, ids)[0] subject = condition.name email_to = condition.email_to file_path = condition.file_save_path msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = mail_user msg['To'] = email_to xls_part = MIMEApplication(open(file_path, 'rb').read()) xls_part.add_header('Content-Disposition', 'attachment', filename=file_path.split('/')[-1]) msg.attach(xls_part) try: client = smtplib.SMTP() client.connect(mail_host) client.login(mail_user, mail_pwd) client.sendmail(mail_user, email_to, msg.as_string()) client.quit() condition.write({'state': 'email_sent'}) except smtplib.SMTPRecipientsRefused, e: raise osv.except_orm('Recipient refused', str(e))
def _build_cps_for_tracking(tracking, parent_cps_counter=None, line_counter=1): cps_segment = { "line": cps_counter, "pacs": { "pac": [] }, "lines": { "line": [] } } if parent_cps_counter: cps_segment["subline"] = parent_cps_counter # only one tracking per cps segment tracking_segment = {} tracking_segment["iso"] = tracking.ul_id.type # pallet | box tracking_segment["sscc"] = tracking.name tracking_segment["qua"] = 1 tracking_segment["brutweight"] = tracking.weight cps_segment["pacs"]["pac"].append(tracking_segment) for quant in tracking.quant_ids: line_segment = {} product = product_db.browse(cr, uid, quant.product_id.id, context) sorted_history_ids = sorted(quant.history_ids, key=lambda move: move.date, reverse=True) order_origin = sorted_history_ids[0].picking_id[0].origin so_ids = order_db.search(cr, uid, [('name', '=', order_origin)]) #was origin, nog available on quant if not so_ids: raise osv.except_orm(_('Error!'), _("No sales order found for origin \"%s\" via quant (%d)" % (order_origin, quant.id))) order = order_db.browse(cr, uid, so_ids, context) dtm = datetime.datetime.strptime(order.date_order, "%Y-%m-%d %H:%M:%S") if product.bom_ids and order.order_bomified: _logger.info("bomified order with bom product, appending bom components to EDI doc") for bom in product.bom_ids[0].bom_line_ids: bomproduct = product_db.browse(cr, uid, bom.product_id.id, context) line_segment = {} line_segment["num"] = line_counter line_segment["gtin"] = bomproduct.ean13 line_segment["delqua"] = int(quant.qty)*int(bom.product_qty) line_segment["ucgln"] = order.partner_id.ref line_segment["ucorder"] = order.origin line_segment["ucorderdate"] = dtm.strftime("%Y%m%d") cps_segment["lines"]["line"].append(line_segment) line_counter += 1 else: _logger.info("no bom product or no bomified order, appending product to EDI doc") line_segment["num"] = line_counter line_segment["gtin"] = product.ean13 line_segment["delqua"] = int(quant.qty) line_segment["ucgln"] = order.partner_id.ref line_segment["ucorder"] = order.origin line_segment["ucorderdate"] = dtm.strftime("%Y%m%d") cps_segment["lines"]["line"].append(line_segment) line_counter += 1 if not cps_segment["lines"]["line"]: cps_segment.pop("lines") return cps_segment, line_counter
def create(self, cr, uid, vals, context=None): external_benefit_code_val = False if 'benefit_edc_map_ids' in vals.keys(): if len(vals['benefit_edc_map_ids']) > 1: raise osv.except_orm(('Warning!'),("Cannot add EDC Map more than 1 record")) elif vals['benefit_edc_map_ids'] and len(vals['benefit_edc_map_ids']) == 1: if vals['benefit_edc_map_ids'][0][2]: benefit_map_id = vals['benefit_edc_map_ids'][0][2].values()[0] benefit_map_obj = self.pool.get('netpro.benefit_map').browse(cr, uid, benefit_map_id, context=None) external_benefit_code_val = benefit_map_obj.code cur_user = self.pool.get('res.users').browse(cr, uid, uid, context=None) tpa_val = False if cur_user.tpa_id: tpa_val = cur_user.tpa_id.id pass vals.update({ 'created_by_id':uid, 'external_benefit_code': external_benefit_code_val, 'tpa_id':tpa_val, }) new_record = super(benefit, self).create(cr, uid, vals, context=context) return new_record
def action_cancel(self): for inv in self: if self.afip_cae: raise osv.except_orm( _('Error!'), _('You can not cancel an electronic invoice (has CAE assigned).\ You should do a credit note instead.')) return super(invoice, self).action_cancel()
def action_cancel(self): for inv in self: if self.afip_cae: raise osv.except_orm( _('Error!'), _('You can not cancel an electronic invoice (has CAE assigned).\ You should do a credit note instead.')) return super(invoice, self).action_cancel()
def import_data(self, cr, uid, ids, context=None): sale_order_objs = self.browse(cr, uid, ids) if len(sale_order_objs) > 0: sale_order_obj = sale_order_objs[0] else: raise osv.except_orm(u'销售订单不存在', u'销售订单不存在') if sale_order_obj.data : excel = xlrd.open_workbook(file_contents=base64.decodestring(sale_order_obj.data)) #全部采用excel 第一个 sheet sheet = excel.sheet_by_index(0) for row in range(4,sheet.nrows-5): line_args = { 'order_id':ids[0] } #编码 必填 sh_default_code = sheet.cell(row, 1).value if sh_default_code: default_code = None if type(sh_default_code) == type(1) or type(sh_default_code) == type(1.0): #是数字 default_code = '%d'%int(sh_default_code) else: #字符串 default_code = sh_default_code #获取产品 根据 defaut_code product_product_ids = self.pool.get("product.product").search(cr, uid, [('default_code','=',default_code)]) if len(product_product_ids) > 0: product_product_id = product_product_ids[0] product = self.pool.get('product.product').browse(cr, uid, product_product_id) line_args['product_id'] = product.id line_args['product_uom'] = product.uom_id.id line_args['name'] = product.name else: raise osv.except_orm(u'产品不存在(检查编码)',u'错误发生在EXCEl表的第%d行' %(row+1)) else: raise osv.except_orm(u'编码不能为空!',u'错误发生在EXCEl表的第%d行' %(row+1)) #数量 必填 if sheet.cell(row, 5).value: line_args['product_uom_qty'] = sheet.cell(row, 5).value else: raise osv.except_orm(u'数量不能为空!',u'错误发生在EXCEl表的第%d行' %(row+1)) #单价 必填 if sheet.cell(row, 6).value: line_args['price_unit'] = sheet.cell(row, 6).value else: raise osv.except_orm(u'单价不能为空!',u'错误发生在EXCEl表的第%d行' %(row+1)) #创建 line self.pool.get('sale.order.line').create(cr, uid, line_args) else: raise osv.except_orm(u'没有导入的Excel文件',u'Excle不存在!')
def write(self, cr, uid, ids, vals, context=None): external_benefit_code_val = False if 'benefit_edc_map_ids' in vals.keys(): if len(vals['benefit_edc_map_ids']) > 1: raise osv.except_orm(('Warning!'),("Cannot add EDC Map more than 1 record")) elif vals['benefit_edc_map_ids'] and len(vals['benefit_edc_map_ids']) == 1: if vals['benefit_edc_map_ids'][0][2]: benefit_map_id = vals['benefit_edc_map_ids'][0][2].values()[0] benefit_map_obj = self.pool.get('netpro.benefit_map').browse(cr, uid, benefit_map_id, context=None) external_benefit_code_val = benefit_map_obj.code vals.update({ 'external_benefit_code': external_benefit_code_val }) return super(benefit, self).write(cr, uid, ids, vals, context=context)
class export_by_sql(osv.osv): _name = "export_by_sql" _columns = { 'name': fields.char(u'查询名称', size=64, help=u'查询名称将作为邮件的主题,请谨慎填写,简洁易懂'), 'state': fields.selection([('draft', u'查询草稿'), ('executed', u'查询已执行'), ('email_sent', u'邮件已发送')], u'执行状态'), 'sql_string': fields.text(u'SQL查询语句', \ states = {'executed': [('readonly', True)], 'email_sent': [('readonly', True)]}), 'saved_file': fields.binary(u'结果文件', filters='*.xls', help=u'查询结果文件'), 'email_to': fields.text(u'接收邮箱', help=u'查询结果将excel文件作为附件发送给此列表中的邮箱,多个邮箱用英文逗号“,”分隔'), 'file_save_path': fields.char(u'文件保存路径', help=u'给出文件保存在服务器中的地址及文件名(中文字符会导致邮件发送时出错)', \ states = {'executed': [('readonly', True)], 'email_sent': [('readonly', True)]}), } _defaults = { 'state': 'draft', } def execute_sql_2_export(self, cr, uid, ids, context=None): condition = self.browse(cr, uid, ids)[0] sql_string = condition.sql_string file_save_path = condition.file_save_path if file_save_path[-4:] != '.xls': raise osv.except_orm('提示!', '文件保存地址不合法,请以“.xls”结尾') connection = psycopg2.connect(database=DATABASE_NAME, user=DATABASE_USER, password=DATABASE_PWD, host=DATABASE_HOST, port=DATABASE_PORT) try: df = pandas.read_sql(sql_string, connection) except Exception, e: raise osv.except_orm('查询失败,请检查SQL语句', '') try: with ExcelWriter(file_save_path) as writer: df.to_excel(writer, sheet_name=u'Sheet1') condition.write({'state': 'executed'}) except Exception, e: raise osv.except_orm('保存文件出错,请检查地址是否合法', str(e))
def purchase_finances(self, cr, uid, ids, context=None): valida = 0 for rec in self.browse(cr,uid,ids,context): val = { 'tracing_id': [(0, 0, { 'purchase_order_id': rec.id, 'user_id': rec.env.user.id, 'date_tracing': time.strftime('%Y-%m-%d %H:%M:%S'), 'state': 'control' })] } rec.write(val) for quote in rec.quotes_ids: if not quote: raise except_orm('Error!', 'Debe definir al menos una cotizacion') if quote.state == 'done': valida = 1 if valida == 0: raise osv.except_orm('Alerta!', 'Debe aprobar al menos una cotizacion') return self.write(cr, uid, ids, {'state_manager': 'presupuesto'})
def create(self, cr, uid, vals, context=None): if vals['parent_id']: this = self.browse(cr, uid, vals['parent_id'], context=None) policy_obj = this.policy_id vals.update({ 'policy_id' : policy_obj.id, 'insurance_period_start' : policy_obj.insurance_period_start, 'insurance_period_end' : policy_obj.insurance_period_end, }) if policy_obj.policy_category_id.name == 'Individual': #import pdb;pdb.set_trace() if policy_obj.individual_member_limit > 0: if len(this.family_ids) == policy_obj.individual_member_limit-1: raise osv.except_orm(('Warning!'),("Member limit excessed. Cannot add more than "+ str(policy_obj.individual_member_limit) +" member(s) to this Policy.")) if not vals['member_no']: vals.update({ 'member_no' : self.pool.get('ir.sequence').get(cr, uid, 'member_seq') or '/', }) return super(netpro_member, self).create(cr, uid, vals, context=context)
def write(self, cr, uid, ids, vals, context=None): external_benefit_code_val = False if 'benefit_edc_map_ids' in vals.keys(): if len(vals['benefit_edc_map_ids']) > 1: raise osv.except_orm(('Warning!'), ("Cannot add EDC Map more than 1 record")) elif vals['benefit_edc_map_ids'] and len( vals['benefit_edc_map_ids']) == 1: if vals['benefit_edc_map_ids'][0][2]: benefit_map_id = vals['benefit_edc_map_ids'][0][2].values( )[0] benefit_map_obj = self.pool.get( 'netpro.benefit_map').browse(cr, uid, benefit_map_id, context=None) external_benefit_code_val = benefit_map_obj.code vals.update({'external_benefit_code': external_benefit_code_val}) return super(benefit, self).write(cr, uid, ids, vals, context=context)
def create(self, cr, uid, vals, context=None): external_benefit_code_val = False if 'benefit_edc_map_ids' in vals.keys(): if len(vals['benefit_edc_map_ids']) > 1: raise osv.except_orm(('Warning!'), ("Cannot add EDC Map more than 1 record")) elif vals['benefit_edc_map_ids'] and len( vals['benefit_edc_map_ids']) == 1: if vals['benefit_edc_map_ids'][0][2]: benefit_map_id = vals['benefit_edc_map_ids'][0][2].values( )[0] benefit_map_obj = self.pool.get( 'netpro.benefit_map').browse(cr, uid, benefit_map_id, context=None) external_benefit_code_val = benefit_map_obj.code cur_user = self.pool.get('res.users').browse(cr, uid, uid, context=None) tpa_val = False if cur_user.tpa_id: tpa_val = cur_user.tpa_id.id pass vals.update({ 'created_by_id': uid, 'external_benefit_code': external_benefit_code_val, 'tpa_id': tpa_val, }) new_record = super(benefit, self).create(cr, uid, vals, context=context) return new_record
def _prepare_inv_line(self, cr, uid, account_id, order_line, context=None): """Collects require data from purchase order line that is used to create invoice line for that purchase order line :param account_id: Expense account of the product of PO line if any. :param browse_record order_line: Purchase order line browse record :return: Value for fields of invoice lines. :rtype: dict """ taxes = [] fiscal = False for tax in order_line.taxes_id: tax_to_add = tax.id if tax.description in ('1', '2'): fp = self.pool.get('account.fiscal.position.tax') if order_line.partner_id.property_account_position: fiscal = fp.search(cr, uid, [('position_id', '=', order_line.partner_id.property_account_position.id), ('tax_src_id.description', '=', tax.description)]) if not fiscal and order_line.partner_id.property_account_position: raise osv.except_orm('Error!', 'Configure la posicion fiscal del proveedor') if fiscal: fiscal = fp.browse(cr, uid, fiscal[0]) tax_to_add = fiscal.tax_dest_id.id else: continue taxes.append(tax_to_add) return { 'name': order_line.name, 'account_id': account_id, 'price_unit': order_line.price_unit or 0.0, 'quantity': order_line.product_qty, 'product_id': order_line.product_id.id or False, 'uos_id': order_line.product_uom.id or False, 'invoice_line_tax_id': [(6, 0, taxes)], 'account_analytic_id': order_line.account_analytic_id.id or False, 'purchase_line_id': order_line.id, }
def _disaggregated_lines(self, invoice): lines = list() if not invoice.invoice_line: raise osv.except_orm( 'Error!', 'La factura %s no tiene lineas' % invoice.name) for line in invoice.invoice_line: if line.product_id.is_lumpsum: lines.append({ 'name': line.name, 'quantity': line.quantity, 'uos_id': line.uos_id.name, 'price_unit': line.price_unit, 'invoice_line_tax_id': line.invoice_line_tax_id, 'price_subtotal': line.price_subtotal, 'prod': '' }) for lump in line.product_id.components: lines.append({ 'name': self.get_description(lump, invoice)[0], 'quantity': lump.qty, 'uos_id': lump.uom_id.name, 'price_unit': '', 'invoice_line_tax_id': '', 'price_subtotal': '', 'prod': self.get_description(lump, invoice)[2] }) continue lines.append({ 'name': line.name, 'quantity': line.quantity, 'uos_id': line.uos_id.name, 'price_unit': line.price_unit, 'invoice_line_tax_id': line.invoice_line_tax_id, 'price_subtotal': line.price_subtotal, 'prod': line.custom_identificator }) return lines
def action_area_manager(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context): if rec.app_user_id.id != uid: raise osv.except_orm('Error!', 'Usted no esta autorizado a aprobar este documento') return self.write(cr, uid, ids, {'state_manager': 'except'})
def generate_file(self, cr, uid, ids, context): _logger = logging.getLogger(__name__) instance = self.browse(cr, uid, ids, context=None)[0] message = '' inv_obj = self.pool.get('account.invoice') invoice_ids = inv_obj.search(cr, uid, [('gls_bot_passed', '=', False), ('carrier_id', '!=', False), ('carrier_id.gls_instance', '!=', None)], context=None) _logger.warning("----TOTAL NUMBER OF GLS INVOICES: %s" % len(invoice_ids)) invoices = inv_obj.browse(cr, uid, invoice_ids, context=None) ddt_obj = self.pool.get('stock.picking.package.preparation') ddt_ids = ddt_obj.search(cr, uid, [('gls_bot_passed', '=', False), ('carrier_id', '!=', False), ('carrier_id.gls_instance', '!=', None)], context=None) _logger.info("----TOTAL NUMBER OF GLS DDTS: %s" % len(ddt_ids)) ddts = ddt_obj.browse(cr, uid, ddt_ids, context=None) values = [] cnt = 0 for invoice in invoices: if invoice.carrier_id.gls_instance.id != instance.id: continue cnt += 1 if not invoice.total_weight: raise osv.except_orm( "GLS Labeling", "You must specify total weight in invoice: %s (id: %s)" % (invoice.number, invoice.id)) if not invoice.carriage_condition_id: raise osv.except_orm( "GLS Labeling", "You must specify carriage condition (Franco/Contrassegno) in invoice: %s (id: %s)" % (invoice.number, invoice.id)) pts = '' if invoice.carriage_condition_id.name == "PORTO FRANCO": tipo_porto = "F" elif invoice.carriage_condition_id.name == "PORTO ASSEGNATO": tipo_porto = "A" else: tipo_porto = "F" shipping_partner = invoice.address_shipping_id vname = shipping_partner.parent_id.name if shipping_partner.parent_id else shipping_partner.name vstreet = shipping_partner.street vloc = shipping_partner.city importo_contrassegno = invoice.amount_total importo_contrassegno = str(importo_contrassegno) importo_contrassegno = importo_contrassegno.replace('.', ',') vweight = invoice.total_weight vweight = str(vweight) vweight = vweight.replace('.', ',') vnote = invoice.transportation_note or '' valx = { 'ragionesociale': vname, 'indirizzo': vstreet, 'localita': vloc, 'zipcode': invoice.address_shipping_id.zip, 'provincia': invoice.address_shipping_id.state_id.code or '', 'colli': invoice.parcels or 1, 'peso_reale': vweight, 'importo_contrassegno': importo_contrassegno, 'tipo_porto': tipo_porto, 'tipo_collo': '', #tipo_collo, 'document_name': invoice.number, 'cellulare': invoice.address_shipping_id.mobile, 'email': shipping_partner.email, 'note': vnote, 'invoice_id': invoice.id, 'instance_id': invoice.carrier_id.gls_instance.id } res = self.pool.get('gls.new.parcel').create(cr, uid, valx, context=None) _logger.info("_____res %s" % res) if res: values.append(valx) invoice.gls_bot_passed = True message += 'Creating parcel for %s: Success ' % valx[ 'document_name'] cnt = 0 for ddt in ddts: if ddt.carrier_id.gls_instance.id != instance.id: continue cnt += 1 if not ddt.total_weight: raise osv.except_orm( "GLS Labeling", "You must specify total weight in DDT: %s (id: %s)" % (ddt.name, ddt.id)) if not ddt.carriage_condition_id: raise osv.except_orm( "GLS Labeling", "You must specify carriage condition (Franco/Contrassegno) in DDT: %s (id: %s)" % (ddt.name, ddt.id)) pts = '' if ddt.carriage_condition_id.name == "PORTO FRANCO": tipo_porto = "F" elif ddt.carriage_condition_id.name == "PORTO ASSEGNATO": tipo_porto = "A" else: tipo_porto = "F" shipping_partner = ddt.partner_shipping_id vname = shipping_partner.parent_id.name if shipping_partner.parent_id else shipping_partner.name vstreet = shipping_partner.street vloc = shipping_partner.city importo_contrassegno = 0 vweight = ddt.total_weight vweight = str(vweight) vweight = vweight.replace('.', ',') vnote = ddt.note or '' valx = { 'ragionesociale': vname, 'indirizzo': vstreet, 'localita': vloc, 'zipcode': ddt.partner_shipping_id.zip, 'provincia': ddt.partner_shipping_id.state_id.code or '', 'colli': ddt.parcels or 1, 'peso_reale': vweight, 'importo_contrassegno': importo_contrassegno, 'tipo_porto': tipo_porto, 'tipo_collo': '', #tipo_collo, 'document_name': ddt.name, 'cellulare': ddt.partner_shipping_id.mobile, 'email': shipping_partner.email, 'note': vnote, 'ddt_id': ddt.id, 'instance_id': ddt.carrier_id.gls_instance.id } res = self.pool.get('gls.new.parcel').create(cr, uid, valx, context=None) _logger.info("_____res %s" % res) if res: values.append(valx) invoice.gls_bot_passed = True message += 'Creating parcel for %s: Success ' % valx[ document_name] _logger.info(values) try: text = '' with open(record.local_file_path, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL) for val in values: importo = val['importo_contrassegno'] if val[ 'tipo_porto'] == 'A' else '' writer.writerow([val['ragionesociale']] + [val['indirizzo']] + [val['localita']] + [val['zipcode']] + [val['provincia']] + [val['document_name']] + [' '] + [val['colli']] + [' '] + [val['peso_reale']] + [importo] + [val['note']]) message += "Writing to file: Success " except IOError: _logger.info("FAILED WRITING TO FILE") message += "Writing to file: FAILED " try: #isto i za transfer #Transfer the file host = record.host user = record.user password = record.password port = record.port or 21 path = record.path ftp = ftplib.FTP(host) ftp.set_pasv(False) ftp.login(user=user, passwd=password) filename = record.local_file_path fn = 'file.csv' if path: ftp.cwd(path) response = ftp.storbinary('STOR ' + fn, open(filename, 'rb')) _logger.info(response) message += "Tranfer to ftp: %s" % response ftp.quit() except: message += "Transfering: FAILED" record.last_gen = datetime.now() log_vals = { 'name': "Adding parcels", 'message': message, 'datetime': datetime.now(), 'instance_id': record.id } self.pool.get('gls.new.log').create(cr, uid, log_vals, context=None)
def validar_caja(self, cr, uid, ids, context=None): band = 0 lis_rec = [] invoice_id = False obj_caja = self.browse(cr, uid, ids)[0] self.write(cr, uid, ids, { 'state': 'confirm', 'date_cierre': time.strftime('%Y-%m-%d %H:%M:%S') }) inv_obj = self.pool.get('account.invoice') acc_jour_obj = self.pool.get('account.journal') inv_line_obj = self.pool.get('account.invoice.line') cchica_lin_obj = self.pool.get('account.caja.chica.line') cchica_line_ids = cchica_lin_obj.search( cr, uid, [('caja_chica_id', '=', obj_caja.id)], order='id, number_fact') stat_conc_line_obj = cchica_lin_obj.browse(cr, uid, cchica_line_ids, context=context) # JJM 2018-02-15 utilizo el superuser_id por que se necesita validar cajas chicas de otras companias # evito regla de registro para account_journal sobre company_id journal_id = acc_jour_obj.search( cr, SUPERUSER_ID, [('code', '=', 'DCC'), ('company_id', '=', obj_caja.company_id.id)]) if not journal_id: raise osv.except_osv( _('Advertencia!'), _('Primero debe crear un diario de caja chica para esta compania con codigo DCC!' )) journal_obj = acc_jour_obj.browse(cr, uid, journal_id, context=context) for ji in journal_obj: id_journal = ji.id num_comp = '' for det_cc in stat_conc_line_obj: #CONDICION SI ES COMPROBANTE TIPO FACTURA #print "LINEAS ID", det_cc.id #print "LINEAS", det_cc.product_id.name # JJM 2017-01-28 comento siguiente linea, ahora tomo cuenta desde la compañia #account_id = self.pool.get('multi.account.partner.rel').search(cr, uid, [('partner_id', '=', det_cc.partner_id.id), # ('type', '=', 'payable'), # ('company_id', '=', det_cc.company_id.id)]) if not det_cc.partner_id: raise osv.except_orm( 'Advertencia!', 'Debe ingresar un proveedor para la linea de %s' % (det_cc.name)) if len(det_cc.company_id.payable_ids) == 0: raise osv.except_orm( 'Advertencia!', 'La compania %s no tiene configurada la cuenta a pagar Proveedores' % det_cc.company_id.name) # JJM ahora tomo la cuenta desde la compañia en lugar del multi.account account_id = det_cc.company_id.payable_ids[0].id #account_id = self.pool.get('multi.account.partner.rel').browse(cr, uid, account_id[0]).property_account.id if not det_cc.sudo( det_cc.user_id).product_id.property_account_expense: raise osv.except_orm( 'Advertencia!', 'No tiene configurada la cuenta de gastos para el producto %s' % (det_cc.product_id.name)) if det_cc.cantidad <= 0: raise osv.except_orm( 'Advertencia!', 'la cantidad del producto %s no puede ser cero' % (det_cc.product_id.name)) if det_cc.tipo_comp == 'factura': #CREO REGISTRO NUEVO SOLO SI ES COMPROBANTE DIFERENTE if det_cc.tipo_comp == 'factura' and det_cc.number_fact != num_comp: num_comp = det_cc.number_fact #Creo cabecera Factura vals_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'journal_id': id_journal, 'number_seq': det_cc.number_fact, 'account_id': account_id, 'partner_id': det_cc.partner_id.id, 'company_id': det_cc.company_id.id, 'reference': det_cc.name, 'type': 'in_invoice', 'document_type': 1, 'is_cchica': True, 'is_asum': True, 'is_inv_elect': False, 'date_invoice': time.strftime('%Y-%m-%d %H:%M:%S'), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'state': 'draft' } print "DICCIO FACT", vals_invoice invoice_id = inv_obj.create(cr, uid, vals_invoice, context=context) #Creo detalle Factura if invoice_id: vals_det_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'invoice_id': invoice_id, 'company_id': det_cc.company_id.id, 'partner_id': det_cc.partner_id.id, 'product_id': det_cc.product_id.id, 'quantity': det_cc.cantidad, 'account_id': det_cc.sudo(det_cc.user_id).product_id. property_account_expense.id, 'price_unit': round(det_cc.amount_neto / det_cc.cantidad, 2), 'price_subtotal': round(det_cc.amount_neto / det_cc.cantidad, 2), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), } invoice_line_id = inv_line_obj.create( cr, uid, vals_det_invoice) # CREO UNA LINEA MAS NADA MAS PORQUE ES DE LA MISMA FACTURA elif det_cc.tipo_comp == 'factura' and det_cc.number_fact == num_comp: num_comp = det_cc.number_fact #Creo detalle Factura if invoice_id: vals_det_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'invoice_id': invoice_id, 'company_id': det_cc.company_id.id, 'partner_id': det_cc.partner_id.id, 'product_id': det_cc.product_id.id, 'quantity': det_cc.cantidad, 'account_id': det_cc.sudo(det_cc.user_id).product_id. property_account_expense.id, 'price_unit': round(det_cc.amount_neto / det_cc.cantidad, 2), 'price_subtotal': round(det_cc.amount_neto / det_cc.cantidad, 2), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), } invoice_line_id = inv_line_obj.create( cr, uid, vals_det_invoice) #CONDICION SI ES COMPROBANTE TIPO NOTA VENTA elif det_cc.tipo_comp == 'nventa': #CREO REGISTRO NUEVO SOLO SI ES COMPROBANTE DIFERENTE if det_cc.tipo_comp == 'nventa' and det_cc.number_fact != num_comp: num_comp = det_cc.number_fact #Creo cabecera COMPROBANTE TIPO NOTA VENTA vals_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'journal_id': id_journal, 'number_seq': det_cc.number_fact, 'account_id': account_id, 'partner_id': det_cc.partner_id.id, 'company_id': det_cc.company_id.id, 'reference': det_cc.name, 'type': 'in_invoice', 'document_type': 2, 'is_cchica': True, 'is_asum': True, 'is_inv_elect': False, 'date_invoice': time.strftime('%Y-%m-%d %H:%M:%S'), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'state': 'draft' } invoice_id = inv_obj.create(cr, uid, vals_invoice, context=context) #Creo detalle COMPROBANTE TIPO NOTA VENTA if invoice_id: vals_det_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'invoice_id': invoice_id, 'company_id': det_cc.company_id.id, 'partner_id': det_cc.partner_id.id, 'product_id': det_cc.product_id.id, 'quantity': det_cc.cantidad, 'account_id': det_cc.sudo(det_cc.user_id).product_id. property_account_expense.id, 'price_unit': round(det_cc.amount_neto / det_cc.cantidad, 2), 'price_subtotal': round(det_cc.amount_neto / det_cc.cantidad, 2), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), } invoice_line_id = inv_line_obj.create( cr, uid, vals_det_invoice) # CREO UNA LINEA MAS NADA MAS PORQUE ES DE LA MISMO COMPROBANTE TIPO NOTA VENTA elif det_cc.tipo_comp == 'nventa' and det_cc.number_fact == num_comp: num_comp = det_cc.number_fact #Creo detalle COMPROBANTE TIPO NOTA VENTA if invoice_id: vals_det_invoice = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'invoice_id': invoice_id, 'company_id': det_cc.company_id.id, 'partner_id': det_cc.partner_id.id, 'product_id': det_cc.product_id.id, 'quantity': det_cc.cantidad, 'account_id': det_cc.sudo(det_cc.user_id).product_id. property_account_expense.id, 'price_unit': round(det_cc.amount_neto / det_cc.cantidad, 2), 'price_subtotal': round(det_cc.amount_neto / det_cc.cantidad, 2), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), } invoice_line_id = inv_line_obj.create( cr, uid, vals_det_invoice) else: vals_recibo = { 'name': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'journal_id': id_journal, 'account_id': account_id, 'partner_id': det_cc.partner_id.id, 'company_id': det_cc.company_id.id, 'reference': det_cc.name, 'date_invoice': time.strftime('%Y-%m-%d %H:%M:%S'), 'origin': 'CCHICA' + '-' + time.strftime('%Y-%m-%d %H:%M:%S'), 'product_id': det_cc.product_id.id, 'quantity': det_cc.cantidad, 'account_line_id': det_cc.sudo( det_cc.user_id).product_id.property_account_expense.id, 'price_unit': round(det_cc.amount_neto / det_cc.cantidad, 2), 'price_subtotal': round(det_cc.amount_neto / det_cc.cantidad, 2) } lis_rec.append(vals_recibo) band = 1 if band == 1: band1 = 0 for inv_rec in lis_rec: #Creo cabecera Factura if band1 == 0: vals_invoice = { 'name': inv_rec.get('name'), #'journal_id': det_cc.journal_id.id, 'account_id': inv_rec.get('account_id'), 'partner_id': inv_rec.get('partner_id'), 'company_id': inv_rec.get('company_id'), 'reference': inv_rec.get('reference'), 'type': 'in_invoice', 'document_type': 3, 'is_cchica': True, 'is_asum': True, 'is_inv_elect': False, 'date_invoice': inv_rec.get('date_invoice'), 'origin': inv_rec.get('origin'), 'state': 'draft' } invoice_idr = inv_obj.create(cr, uid, vals_invoice, context=context) band1 = 1 #Creo detalle Factura if invoice_idr: vals_det_invoice = { 'name': inv_rec.get('name'), 'invoice_id': invoice_idr, 'company_id': inv_rec.get('company_id'), 'partner_id': inv_rec.get('partner_id'), 'product_id': inv_rec.get('product_id'), 'quantity': inv_rec.get('quantity'), 'account_id': inv_rec.get('account_line_id'), 'price_unit': inv_rec.get('price_unit'), 'price_subtotal': inv_rec.get('price_subtotal'), 'origin': inv_rec.get('origin'), } invoice_line_id = inv_line_obj.create( cr, uid, vals_det_invoice) return True
subject = condition.name email_to = condition.email_to file_path = condition.file_save_path msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = mail_user msg['To'] = email_to xls_part = MIMEApplication(open(file_path, 'rb').read()) xls_part.add_header('Content-Disposition', 'attachment', filename=file_path.split('/')[-1]) msg.attach(xls_part) try: client = smtplib.SMTP() client.connect(mail_host) client.login(mail_user, mail_pwd) client.sendmail(mail_user, email_to, msg.as_string()) client.quit() condition.write({'state': 'email_sent'}) except smtplib.SMTPRecipientsRefused, e: raise osv.except_orm('Recipient refused', str(e)) except smtplib.SMTPAuthenticationError, e: raise osv.except_orm('Auth error', str(e)) except smtplib.SMTPSenderRefused, e: raise osv.except_orm('Sender refused', str(e)) except smtplib.SMTPException, e: raise osv.except_orm('', str(e))
def gls_print(self, cr, uid, ids, context=None): #_logger = logging.getLogger(__name__) for invoice in self.browse(cr, uid, ids, context=context): curr_invoice = invoice config = curr_invoice.gls_config_id or self.pool.get( 'gls.config').browse(cr, uid, 1, context=context) if config.sedeID is None: raise osv.except_orm("GLS Labeling", "COULD NOT GET CONFIG") colli = curr_invoice.parcels or 1 progressive_counter = config.progressive_counter config.progressive_counter = progressive_counter if not curr_invoice.total_weight: raise osv.except_orm("GLS Labeling", "You must specify total weight") if not curr_invoice.carriage_condition_id: raise osv.except_orm( "GLS Labeling", "You must specify carriage condition (Franco/Contrassegno)") pts = '' if curr_invoice.carriage_condition_id.name == "PORTO FRANCO": tipo_porto = "F" elif curr_invoice.carriage_condition_id.name == "PORTO ASSEGNATO": tipo_porto = "A" else: tipo_porto = "F" invoice_name = curr_invoice.ddt_number if not invoice_name: raise osv.except_orm("GLS Labeling", "This Ddt has no name!") invoice_name = invoice_name.replace("/", "-") client = curr_invoice.partner_id shipping_partner = curr_invoice.partner_shipping_id or client #_logger.info("PARTNER %s " % shipping_partner) if not shipping_partner.street or not shipping_partner.zip or not shipping_partner.city or not shipping_partner.state_id: raise osv.except_osv( _("GLS LABEL PRINT"), _("Missing information on client. Client must have street, city, zip code and state (province). If invoice has shipping address defined, that is considered, if no, main invoice partner is considered " )) vname = shipping_partner.name vname = vname.replace("&", "&") vname = vname.replace("'", "'") vname = vname.replace("\"", """) vstreet = shipping_partner.street vstreet = vstreet.replace("&", "&") vstreet = vstreet.replace("'", "'") vstreet = vstreet.replace("\"", """) vloc = shipping_partner.city vloc = vloc.replace("&", "&") vloc = vloc.replace("'", "'") vloc = vloc.replace("\"", """) vweight = curr_invoice.total_weight if colli > 1: vweight = vweight / colli vweight = str(vweight) vweight = vweight.replace('.', ',') vnote = curr_invoice.transportation_note or '' vnote = vnote.replace("&", "&") vnote = vnote.replace("'", "'") vnote = vnote.replace("\"", """) prcls = 0 for i in range(0, colli): vals = { 'ragionesociale': vname, 'indirizzo': vstreet, 'localita': vloc, 'zipcode': shipping_partner.zip, 'provincia': shipping_partner.state_id.code, 'peso_reale': vweight, 'tipo_porto': tipo_porto, 'cellulare1': shipping_partner.mobile or '', 'email': shipping_partner.email or '', 'importo_contrassegno': '0', 'modalita_incasso': '', 'extra_filename': invoice_name, 'contatore_progressivo': progressive_counter, 'colli': 1, 'note': vnote, 'ddt_id': curr_invoice.id, 'config_id': config.id } counter = self.pool.get('gls.parcel').create(cr, uid, vals, context=context) prcls += 1 if not counter: raise osv.except_orm("GLS Labeling", "Fatal: Error creating parcel in local") #print "CREATED GLS PARCEL LOCAL WITH ID: " + str(counter) #print vals parcel = self.pool.get('gls.parcel').browse(cr, uid, counter, context=context)[0] if not parcel: #print "Parcel not retrieved" return False infostring = "<Info><SedeGls>" + config.sedeID + "</SedeGls><CodiceClienteGls>" + config.glsUser + "</CodiceClienteGls><PasswordClienteGls>" + config.glsPass + "</PasswordClienteGls>" infostring += getInfoString(parcel, config.glsContract, ddt=True) infostring += "</Info>" if infostring is None: #print "No infostring" return False with open('/opt/odoo/gigra_addons/gls_labels/infostring.xml', 'w') as f: f.write(infostring) mydata = [('XMLInfoParcel', infostring)] mydata = urllib.urlencode(mydata) path = 'https://weblabeling.gls-italy.com/IlsWebService.asmx/AddParcel' req = urllib2.Request(path, mydata) req.add_header("Content-type", "application/x-www-form-urlencoded") page = urllib2.urlopen(req).read() if True: with open('/opt/odoo/gigra_addons/gls_labels/parcel.xml', 'w') as f: f.write(page) with open('/opt/odoo/gigra_addons/gls_labels/parcel.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() #print root.tag child = root[0] sped_num = child.find('NumeroSpedizione') if sped_num is None: #print "Sped num not retrieved" return False if sped_num.text == '999999999': mess = child.find('NoteSpedizione') self.pool.get('gls.parcel').unlink(cr, uid, counter, context=None) raise osv.except_osv(_("GLS LABEL PRINT"), _(mess.text)) sigla = child.find('SiglaMittente') tot_colli = child.find('TotaleColli') t_collo = child.find('TipoCollo') dest = child.find('SiglaSedeDestino') date = child.find('DataSpedizione') comp_sped = "%s %s %s %s %s" % (sigla.text, sped_num.text, tot_colli.text, t_collo.text, dest.text) self.pool.get('gls.parcel').write( cr, uid, counter, { 'date': date, 'numero_spedizione': sped_num.text, 'name': comp_sped, 'status': 'Pending closure' }, context=context) #print "SPED NUMBER: " + sped_num.text #print child.tag label = child.find('PdfLabel') decoded = base64.b64decode(label.text) parcel.label_binary = label.text parcel.label_filename = "gls-%s.pdf" % invoice_name
def import_data(self, cr, uid, ids, context=None): sale_order_objs = self.browse(cr, uid, ids) if len(sale_order_objs) > 0: sale_order_obj = sale_order_objs[0] else: raise osv.except_orm(u'销售订单不存在', u'销售订单不存在') if sale_order_obj.data: excel = xlrd.open_workbook( file_contents=base64.decodestring(sale_order_obj.data)) #全部采用excel 第一个 sheet sheet = excel.sheet_by_index(0) for row in range(4, sheet.nrows - 5): line_args = {'order_id': ids[0]} #编码 必填 sh_default_code = sheet.cell(row, 1).value if sh_default_code: default_code = None if type(sh_default_code) == type(1) or type( sh_default_code) == type(1.0): #是数字 default_code = '%d' % int(sh_default_code) else: #字符串 default_code = sh_default_code #获取产品 根据 defaut_code product_product_ids = self.pool.get( "product.product").search( cr, uid, [('default_code', '=', default_code)]) if len(product_product_ids) > 0: product_product_id = product_product_ids[0] product = self.pool.get('product.product').browse( cr, uid, product_product_id) line_args['product_id'] = product.id line_args['product_uom'] = product.uom_id.id line_args['name'] = product.name else: raise osv.except_orm(u'产品不存在(检查编码)', u'错误发生在EXCEl表的第%d行' % (row + 1)) else: raise osv.except_orm(u'编码不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #数量 必填 if sheet.cell(row, 5).value: line_args['product_uom_qty'] = sheet.cell(row, 5).value else: raise osv.except_orm(u'数量不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #单价 必填 if sheet.cell(row, 6).value: line_args['price_unit'] = sheet.cell(row, 6).value else: raise osv.except_orm(u'单价不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #创建 line self.pool.get('sale.order.line').create(cr, uid, line_args) else: raise osv.except_orm(u'没有导入的Excel文件', u'Excle不存在!')
def _build_cps_for_tracking(tracking, parent_cps_counter=None, line_counter=1): cps_segment = { "line": cps_counter, "pacs": { "pac": [] }, "lines": { "line": [] } } if parent_cps_counter: cps_segment["subline"] = parent_cps_counter # only one tracking per cps segment tracking_segment = {} tracking_segment["iso"] = tracking.ul_id.name # pallet | box tracking_segment["children"] = 0 for child in tracking.children_ids: tracking_segment["children"] = 1 tracking_segment["sscc"] = tracking.name tracking_segment["qua"] = 1 tracking_segment["brutweight"] = tracking.weight cps_segment["pacs"]["pac"].append(tracking_segment) #quant is gesorteerd op ID #dit is niet altijd correct, moet op picking volgorde zijn volgens LINE ID van Essers PCLO for quant in tracking.quant_ids: line_segment = {} product = self.env['product.product'].browse( quant.product_id.id) sorted_history_ids = sorted(quant.history_ids, key=lambda move: move.date, reverse=True) order_origin = sorted_history_ids[0].picking_id[0].origin #so_ids = order_db.search(cr, uid, [('name', '=', order_origin)]) #was origin, nog available on quant #so_ids = self.env['sale.order'].search([('name', '=', delivery.origin)], limit=1).id so_ids = so_id if not so_ids: raise osv.except_orm( _('Error!'), _("No sales order found for origin \"%s\" via quant (%d)" % (order_origin, quant.id))) order = self.env['sale.order'].browse(so_id) dtm = datetime.datetime.strptime(order.date_order, "%Y-%m-%d %H:%M:%S") if product.bom_ids and order.order_bomified: _logger.info( "bomified order with bom product, appending bom components to EDI doc" ) for bom in product.bom_ids[0].bom_line_ids: bomproduct = self.env['product.product'].browse( bom.product_id.id) line_segment = {} line_segment["num"] = line_counter line_segment["suart"] = bomproduct.name line_segment["desc"] = bomproduct.description[:35] line_segment["gtin"] = bomproduct.ean13 for customer_id in bomproduct.customer_ids: if customer_id.name.id == order.partner_shipping_id.id or customer_id.name.id == order.partner_shipping_id.parent_id.id: _logger.info( "found customer product reference") line_segment[ "byart"] = customer_id.product_code line_segment["delqua"] = int(quant.qty) * int( bom.product_qty) line_segment["ucgln"] = order.partner_id.ref line_segment["ucorder"] = order.origin line_segment["ucorderdate"] = dtm.strftime("%Y%m%d") cps_segment["lines"]["line"].append(line_segment) line_counter += 1 else: _logger.info( "no bom product or no bomified order, appending product to EDI doc" ) line_segment["num"] = line_counter line_segment["suart"] = product.name line_segment["desc"] = product.description[:35] line_segment["gtin"] = product.ean13 for customer_id in product.customer_ids: if customer_id.name.id == order.partner_shipping_id.id or customer_id.name.id == order.partner_shipping_id.parent_id.id: _logger.info("found customer product reference") line_segment["byart"] = customer_id.product_code line_segment["delqua"] = int(quant.qty) line_segment["ucgln"] = order.partner_id.ref line_segment["ucorder"] = order.origin line_segment["ucorderdate"] = dtm.strftime("%Y%m%d") cps_segment["lines"]["line"].append(line_segment) line_counter += 1 if not cps_segment["lines"]["line"]: cps_segment.pop("lines") return cps_segment, line_counter
def wkf_confirm_order(self, cr, uid, ids, context=None): for po in self.browse(cr, uid, ids, context=context): if po.state_manager == 'except': raise osv.except_orm('Error!', 'La Requisicion numero %s requiere aprobacion de gerencia' % po.name) return super(purchase_order, self).wkf_confirm_order(cr, uid, ids, context)
def process_sheet(self, cr, uid, ids, context=None): print "02s_hr_payroll_account::process_sheet:: ", ids move_pool = self.pool.get('account.move') period_pool = self.pool.get('account.period') precision = self.pool.get('decimal.precision').precision_get( cr, uid, 'Payroll') timenow = time.strftime('%Y-%m-%d') partner_employee_pool = self.pool.get('res.partner') input_obj = self.pool.get('hr.payslip.input') for slip in self.browse(cr, uid, ids, context=context): partner_employee_ids = partner_employee_pool.search( cr, uid, [('employee_id', '=', slip.employee_id.id)]) if not partner_employee_ids: raise osv.except_osv( ('Alerta!'), ('En empleado "%s" no tiene vinculado un partner!') % (slip.employee_id.name)) line_ids = [] line_provition_ids = [] debit_sum = 0.0 credit_sum = 0.0 debit_provition_sum = 0.0 credit_provition_sum = 0.0 is_provition = 0 if not slip.period_id: search_periods = period_pool.search( cr, uid, [('date_start', '<=', slip.date_to), ('date_stop', '>=', slip.date_to), ('company_id', '=', slip.company_id.id)]) if not search_periods: raise osv.except_orm( 'Error!', 'No existe un perido que contenga la fecha del slip %s para la compania %s' % (slip.date_to, slip.company_id.name)) period_id = search_periods[0] else: period_id = slip.period_id.id period = self.pool.get('account.period').browse(cr, uid, period_id) name = _('Payslip of %s') % (slip.employee_id.name) name_provition = ('Provisiones de %s') % (slip.employee_id.name) move = { 'narration': name, 'date': period.date_stop, 'ref': slip.payslip_run_id.name + ' ' + slip.number, 'journal_id': slip.journal_id.id, 'period_id': period_id, } move_provition = { 'narration': name_provition, 'date': period.date_stop, 'ref': slip.payslip_run_id.name + ' ' + slip.number, 'journal_id': slip.journal_id.id, 'period_id': period_id, } for line in slip.details_by_salary_rule_category: debit_account_id = 0 credit_account_id = 0 is_provition = 0 amt = slip.credit_note and -line.total or line.total if float_is_zero(amt, precision_digits=precision): continue print "line.salary_rule_id: ", line.salary_rule_id.name print "line.salary_rule_id.category_id.code: ", line.salary_rule_id.category_id.code if line.salary_rule_id.category_id.code == 'PRO': is_provition = 1 if line.salary_rule_id.category_id.code == 'SUBTOTAL': continue if line.salary_rule_id.rule_account_ids: for cuentas in line.salary_rule_id.rule_account_ids: if cuentas.business_unit_id.id == slip.employee_id.business_unit_id.id: debit_account_id = cuentas.debit_account_id.id credit_account_id = cuentas.credit_account_id.id if cuentas.credit_account_id.type in ( 'view', 'consolidation'): print "AQUI: ", cuentas.credit_account_id.name raise osv.except_osv(( 'Error de configuracion!' ), ('La Cuenta "%s" no se ha configurado correctamente la cuenta de Debito!' ) % (line.salary_rule_id.name)) if line.salary_rule_id.category_id.code in ('IGBS', 'OINGNBS'): if not debit_account_id: raise osv.except_osv(('Error de configuracion!'), ( 'En la Regla "%s" no se ha configurado correctamente la cuenta de Debito!' ) % (line.salary_rule_id.name)) if line.salary_rule_id.category_id.code in ('EGRE'): if not credit_account_id: raise osv.except_osv(('Error de configuracion!'), ( 'En la Regla "%s" no se ha configurado correctamente la cuenta de Credito!' ) % (line.salary_rule_id.name)) # Distribucion if line.code in ('INGHXT', 'INGHNOC', 'INGHSUP', 'INGHRF') or line.category_id.code == 'EGRE': if line.category_id.code != 'EGRE': input_ids = input_obj.search( cr, uid, [('payslip_id', '=', slip.id), ('code', '=', line.code)]) for input in input_obj.browse(cr, uid, input_ids): if debit_account_id: debit_line = ( 0, 0, { 'name': line.name, 'date': period.date_stop, 'partner_id': (partner_employee_ids[0] or False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': input.amount > 0.0 and round(input.amount, 4) or 0.0, 'credit': input.amount < 0.0 and -round(input.amount, 4) or 0.0, # 'analytic_account_id': input.income_id.analytic_id.id or False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and input.amount or 0.0, }) line_ids.append(debit_line) debit_sum += debit_line[2][ 'debit'] - debit_line[2]['credit'] else: if credit_account_id: credit_line = (0, 0, { 'name': line.name, 'date': period.date_stop, 'partner_id': (partner_employee_ids[0] or False), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': line.total < 0.0 and -round(line.total, 4) or 0.0, 'credit': line.total > 0.0 and round(line.total, 4) or 0.0, 'analytic_account_id': False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and line.total or 0.0, }) if is_provition: line_provition_ids.append(credit_line) credit_provition_sum += credit_line[2][ 'credit'] - credit_line[2]['debit'] else: line_ids.append(credit_line) credit_sum += credit_line[2][ 'credit'] - credit_line[2]['debit'] else: # for distribucion in line.contract_id.contract_analytic_ids: # print "Distribucion rate: ", distribucion.rate # if distribucion.rate <= 0: # raise osv.except_osv(('Error de configuracion!'),('Revisar los Centros de Costo del Empleado "%s" !')%(line.employee_id.name_related)) # vd_amt = amt * distribucion.rate / 100.00 # print "amt: ", amt # print "vd_amt: ", vd_amt if debit_account_id: debit_line = ( 0, 0, { 'name': line.name, 'date': period.date_stop, 'partner_id': (partner_employee_ids[0] or False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt > 0.0 and round(amt, 4) or 0.0, 'credit': amt < 0.0 and -round(amt, 4) or 0.0, # 'analytic_account_id': distribucion.account_analytic_id.id or False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0, }) if is_provition: line_provition_ids.append(debit_line) debit_provition_sum += debit_line[2][ 'debit'] - debit_line[2]['credit'] else: line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[ 2]['credit'] if credit_account_id: credit_line = ( 0, 0, { 'name': line.name, 'date': period.date_stop, 'partner_id': (partner_employee_ids[0] or False), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt < 0.0 and -round(amt, 4) or 0.0, 'credit': amt > 0.0 and round(amt, 4) or 0.0, # 'analytic_account_id': distribucion.account_analytic_id.id if not is_provition else False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0, }) if is_provition: line_provition_ids.append(credit_line) credit_provition_sum += credit_line[2][ 'credit'] - credit_line[2]['debit'] else: line_ids.append(credit_line) credit_sum += credit_line[2][ 'credit'] - credit_line[2]['debit'] if float_compare(credit_sum, debit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise osv.except_osv( _('Configuration Error!'), _('The Expense Journal "%s" has not properly configured the Credit Account!' ) % (slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'date': period.date_stop, 'partner_id': partner_employee_ids[0], 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': 0.0, 'credit': round(debit_sum - credit_sum, 4), }) line_ids.append(adjust_credit) # Para provisiones if float_compare(credit_provition_sum, debit_provition_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise osv.except_osv( _('Configuration Error!'), _('The Expense Journal "%s" has not properly configured the Credit Account!' ) % (slip.journal_id.name)) adjust_provition_credit = (0, 0, { 'name': _('Adjustment Entry'), 'date': period.date_stop, 'partner_id': partner_employee_ids[0], 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': 0.0, 'credit': round(debit_provition_sum - credit_provition_sum, 4), }) line_provition_ids.append(adjust_provition_credit) elif float_compare(debit_sum, credit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise osv.except_osv( _('Configuration Error!'), _('The Expense Journal "%s" has not properly configured the Debit Account!' ) % (slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'date': period.date_stop, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': round(credit_sum - debit_sum, 4), 'credit': 0.0, }) line_ids.append(adjust_debit) # Para provisiones elif float_compare(debit_provition_sum, credit_provition_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise osv.except_osv( _('Configuration Error!'), _('The Expense Journal "%s" has not properly configured the Debit Account!' ) % (slip.journal_id.name)) adjust_provition_debit = (0, 0, { 'name': _('Adjustment Entry'), 'date': period.date_stop, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': round(credit_sum - debit_sum, 4), 'credit': 0.0, }) line_provition_ids.append(adjust_provition_debit) line_ids = self.validate_move(line_ids) move.update({'line_id': line_ids}) move_id = move_pool.create(cr, uid, move, context=context) if slip.type == 'rol': line_provition_ids = self.validate_move(line_provition_ids) move_provition.update({'line_id': line_provition_ids}) move_provition_id = move_pool.create(cr, uid, move_provition, context=context) else: move_provition_id = False self.write(cr, uid, [slip.id], { 'move_id': move_id, 'period_id': period_id, 'move_provition_id': move_provition_id }, context=context) # if slip.journal_id.entry_posted: # move_pool.post(cr, uid, [move_id, move_provition_id], context=context) return self.write(cr, uid, ids, { 'paid': True, 'state': 'done' }, context=context)
def check_vat(self): for rec in self: if len(rec.vat) < 2: raise osv.except_orm( _(u"Error !"), _(u"Your vat number length is less than 3")) super(res_partner_vat, self).check_vat()
def compute_rule(self, cr, uid, rule_id, localdict, context=None): obj = self.browse(cr, uid, rule_id) if obj.code == 'EGRIR': # tax_pool = self.pool.get('hr.income.tax') table_tax_obj = self.get_current_tax_table(cr, uid, context=None) if not table_tax_obj: raise osv.except_orm('Error!', 'Configure la tabla de impuestos') # rule = self.browse(cr, uid, rule_id, context=None) # tuple_ingresos = super(hr_salary_rule, self).compute_rule(cr, uid, rule_id, localdict, context=None) employee = localdict['employee'] contract = localdict['contract'] slip_pool = self.pool.get('hr.payslip') base_imp = 0.00 last_wage = contract.wage # base_imp += incomes_amount # ba = self.get_food_vouchers_amount(cr, uid, [contract.id], context.get('active_id'), context=None) # antique = self.get_antique_amount(cr, uid, contract, context.get('active_id'), context=None) # base_imp += (ba + antique) amount_not_average = 0.00 amount_expenses = 0.00 fiscalyear_id = self.get_current_fiscalyear(cr, uid, context=None) payslip_run = self.pool.get('hr.payslip.run').browse(cr, uid, context.get('active_id'), context=None) fiscalyear_obj = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id) days = parser.parse(fiscalyear_obj.date_stop) - parser.parse(payslip_run.date_start) average = parser.parse(payslip_run.date_end).month - parser.parse(fiscalyear_obj.date_start).month + 1 months = int(days.days.real/30) for personal_expense in employee.personal_expense_ids: if personal_expense.fiscalyear_id.id == fiscalyear_id: amount_expenses += personal_expense.total_annual_cost incomes_amount = 0.00 valquid = util = 0.00 for income in self.get_incomes(cr, uid, context.get('active_id'), employee.id): if income.adm_id.code != 'UTIL' and not income.adm_id.not_generate_benefits and income.adm_id.average: # util = income.value if income.adm_id.code == 'VALIQUD': valquid = income.value incomes_amount += income.value if income.adm_id.code != 'UTIL' and not income.adm_id.average: amount_not_average += income.value incomes_amount += contract.wage base_imp = incomes_amount payslip_ids = slip_pool.search(cr, uid, [('employee_id', '=', employee.id), ('payslip_run_id.fiscalyear_id', '=', fiscalyear_id), ('type', '=', 'rol'), ('state', '=', 'done'), ('date_to', '<', payslip_run.date_end)]) tax_acumulated = 0.00 if payslip_ids: for slip in slip_pool.browse(cr, uid, payslip_ids, context=None): for line in slip.line_ids: if line.salary_rule_id.category_id.code == 'IGBS' and line.salary_rule_id.code not in ('BANP','BONCEX'): base_imp += line.total elif line.salary_rule_id.category_id.code == 'IGBS' and line.salary_rule_id.code in ('BANP','BONCEX'): amount_not_average += line.total if line.salary_rule_id.code == 'EGRIR': tax_acumulated += line.total taxutil = self.get_util_tax(cr, uid, fiscalyear_obj, employee.id) tax_acumulated += taxutil util = self.get_utilities(cr, uid, fiscalyear_obj, employee.id, payslip_run.date_start) acumulated = base_imp base_imp /= average base_imp *= (months - 1) base_imp += acumulated + amount_not_average iess = (base_imp - valquid) * 0.0945 base_imp += util base_calc = base_imp - iess - amount_expenses line_fraction = self.pool.get('hr.income.tax').find_base_fraction(cr, uid, table_tax_obj, base_calc, context=None) taxes = 0.00 if line_fraction: excessive = base_calc - line_fraction.basic_fraction taxes = (excessive * line_fraction.tax_surplus_fraction/100) + line_fraction.tax_basic_fraction if taxes > 0: taxes -= tax_acumulated # Si se va a calcular el impuesto del anyo comentar esta linea y las 2 de abajo if taxes < 0: self.pool.get('negative.taxes').create(cr, uid, {'employee_id': employee.id, 'amount': taxes, 'user_id': uid}) taxes = 0.00 taxes /= months return taxes, 1, 100 return super(hr_salary_rule, self).compute_rule(cr, uid, rule_id, localdict, context=None)
def obtener_cadena(self, cr, uid, employee, f_hasta, b_id, data, cont, context): #metodo que obtiene la cadena segun formato del banco que se configure #TODO Hacer la configuracion del banco con el que se va ha pagar y del formato #En este caso hacemos solo para el banco de guayaquil ref = "SUELDO DE" + " " + time.strftime( '%B del %Y', time.strptime(f_hasta, '%Y-%m-%d')).upper() buf = StringIO.StringIO() id_char = 'C' ced = str(employee.identification_id) if employee.emp_tipo_doc == 'p': id_char = 'P' esp = [ 'á', 'à', 'â', 'ã', 'ª', 'Á', 'À', 'Â', 'Ã', 'Í', 'Ì', 'Î', 'í', 'ì', 'î', 'é', 'è', 'ê', 'É', 'È', 'Ê', 'ó', 'ò', 'ô', 'õ', 'º', 'Ó', 'Ò', 'Ô', 'Õ', 'ú', 'ù', 'û', 'Ú', 'Ù', 'Û', 'ç', 'Ç', 'ñ', 'Ñ', 'Ñ' ] nor = [ 'a', 'a', 'a', 'a', 'a', 'A', 'A', 'A', 'A', 'I', 'I', 'I', 'i', 'i', 'i', 'e', 'e', 'e', 'E', 'E', 'E', 'o', 'o', 'o', 'o', 'o', 'O', 'O', 'O', 'O', 'u', 'u', 'u', 'U', 'U', 'U', 'c', 'C', 'n', 'N', 'N' ] forma_pago = "CTA" cur = "USD" numero_banco = '884' band = 0 # banco == Guayaquil if employee.bank_account_id.bank.bic == '17': # Si es banco de guayaquil cadena = '' cadena_formato = self.obtener_formato() print ' cadena_formato ', cadena_formato for dato in cadena_formato: if dato['tipo'] == 'fijo': cadena = cadena + dato['dato'] + dato['separador'] print ' cadena ', cadena else: cadena = cadena + self.get_data(employee, data, dato) + dato['separador'] print ' cadena2 ', cadena return cadena + numero_banco + os.linesep # Cooperative Cotocollao elif employee.bank_account_id.bank.bic == '18': factual = time.strftime('%Y-%m-%d') fact = factual.split('-') print "fecha actual", fact fecha = str(fact[2] + '/' + fact[1] + '/' + fact[0]) tot = str(data['credit']) print ' tot ', tot val = tot.split('.') l = "" for item in val[0]: l += item if len(val[1]) < 2: val[1] += '0' print 'val[1] ', val[1] for item in val[1]: l += item t_cta = str(employee.bank_account_id.state) if t_cta == 'ahorro': t_cta = 'C' elif t_cta == 'corriente': t_cta = 'C' t_cod = str(employee.bank_account_id.bank.bic) tam_cod = len(t_cod) if tam_cod < 3: for i in range(3 - tam_cod): t_cod += ' ' num_cta = str(employee.bank_account_id.acc_number.strip()) tam_cta = len(num_cta) if tam_cta < 13: for i in range(13 - tam_cta): num_cta += ' ' cadena = fecha + ',' + '0' + ',' + '1' + ',' + num_cta.strip( ) + ',' + t_cta + ',' + tot + ',' + t_cod + os.linesep return cadena #banco == Pichincha elif employee.bank_account_id.bank.bic in [ '10', '32' ]: #32 es del banco internacional, 10 del pichincha, el archivo contiene la misma informacion, le hago aqui Ramses #Si el banco es el pichincha code = employee.bank_account_id.bank.bic tam_ced = len(ced) if tam_ced < 10: for i in range(10 - tam_ced): ced += ' ' tot = str(data['credit']) print ' tot ', tot val = tot.split('.') l = "" for item in val[0]: l += item if len(val[1]) < 2: val[1] += '0' print 'val[1] ', val[1] for item in val[1]: l += item t_cta = str(employee.bank_account_id.state) t_cod = str(employee.bank_account_id.bank.bic) tam_cod = len(t_cod) if tam_cod < 3: for i in range(3 - tam_cod): t_cod += ' ' num_cta = str(employee.bank_account_id.acc_number.strip()) tam_cta = len(num_cta) if tam_cta < 13: for i in range(13 - tam_cta): num_cta += ' ' t_em = str(employee.id) nom = str(employee.name_related.encode('"UTF-8"')) for indi in range(40): nom = nom.replace(esp[indi], nor[indi]) nombre = str(nom) print nombre tam_nom = len(nombre) if tam_nom < 45: for i in range(45 - tam_nom): nombre += ' ' num = str(cont) tam_cont = len(num) if tam_cont < 3: for i in range(3 - tam_cont): num += ' ' space = '' if code == '10': cadena = "PA" + ced + space.ljust( 20 - len(ced)) + cur + l.zfill( 13) + forma_pago + t_cta + num_cta + space.ljust( 20 - len(num_cta)) + ref + space.ljust( 40 - len(ref)) + id_char + ced + space.ljust( 14 - len(ced)) + nombre.ljust( 41 + 13 - len(code)) + str(code) + os.linesep else: company_account = employee.company_id.partner_id.bank_ids if not company_account: raise osv.except_orm( 'Error!', 'La Compania no tiene cuenta bancaria asociada') slip = self.pool.get('hr.payslip').browse(cr, uid, data['id']) cadena = "PA" + '\t' + str(cont) + '\t' + cur + '\t' + l.zfill(13) + '\t' + forma_pago + '\t' + t_cta + '\t' + num_cta[:10] + '\t' + '\t' + id_char + '\t' + ced + '\t' + \ nombre[0:40] + chr(13) + chr(10) return cadena # Produbanco Cooperative elif employee.bank_account_id.bank.bic == '36': factual = time.strftime('%d%m%y') fecha = str(factual) print "fecha: ", fecha tot = str(data['credit']) print ' tot ', tot val = tot.split('.') l = "" for item in val[0]: l += item if len(val[1]) < 2: val[1] += '0' print 'val[1] ', val[1] for item in val[1]: l += item t_cta = str(employee.bank_account_id.state) if t_cta == 'Débito': t_cta = 'D' elif t_cta == 'Crédito': t_cta = 'C' t_cod = str(employee.bank_account_id.bank.bic) tam_cod = len(t_cod) if tam_cod < 3: for i in range(3 - tam_cod): t_cod += ' ' num_cta = str(employee.bank_account_id.acc_number.strip()) tam_cta = len(num_cta) if tam_cta < 13: for i in range(13 - tam_cta): num_cta += ' ' nom = str(employee.name_related.encode('"UTF-8"')) for indi in range(40): nom = nom.replace(esp[indi], nor[indi]) twoplaces = Decimal(10)**-2 cadena = "C" + str(nom).ljust(40) + num_cta.strip() + str( Decimal(tot).quantize(twoplaces)).replace( ".", "").zfill(14) + fecha + "N" + os.linesep return cadena
def import_data(self, cr, uid, ids, context=None): purchase_order_obj = None purchase_order_objs = self.browse(cr, uid, ids) if len(purchase_order_objs) > 0: purchase_order_obj = purchase_order_objs[0] else: raise osv.except_orm(u'采购订单不存在', u'采购订单不存在') if purchase_order_obj.data: excel = xlrd.open_workbook( file_contents=base64.decodestring(purchase_order_obj.data)) #全部采用excel 第一个 sheet sheet = excel.sheet_by_index(0) for row in range(1, sheet.nrows): line_args = {'order_id': ids[0]} #编码 必填 (通过产品编码获取到产品) 0 产品名 sh_default_code = sheet.cell(row, 0).value print sh_default_code if sh_default_code: default_code = None if type(sh_default_code) == type(1) or type( sh_default_code) == type(1.0): #是数字 default_code = '%d' % int(sh_default_code) else: #字符串 default_code = sh_default_code default_code = default_code[default_code.index('[') + 1:default_code.index(']')] #获取产品 根据 defaut_code product_product_ids = self.pool.get( "product.product").search( cr, uid, [('default_code', '=', default_code)]) if len(product_product_ids) > 0: product_product_id = product_product_ids[0] product = self.pool.get('product.product').browse( cr, uid, product_product_id) line_args['product_id'] = product.id line_args['product_uom'] = product.uom_id.id line_args['name'] = product.name else: raise osv.except_orm(u'产品不存在(检查编码)', u'错误发生在EXCEl表的第%d行' % (row + 1)) else: raise osv.except_orm(u'编码不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #计划日期 2 2014年12月33日 if sheet.cell(row, 2).value: print sheet.cell(row, 2).value t = datetime.datetime.strptime( sheet.cell(row, 2).value, '%Y年%m月%d日') line_args['date_planned'] = t else: raise osv.except_orm(u'计划日期不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #数量 必填 4 if sheet.cell(row, 4).value == 0 or sheet.cell(row, 4).value: line_args['product_qty'] = sheet.cell(row, 4).value else: raise osv.except_orm(u'数量不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #单价 必填 if sheet.cell(row, 6).value == 0 or sheet.cell(row, 6).value: line_args['price_unit'] = sheet.cell(row, 6).value else: raise osv.except_orm(u'单价不能为空!', u'错误发生在EXCEl表的第%d行' % (row + 1)) #创建 line self.pool.get('purchase.order.line').create(cr, uid, line_args) else: raise osv.except_orm(u'没有导入的Excel文件', u'Excle不存在!')
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None, price_unit=False): context = context or {} tax_id = context.get('default_tax_id') print tax_id a, b, tax_id = tax_id[0] if len(tax_id) > 1: raise osv.except_orm(_('只能定义一种税金!'), _('请先定义税金.')) if not tax_id: raise osv.except_orm(_('没有定于税金!'), _('请先定义税金.')) lang = lang or context.get('lang', False) if not partner_id: raise osv.except_osv( _('No Customer Defined!'), _('Before choosing a product,\n select a customer in the sales form.' )) warning = False product_uom_obj = self.pool.get('product.uom') partner_obj = self.pool.get('res.partner') tax_obj = self.pool.get('account.tax') price_discount_obj = self.pool.get('product.price.discount') product_obj = self.pool.get('product.product') tax_id = tax_obj.browse(cr, uid, tax_id[0]) partner = partner_obj.browse(cr, uid, partner_id) lang = partner.lang context_partner = context.copy() context_partner.update({'lang': lang, 'partner_id': partner_id}) if not product: return { 'value': { 'th_weight': 0, 'product_uos_qty': qty }, 'domain': { 'product_uom': [], 'product_uos': [] } } if not date_order: date_order = time.strftime(DEFAULT_SERVER_DATE_FORMAT) result = {} warning_msgs = '' product_obj = product_obj.browse(cr, uid, product, context=context_partner) uom2 = False if uom: uom2 = product_uom_obj.browse(cr, uid, uom) if product_obj.uom_id.category_id.id != uom2.category_id.id: uom = False if uos: if product_obj.uos_id: uos2 = product_uom_obj.browse(cr, uid, uos) if product_obj.uos_id.category_id.id != uos2.category_id.id: uos = False else: uos = False fpos = False if not fiscal_position: fpos = partner.property_account_position or False else: fpos = self.pool.get('account.fiscal.position').browse( cr, uid, fiscal_position) if uid == SUPERUSER_ID and context.get('company_id'): taxes = product_obj.taxes_id.filtered( lambda r: r.company_id.id == context['company_id']) else: taxes = product_obj.taxes_id # result['tax_id'] = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, taxes, context=context) if not flag: result['name'] = \ self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context_partner)[0][1] if product_obj.description_sale: result['name'] += '\n' + product_obj.description_sale domain = {} if (not uom) and (not uos): result['product_uom'] = product_obj.uom_id.id if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff uos_category_id = product_obj.uos_id.category_id.id else: result['product_uos'] = False result['product_uos_qty'] = qty uos_category_id = False result['th_weight'] = qty * product_obj.weight domain = { 'product_uom': [('category_id', '=', product_obj.uom_id.category_id.id)], 'product_uos': [('category_id', '=', uos_category_id)] } elif uos and not uom: # only happens if uom is False result[ 'product_uom'] = product_obj.uom_id and product_obj.uom_id.id result['product_uom_qty'] = qty_uos / product_obj.uos_coeff result[ 'th_weight'] = result['product_uom_qty'] * product_obj.weight elif uom: # whether uos is set or not default_uom = product_obj.uom_id and product_obj.uom_id.id q = product_uom_obj._compute_qty(cr, uid, uom, qty, default_uom) if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff else: result['product_uos'] = False result['product_uos_qty'] = qty result[ 'th_weight'] = q * product_obj.weight # Round the quantity up if not uom2: uom2 = product_obj.uom_id # get unit price if not pricelist: warn_msg = _( 'You have to select a pricelist or a customer in the sales form !\n' 'Please set one before choosing a product.') warning_msgs += _("No Pricelist ! : ") + warn_msg + "\n\n" else: ctx = dict( context, uom=uom or result.get('product_uom'), date=date_order, ) # allen modify discount_id = price_discount_obj.search( cr, uid, [('partner_id', '=', partner_id), ('product_id', '=', product_obj.id)]) if not discount_id: discount_id = price_discount_obj.create( cr, uid, { 'partner_id': partner_id, 'product_id': product_obj.id }) price = 0.0 discount = price_discount_obj.browse(cr, uid, discount_id).price discount_tax = price_discount_obj.browse(cr, uid, discount_id).price_tax if partner.level == 1: if not tax_id.amount: price = product_obj.price1 * discount else: price = product_obj.price1_tax * discount_tax elif partner.level == 2: if not tax_id.amount: price = product_obj.price2 * discount else: price = product_obj.price2_tax * discount_tax elif partner.level == 3: if not tax_id.amount: price = product_obj.price3 * discount else: price = product_obj.price3_tax * discount_tax else: pass # price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], # product, qty or 1.0, partner_id, ctx)[pricelist] if price is False: price = 0.00 # warn_msg = _("Cannot find a pricelist line matching this product and quantity.\n" # "You have to change either the product, the quantity or the pricelist.") # # warning_msgs += _("No valid pricelist line found ! :") + warn_msg + "\n\n" else: # price = self.pool['account.tax']._fix_tax_included_price(cr, uid, price, taxes, # # context['default_tax_id']) if not result.get('price_unit'): result.update({'price_unit': price}) if context.get('uom_qty_change', False): values = {'price_unit': price} if result.get('product_uos_qty'): values['product_uos_qty'] = result['product_uos_qty'] print values return {'value': values, 'domain': {}, 'warning': False} if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message': warning_msgs } return {'value': result, 'domain': domain, 'warning': warning}