def check_tax_lines(self, cr, uid, inv, compute_taxes, ait_obj): """ Check if no tax lines are created. If existing tax lines, there are checks on the invoice and match the tax base. """ if not inv.tax_line: for tax in compute_taxes.values(): ait_obj.create(cr, uid, tax) else: tax_key = [] for tax in inv.tax_line: if tax.manual: continue # key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id) #### group by tax id #### key = (tax.tax_id.id) tax_key.append(key) if not key in compute_taxes: raise osv.except_osv(_('Warning !'), _('Global taxes defined, but are not in invoice lines !')) base = compute_taxes[key]['base'] if abs(base - tax.base) > inv.company_id.currency_id.rounding: raise osv.except_osv(_('Warning !'), _('Tax base different !\nClick on compute to update tax base')) for key in compute_taxes: if not key in tax_key: raise osv.except_osv(_('Warning !'), _('Taxes missing !'))
def test_serial(self, cr, uid, ids): ok = True spl_obj = self.pool.get('stock.production.lot') for pick in self.browse(cr, uid, ids): for move in pick.move_lines: if move.product_id.track_serial_incoming and not \ move.prodlot_id and pick.type == 'in': raise osv.except_osv(_('Error !'), _( 'This product %s should be serialized') % move.product_id.name) if move.product_id.track_serial_outgoing and not \ move.prodlot_id and pick.type == 'out': raise osv.except_osv(_('Error !'), _( 'This product %s should be serialized') % move.product_id.name) if move.product_id.track_serial_incoming and \ move.product_id.track_serial_outgoing and\ pick.type == 'out': spl_ids = spl_obj.search(cr, uid, [( 'product_id', '=', move.product_id.id), ('name', '=', move.prodlot_id.name)]) if len(spl_ids) < 1: raise osv.except_osv(_('Error !'), _( 'This serial %s is not exist') % move.prodlot_id.name) return ok
def do_button_print(self, cr, uid, ids, context=None): assert(len(ids) == 1) company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id #search if the partner has accounting entries to print. If not, it may not be present in the #psql view the report is based on, so we need to stop the user here. if not self.pool.get('account.move.line').search(cr, uid, [ ('partner_id', '=', ids[0]), ('account_id.type', '=', 'receivable'), ('reconcile_id', '=', False), ('state', '!=', 'draft'), ('company_id', '=', company_id), ], context=context): raise osv.except_osv(_('Error!'),_("The partner does not have any accounting entries to print in the overdue report for the current company.")) self.message_post(cr, uid, [ids[0]], body=_('Printed overdue payments report'), context=context) #build the id of this partner in the psql view. Could be replaced by a search with [('company_id', '=', company_id),('partner_id', '=', ids[0])] wizard_partner_ids = [ids[0] * 10000 + company_id] followup_ids = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context) if not followup_ids: raise osv.except_osv(_('Error!'),_("There is no followup plan defined for the current company.")) data = { 'date': fields.date.today(), 'followup_id': followup_ids[0], } #call the print overdue report on this partner return self.do_partner_print(cr, uid, wizard_partner_ids, data, context=context)
def _check_write_vals(self,cr,uid,vals,ids=None,context=None): if vals.get('default_code') and vals['default_code']: vals['default_code'] = vals['default_code'].strip() if ids: product_id = self.search(cr, uid, [('default_code', '=', vals['default_code']),('id','not in',ids)]) else: product_id = self.search(cr, uid, [('default_code', '=', vals['default_code'])]) if product_id: raise osv.except_osv(_('Error!'), _('Product code must be unique!')) if vals.get('cn_name'): vals['cn_name'] = vals['cn_name'].strip() if ids: product_id = self.search(cr, uid, [('cn_name', '=', vals['cn_name']),('id','not in',ids)]) else: product_id = self.search(cr, uid, [('cn_name', '=', vals['cn_name'])]) if product_id: raise osv.except_osv(_('Error!'), _('Product Chinese Name must be unique!')) if vals.get('name'): vals['name'] = vals['name'].strip() if ids: product_id = self.search(cr, uid, [('name', '=', vals['name']),('id','not in',ids)]) else: product_id = self.search(cr, uid, [('name', '=', vals['name'])]) if product_id: raise osv.except_osv(_('Error!'), _('Product Name must be unique!')) return True
def create_budget_line(self, cr, uid, ids, context=None): for bud in self.browse(cr, uid, ids, context=context): if not bud.budget_file: raise osv.except_osv(_('ERROR !!'),_('Please select the file.')) csvfile = bud.budget_file.decode('base64') print csvfile fileReader = csvfile.split('\n') flag = False for row in fileReader: if not flag: flag = True continue row = row.split(',') if len(row) < 5: continue print '-----------ROW-----------',len(row) analytic_account_id = self.pool.get('account.analytic.account').search(cr, uid, [('name','=',row[0])]) if not analytic_account_id: raise osv.except_osv(_('ERROR !!'),_('There is no Analytic Account with name %s'%(row[0]))) general_budget_id = self.pool.get('account.budget.post').search(cr, uid, [('name','=',row[1]),('analytic_account_id','=',analytic_account_id[0])]) if not general_budget_id: raise osv.except_osv(_('ERROR !!'),_('There is no Analytic Element with name %s or it may not be linked with Analytic Account %s'%(row[1],row[0]))) data = { 'analytic_account_id':analytic_account_id[0], 'general_budget_id':general_budget_id[0], 'planned_amount':-abs(float(row[2])), 'date_from':row[3], 'date_to':row[4], 'department_id':bud.department_id.id, } print "------------CSVDATA-----------",data self.pool.get('crossovered.budget.lines').create(cr, uid, data, context=context) return True
def create(self, cr, uid, vals, context=None): # PARA SECUENCIAS POR UBICACIONES picking_id = super(stock_picking_out, self).create(cr, uid, vals, context=context) picking = self.pool.get('stock.picking.out').browse(cr, uid, picking_id, context=context) sequence_obj = self.pool.get('ir.sequence') #_logger.error("PINCKING: %r", picking) #if ('name' not in vals) or (vals.get('name')=='/'): if vals['type'] == 'out': location_id = vals.get('location_id', []) if location_id: location = self.pool.get('stock.location').browse(cr, uid, location_id, context) if location.sequence_out_id: vals = {'name': sequence_obj.get_id(cr, uid, location.sequence_out_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_('Warning!'), _('Ubicacion de origen no tiene secuencia asignanda.')) else: for move in picking.move_lines: location_id = move.location_id location = self.pool.get('stock.location').browse(cr, uid, location_id.id, context) if location.sequence_out_id: vals = {'name': sequence_obj.get_id(cr, uid, location.sequence_out_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_('Warning!'), _('Ubicacion de origen no tiene secuencia asignanda.')) return picking_id
def calc_period_prec(self, cr, uid, fiscal_year, context={}): fiscalyear_obj = self.pool['account.fiscalyear'] date_start = ( str(datetime.strptime(fiscal_year.date_start, '%Y-%m-%d') - relativedelta(years=1))[:10]) date_stop = ( str(datetime.strptime(fiscal_year.date_stop, '%Y-%m-%d') - relativedelta(years=1))[:10]) id_fy = fiscalyear_obj.search( cr, uid, [('date_start', '=', date_start), ('date_stop', '=', date_stop)]) if not id_fy: raise osv.except_osv( _('Error!'), _('Not find the previous exercise for period %s - %s' % ( date_start, date_stop))) # Anno Successivo date_start = ( str(datetime.strptime(fiscal_year.date_start, '%Y-%m-%d') + relativedelta(years=1))[:10]) date_stop = ( str(datetime.strptime(fiscal_year.date_stop, '%Y-%m-%d') + relativedelta(years=1))[:10]) id_fy1 = fiscalyear_obj.search( cr, uid, [('date_start', '=', date_start), ('date_stop', '=', date_stop)]) if not id_fy1: raise osv.except_osv( _('Error!'), _('Not find the next exercise for period %s - %s' % ( date_start, date_stop))) return id_fy[0], id_fy1[0]
def validasifaktur(self,cr,uid,id,context=None): objini = self.browse(cr,uid,id) # Cek SJ kembar di faktur listsj = [] for semuafaktur in objini.idpo.pembelianfaktur: if semuafaktur.pembeliansj1 in listsj and semuafaktur.pembeliansj1.nomorsj != False: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Sudah Ada Faktur dengan Surat Jalan: "+ str(semuafaktur.pembeliansj1.nomorsj))) else: listsj.append(semuafaktur.pembeliansj1) if semuafaktur.pembeliansj2 in listsj and semuafaktur.pembeliansj2.nomorsj != False: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Sudah Ada Faktur dengan Surat Jalan: "+ str(semuafaktur.pembeliansj2.nomorsj))) else: listsj.append(semuafaktur.pembeliansj2) if semuafaktur.pembeliansj3 in listsj and semuafaktur.pembeliansj3.nomorsj != False: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Sudah Ada Faktur dengan Surat Jalan: "+ str(semuafaktur.pembeliansj3.nomorsj))) else: listsj.append(semuafaktur.pembeliansj3) if semuafaktur.pembeliansj4 in listsj and semuafaktur.pembeliansj4.nomorsj != False: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Sudah Ada Faktur dengan Surat Jalan: "+ str(semuafaktur.pembeliansj4.nomorsj))) else: listsj.append(semuafaktur.pembeliansj4) if semuafaktur.pembeliansj5 in listsj and semuafaktur.pembeliansj5.nomorsj != False: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Sudah Ada Faktur dengan Surat Jalan: "+ str(semuafaktur.pembeliansj5.nomorsj))) else: listsj.append(semuafaktur.pembeliansj5) return True
def create(self, cr, uid, vals, context=None): # PARA SECUENCIAS POR UBICACIONES picking_id = super(stock_picking_in, self).create(cr, uid, vals, context=context) # _logger.error("PINCKING id1: %r", picking_id) picking = self.pool.get("stock.picking.in").browse(cr, uid, picking_id, context=context) sequence_obj = self.pool.get("ir.sequence") # if ('name' not in vals) or (vals.get('name')=='/'): if vals["type"] == "in": location_id = vals.get("location_dest_id", []) if location_id: location = self.pool.get("stock.location").browse(cr, uid, location_id, context) if location.sequence_in_id: vals = {"name": sequence_obj.get_id(cr, uid, location.sequence_in_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_("Warning!"), _("Ubicacion de destino no tiene secuencia asignanda.")) else: for move in picking.move_lines: location_id = move.location_dest_id location = self.pool.get("stock.location").browse(cr, uid, location_id.id, context) if location.sequence_in_id: vals = {"name": sequence_obj.get_id(cr, uid, location.sequence_in_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_("Warning!"), _("Ubicacion de destino no tiene secuencia asignanda.")) return picking_id
def unlink(self, cr, uid, id, context): pembelianfaktur = self.browse(cr,uid,id) if pembelianfaktur.disetujui != False and 'ijindelete' not in context: raise osv.except_osv(_('Tidak Dapat Menghapus'),_("Faktur Telah Disetujui!")) if pembelianfaktur.idpo.disetujui == False and 'ijindelete' not in context: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("PO Belum Disetujui")) return super(mmr_pembelianfaktur, self).unlink(cr, uid, id, context)
def validasisj(self,cr,uid,id,context=None): hasil={} listproduk = {} objini = self.browse(cr,uid,id) # SJDETIL--------------------------------- # 1. Pastikan jumlah yang ada di SJ tidak melebihi pesanan, dan barang tersebut ada di SJ! # Browse diri sendiri, buat list ['nopodetil' : 'jumlahpesanan'], Iterasi seluruh sj, tiap Detil dengan produk sama mengurangi jumlah ke list. for semuaprodukpo in objini.idpo.pembelianpodetil: listproduk[semuaprodukpo] = semuaprodukpo.jumlah for semuasj in objini.idpo.pembeliansj: for semuasjdetil in semuasj.pembeliansjdetil: if semuasjdetil.produk in listproduk: listproduk[semuasjdetil.produk] -= semuasjdetil.debit else: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Produk tidak terdaftar!")) for semuaproduk in listproduk: if listproduk[semuaproduk] < 0: notes = "" if semuaproduk.notes != False: notes = str(semuaproduk.notes) raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Jumlah Produk: " + semuaproduk.merk.merk + " " + semuaproduk.namaproduk.namaproduk + " " + notes + " Melebihi Yang Dibeli" + " (Pesan:" + str(semuaproduk.jumlah) + ", Datang:" + str(semuaproduk.jumlah - listproduk[semuaproduk]) + ")")) # 2. Pastikan Stok Keluar tidak melebihi stok masuk for semuapembeliansjdetil in objini.pembeliansjdetil: if semuapembeliansjdetil.debit < semuapembeliansjdetil.kredit: raise osv.except_osv(_('Tidak Dapat Melanjutkan'),_("Barang Keluar lebih Banyak dari yang Masuk")) return True
def onchange_date_from(self, cr, uid, ids, date_to, date_from): """ If there are no date set for date_to, automatically set one 8 hours later than the date_from. Also update the number_of_days. """ # date_from has to be greater then today today= datetime.datetime.now() if (date_from < str(today)): raise osv.except_osv(_('Warning'),_('You are not allowed to create leaves of past dates.')) # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # No date_to set so far: automatically compute one 8 hours later if date_from and not date_to: date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8) result['value']['date_to'] = str(date_to_with_delta) # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result
def create(self, cr, uid, vals, context=None): journal_obj = self.pool.get('account.journal') ana_plan_instance_obj = self.pool.get('account.analytic.plan.instance') acct_anal_acct = self.pool.get('account.analytic.account') acct_anal_plan_line_obj = self.pool.get('account.analytic.plan.line') if context and 'journal_id' in context: journal = journal_obj.browse(cr, uid, context['journal_id'], context=context) pids = ana_plan_instance_obj.search(cr, uid, [('name','=',vals['name']), ('code','=',vals['code']), ('plan_id','<>',False)], context=context) if pids: raise osv.except_osv(_('Error!'), _('A model with this name and code already exists.')) res = acct_anal_plan_line_obj.search(cr, uid, [('plan_id','=',journal.plan_id.id)], context=context) for i in res: total_per_plan = 0 item = acct_anal_plan_line_obj.browse(cr, uid, i, context=context) temp_list = ['account1_ids','account2_ids','account3_ids','account4_ids','account5_ids','account6_ids'] for l in temp_list: if vals.has_key(l): for tempo in vals[l]: if acct_anal_acct.search(cr, uid, [('parent_id', 'child_of', [item.root_analytic_id.id]), ('id', '=', tempo[2]['analytic_account_id'])], context=context): total_per_plan += tempo[2]['rate'] if total_per_plan < item.min_required or total_per_plan > item.max_required: raise osv.except_osv(_('Error!'),_('The total should be between %s and %s.') % (str(item.min_required), str(item.max_required))) return super(account_analytic_plan_instance, self).create(cr, uid, vals, context=context)
def _check_unit_measure(self, cr, uid, ids, context=None): print 'stock check' context = context or {} sm_brw = self.browse(cr, uid, ids[0], context=context) type = sm_brw.picking_id and sm_brw.picking_id.type if not context.get('pass_check', False) and sm_brw.picking_id and \ hasattr(sm_brw.picking_id, 'sale_id') and \ sm_brw.picking_id.sale_id and sm_brw.picking_id.type == 'out': if sm_brw.product_id and\ sm_brw.product_id.uom_id.id != sm_brw.product_uom.id: raise osv.except_osv(_('Error !'), _( "The Unit measure in the line will be the unit measure\ set on the product configuration to sale %s .") % (sm_brw.product_id.name,)) if not context.get('pass_check', False) and \ sm_brw.picking_id and \ hasattr(sm_brw.picking_id, 'purchase_id') and \ sm_brw.picking_id.purchase_id and \ sm_brw.picking_id.type == 'in': if sm_brw.product_id and\ sm_brw.product_id.uom_po_id.id != sm_brw.product_uom.id: raise osv.except_osv(_('Error !'), _( "The Unit measure in the line will be the unit measure\ set on the product configuration to purchase %s .") % (sm_brw.product_id.name,)) return True
def create(self, cr, uid, vals, context=None): reference = vals.get('reference', False) reference_type = vals.get('reference_type', False) if vals.get('type') == 'out_invoice' and not reference_type: # fallback on default communication type for partner reference_type = self.pool.get('res.partner').browse(cr, uid, vals['partner_id']).out_inv_comm_type if reference_type == 'bba': reference = self.generate_bbacomm(cr, uid, [], vals['type'], reference_type, vals['partner_id'], '', context={})['value']['reference'] vals.update({ 'reference_type': reference_type or 'none', 'reference': reference, }) if reference_type == 'bba': if not reference: raise osv.except_osv(_('Warning!'), _('Empty BBA Structured Communication!' \ '\nPlease fill in a unique BBA Structured Communication.')) if self.check_bbacomm(reference): reference = re.sub('\D', '', reference) vals['reference'] = '+++' + reference[0:3] + '/' + reference[3:7] + '/' + reference[7:] + '+++' same_ids = self.search(cr, uid, [('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'), ('reference', '=', vals['reference'])]) if same_ids: raise osv.except_osv(_('Warning!'), _('The BBA Structured Communication has already been used!' \ '\nPlease create manually a unique BBA Structured Communication.')) return super(account_invoice, self).create(cr, uid, vals, context=context)
def change_currency(self, cr, uid, ids, context=None): obj_inv = self.pool.get('account.invoice') obj_inv_line = self.pool.get('account.invoice.line') obj_currency = self.pool.get('res.currency') if context is None: context = {} data = self.browse(cr, uid, ids, context=context)[0] new_currency = data.currency_id.id invoice = obj_inv.browse(cr, uid, context['active_id'], context=context) if invoice.currency_id.id == new_currency: return {} rate = obj_currency.browse(cr, uid, new_currency, context=context).rate for line in invoice.invoice_line: new_price = 0 if invoice.company_id.currency_id.id == invoice.currency_id.id: new_price = line.price_unit * rate if new_price <= 0: raise osv.except_osv(_('Error!'), _('New currency is not configured properly.')) if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id == new_currency: old_rate = invoice.currency_id.rate if old_rate <= 0: raise osv.except_osv(_('Error!'), _('Current currency is not configured properly.')) new_price = line.price_unit / old_rate if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id != new_currency: old_rate = invoice.currency_id.rate if old_rate <= 0: raise osv.except_osv(_('Error!'), _('Current currency is not configured properly.')) new_price = (line.price_unit / old_rate ) * rate obj_inv_line.write(cr, uid, [line.id], {'price_unit': new_price}) obj_inv.write(cr, uid, [invoice.id], {'currency_id': new_currency}, context=context) return {'type': 'ir.actions.act_window_close'}
def import_stock(self, cr, uid, ids, context=None): for excel_data in self.browse(cr, uid, ids): if not excel_data.excel: raise osv.except_osv(_(u'警告!'), _(u'请上传表格!')) excel = xlrd.open_workbook(file_contents=base64.decodestring(excel_data.excel)) product_obj = self.pool.get('product.product') lot_obj = self.pool.get('stock.production.lot') location_obj = self.pool.get('stock.location') table_stock = excel.sheet_by_index(0) if table_stock: inv_data = [] srows = table_stock.nrows #行数 for rx in range(1,srows): stock_res = {} stock_default_code = table_stock.cell(rx, 0).value stock_lot = table_stock.cell(rx, 2).value stock_warehouse = table_stock.cell(rx, 3).value if isinstance(stock_default_code, float): stock_default_code = str(int(stock_default_code)) else: stock_default_code = str(stock_default_code) stock_product_ids = product_obj.search(cr, uid, [('default_code', '=', str(stock_default_code))], context=context) if not stock_product_ids: raise osv.except_osv(_(u'警告!'), _(u'导入模板的产品编号列-第%s行商品%s不存在,请在单品表添加!若已有数据,请确保格式正确或没空格!') % (rx+1,stock_default_code)) else: stock_product_id = stock_product_ids[0] stock_res['product_id'] = stock_product_id stock_uom_data = product_obj.read(cr, uid, stock_product_ids,['uom_id'])[0]['uom_id'][0] stock_res['product_qty'] = table_stock.cell(rx, 1).value stock_res['product_uom'] = stock_uom_data if stock_product_id: if stock_lot and isinstance(stock_lot, float): stock_lot = str(int(stock_lot)) lot_id = lot_obj.search(cr, uid, [('product_id', '=', stock_product_id), ('name', 'ilike', stock_lot), ('ref', '=', stock_default_code)], context=context) if lot_id: lot_id = lot_id[0] else: lot_id = lot_obj.create(cr, uid,{'name':stock_lot,'product_id':stock_product_id}, context=context) stock_res['prod_lot_id'] = lot_id else: stock_res['prod_lot_id'] = False name_no_blank = stock_warehouse.replace(" ", "") name_have_blank = name_no_blank.replace("/", " / ") location_ids = location_obj.search(cr, uid, [('complete_name', '=', name_have_blank)], context=context) if stock_warehouse and (not location_ids): raise osv.except_osv(_(u'警告!'), _(u'导入模板的仓库列-第%s行%s仓库不存在,请在系统创建!') %(rx+1 , stock_warehouse)) elif not stock_warehouse: raise osv.except_osv(_(u'警告!'), _(u'导入模板的仓库列-第%s行为空') %(rx+1)) else: stock_res['location_id'] = location_ids[0] inv_data.append((0, 0, stock_res)) self.pool.get('stock.inventory').create(cr, uid, { 'name':'Import: ' + time.strftime('%Y-%m-%d %H:%M:%S'), 'date':time.strftime('%Y-%m-%d %H:%M:%S'), 'inventory_line_id':inv_data, 'state':'draft'}, context=context) return {'type': 'ir.actions.act_window_close'}
def validate_global_context_dict(self): part = self.pline.partner_id self.global_values['partner_country'] = part.country_id and part.country_id.code + '-' or '' co_addr = self.pline.order_id.company_id self.global_values['comp_country'] = co_addr.country_id and co_addr.country_id.code + '-' or '' if not self.global_values['partner_bank_iban']: raise except_osv(_('Error'), _('No IBAN defined \n for the bank account: %s\n' 'on line: %s') % (self.pline.bank_id.get_account_number(), self.pline.name)) if self.global_values['partner_bank_code']: # Bank code is swift (BIC address) self.global_values['option_id_bank'] = 'A' self.global_values['partner_bank_ident'] = self.global_values['partner_bank_code'] elif self.global_values['partner_bank_city']: self.global_values['option_id_bank'] = 'D' self.global_values['partner_bank_ident'] = self.global_values['partner_bank_name'] \ + ' ' + self.global_values['partner_bank_street'] \ + ' ' + self.global_values['partner_bank_zip'] \ + ' ' + self.global_values['partner_bank_city'] \ + ' ' + self.global_values['partner_bank_country'] else: raise except_osv(_('Error'), _('You must provide the bank city ' 'or the bic code for the partner bank: \n %s\n on line: %s') % (self.pline.bank_id.get_account_number(), self.pline.name))
def _initialize_elec_context(self, cr, uid, data, context=None): elec_context = {} payment_obj = self.pool['payment.order'] payment = payment_obj.browse(cr, uid, data['id'], context=context) elec_context['uid'] = str(uid) elec_context['creation_date'] = time.strftime('%y%m%d') if not payment.mode: raise except_osv(_('Error'), _('No payment mode')) bank = payment.mode.bank_id if not bank: raise except_osv(_('Error'), _('No bank account for the company.')) elec_context['comp_bank_name'] = bank.bank and bank.bank.name or False elec_context['comp_bank_clearing'] = bank.bank.clearing if not elec_context['comp_bank_clearing']: raise except_osv(_('Error'), _('You must provide a Clearing Number for your bank account.')) company = payment.company_id co_addr = company.partner_id elec_context['comp_country'] = co_addr.country_id and co_addr.country_id.name or '' elec_context['comp_street'] = co_addr.street or '' elec_context['comp_zip'] = co_addr.zip elec_context['comp_city'] = co_addr.city elec_context['comp_name'] = co_addr.name elec_context['comp_dta'] = bank.dta_code or '' # Used by Mamuth payment systems # Iban and account number are the same field and depends only on the type of account elec_context['comp_bank_iban'] = elec_context['comp_bank_number'] = bank.acc_number or '' elec_context['comp_bank_iban'] = elec_context['comp_bank_iban'].replace(' ', '') or '' if not elec_context['comp_bank_iban']: raise except_osv(_('Error'), _('No IBAN for the company bank account.')) return elec_context
def action_next(self, cr, uid, ids, context=None): """ Start the survey, Increment in started survey field but if set the max_response_limit of survey then check the current user how many times start this survey. if current user max_response_limit is reach then this user can not start this survey(Raise Exception). """ survey_obj = self.pool.get('survey') search_obj = self.pool.get('ir.ui.view') if context is None: context = {} this = self.browse(cr, uid, ids, context=context)[0] survey_id = this.survey_id.id context.update({'survey_id': survey_id, 'sur_name_id': this.id}) cr.execute('select count(id) from survey_history where user_id=%s\ and survey_id=%s' % (uid,survey_id)) res = cr.fetchone()[0] sur_rec = survey_obj.browse(cr,uid,survey_id,context=context) if sur_rec.response_user and res >= sur_rec.response_user: raise osv.except_osv(_('Warning!'),_("You cannot give response for this survey more than %s times.") % (sur_rec.response_user)) if sur_rec.max_response_limit and sur_rec.max_response_limit <= sur_rec.tot_start_survey: raise osv.except_osv(_('Warning!'),_("You cannot give more responses. Please contact the author of this survey for further assistance.")) search_id = search_obj.search(cr,uid,[('model','=','survey.question.wiz'),('name','=','Survey Search')]) return { 'view_type': 'form', "view_mode": 'form', 'res_model': 'survey.question.wiz', 'type': 'ir.actions.act_window', 'target': 'new', 'search_view_id': search_id[0], 'context': context }
def action_move_create(self, cr, uid, ids, context=None): invoice_line_obj = self.pool.get('account.invoice.line') account_obj = self.pool.get('account.account') for id_ in ids: lines = invoice_line_obj.search( cr, uid, [('invoice_id', '=', id_)]) for line in lines: id_account = invoice_line_obj.browse( cr, uid, line).account_id.id type_line = account_obj.browse(cr, uid, id_account).type if type_line == 'receivable' or type_line == 'payable': raise osv.except_osv(_('Error'), _( """Type of account in line's must be differt to 'receivable' and 'payable'""")) type_acc_invo = self.browse(cr, uid, id_).account_id.type type_invoice = self.browse(cr, uid, id_).type if (type_invoice == 'out_invoice' or type_invoice == 'out_refound') and \ type_acc_invo != 'receivable': raise osv.except_osv(_('Error'), _( """Type of account in invoice to Customer must be 'receivable'""")) if (type_invoice == 'in_invoice' or type_invoice == 'in_refound') and \ type_acc_invo != 'payable': raise osv.except_osv(_('Error'), _( "Type of account in invoice to Partner must be 'payable'")) return super(AccountInvoice, self).action_move_create(cr, uid, ids)
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, currency_id=False, context=None, company_id=None): res = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit,currency_id, context=context, company_id=company_id) def get_real_price(res_dict, product_id, qty, uom, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') field_name = 'list_price' if res_dict.get('item_id',False) and res_dict['item_id'].get(pricelist,False): item = res_dict['item_id'].get(pricelist,False) item_read = item_obj.read(cr, uid, [item], ['base']) if item_read: item_base = item_read[0]['base'] if item_base > 0: field_name = price_type_obj.browse(cr, uid, item_base).field product = product_obj.browse(cr, uid, product_id, context) product_read = product_obj.read(cr, uid, product_id, [field_name], context=context) factor = 1.0 if uom and uom != product.uom_id.id: product_uom_obj = self.pool.get('product.uom') uom_data = product_uom_obj.browse(cr, uid, product.uom_id.id) factor = uom_data.factor return product_read[field_name] * factor if product: pricelist_obj = self.pool.get('product.pricelist') partner_obj = self.pool.get('res.partner') product = self.pool.get('product.product').browse(cr, uid, product, context=context) result = res['value'] pricelist = False real_price = 0.00 if type in ('in_invoice', 'in_refund'): if not price_unit and partner_id: pricelist =partner_obj.browse(cr, uid, partner_id).property_product_pricelist_purchase.id if not pricelist: raise osv.except_osv(_('No Purchase Pricelist Found!'),_("You must first define a pricelist on the supplier form!")) price_unit_res = pricelist_obj.price_get(cr, uid, [pricelist], product.id, qty or 1.0, partner_id, {'uom': uom}) price_unit = price_unit_res[pricelist] real_price = get_real_price(price_unit_res, product.id, qty, uom, pricelist) else: if partner_id: pricelist = partner_obj.browse(cr, uid, partner_id).property_product_pricelist.id if not pricelist: raise osv.except_osv(_('No Sale Pricelist Found!'),_("You must first define a pricelist on the customer form!")) price_unit_res = pricelist_obj.price_get(cr, uid, [pricelist], product.id, qty or 1.0, partner_id, {'uom': uom}) price_unit = price_unit_res[pricelist] real_price = get_real_price(price_unit_res, product.id, qty, uom, pricelist) if pricelist: pricelists=pricelist_obj.read(cr,uid,[pricelist],['visible_discount']) if(len(pricelists)>0 and pricelists[0]['visible_discount'] and real_price != 0): discount=(real_price-price_unit) / real_price * 100 result['price_unit'] = real_price result['discount'] = discount else: result['discount']=0.0 return res
def _compute_purchase_order_portal_url(self): #http://localhost:8069/web?db=elmatica_v1#id=377&view_type=form&model=sale.order&menu_id=471&action=645 dbname = self.env.cr.dbname parameter_url = self.env['ir.config_parameter'].sudo().search([('key','=','web.base.url')]) if not parameter_url: raise osv.except_osv(('Error'), ('portal_url parameter missing!!!')) return None parameter_url = parameter_url.value #Portal/Elmatica/Sale Orders #menu_item = self.env['ir.ui.menu'].sudo().search([('complete_name','=','Portal/Elmatica/Sale Orders')]) #if not menu_item: # raise osv.except_osv(('Error'), ('elmatica_portal module is not installed!!!')) # return None portal.purchase.order.form #view_ids = self.env['ir.ui.view'].sudo().search([('name','=','portal.purchase.order.form')]) #if not view_ids: # raise osv.except_osv(('Error'), ('elmatica_portal module is not installed!!!')) # return None #for view_id in view_ids: action_id = self.env['ir.actions.act_window'].sudo().search([('name','=','portal.purchase.order')]) if action_id: return_url = parameter_url + '/web?='+dbname+'#id'+str(self.id)+\ "&view_type=form&model=purchase.order&action="+str(action_id.id) self.purchase_order_portal_url = return_url return raise osv.except_osv(('Error'), ('elmatica_portal module is not installed!!!'))
def _get_default_produce_line_ids(self, cr, uid, context=None): """ Search the active stock moves from products to produce and then generate the list of dictionary values to create the produce line ids """ context = context or {} production_obj = self.pool.get('mrp.production') produce_line_list = list() production_ids = context.get('active_ids', []) active_model = context.get('active_model', False) if not production_ids or len(production_ids) != 1: raise osv.except_osv( _('Error!!'), _('You need to call method using the wizard from the' ' manufacturing order one by one.')) if active_model not in ['mrp.production']: raise osv.except_osv( _('Error!!'), _('You this wizard can be only called by the manufacturing' ' order.')) production_id = production_ids[0] production_brw = production_obj.browse( cr, uid, production_id, context=context) produce_line_list = self._get_produce_line_list( cr, uid, production_id, context=context) return produce_line_list
def _get_default_consume_line_ids(self, cr, uid, context=None): """ Return the consume lines ids by default for the current work order lot """ context = context or {} consume_line_ids = list() production_obj = self.pool.get('mrp.production') wol_obj = self.pool.get('mrp.workorder.lot') production_ids = context.get('active_ids', []) active_model = context.get('active_model', False) if not production_ids or len(production_ids) != 1: raise osv.except_osv( _('Error!!'), _('You need to call method using the wizard, one by one per' ' manufacturing order or by an active work order lot.')) if active_model not in ['mrp.production', 'mrp.workorder.lot']: raise osv.except_osv( _('Error!!'), _('You this wizard can be only called by the manufacturing' ' order or by an active work order lot.')) production_id = active_model == 'mrp.production' \ and production_ids[0] or wol_obj.browse( cr, uid, production_ids, context=context)[0].production_id.id consume_line_ids = self._get_consume_lines_list( cr, uid, production_id, context=context) return consume_line_ids
def _get_default_wo_lot(self, cr, uid, context=None): """ @return: The first Work Order Lot ready to Produce (cardinal order). """ context = context or {} res = False production_obj = self.pool.get('mrp.production') active_id = context.get('active_id', False) active_model = context.get('active_model', False) if active_id: if active_model == 'mrp.production': production_id = active_id wol_brws = production_obj.browse( cr, uid, production_id, context=context).wo_lot_ids res = [wol_brw.id for wol_brw in wol_brws if wol_brw.state == 'ready'] elif active_model == 'mrp.workorder.lot': res = [active_id] else: raise osv.except_osv( _('Error!!'), _('This wizard only can be call from the manufacturing' ' order form or the Work Orders by Active Lot menu.')) if not res: raise osv.except_osv( _('Warning!!'), _('You can Produce because you have not Ready to Finish' ' Work Order Lots.')) return res and res[0] or False
def afip_validation(self, cr, uid, ids, context={}): obj_resp_class = self.pool.get('afip.responsability_relation') for invoice in self.browse(cr, uid, ids): # If parter is not in Argentina, ignore it. if invoice.partner_id.country_id.name != 'Argentina': continue # Partner responsability ? if isinstance(invoice.partner_id.responsability_id, orm.browse_null): raise osv.except_osv(_('No responsability'), _('Your partner have not afip responsability assigned. Assign one please.')) # Take responsability classes for this journal invoice_class = invoice.journal_id.journal_class_id.document_class_id resp_class_ids = obj_resp_class.search(cr, uid, [('document_class_id','=', invoice_class.id)]) # You can emmit this document? resp_class = [ rc.issuer_id.code for rc in obj_resp_class.browse(cr, uid, resp_class_ids) ] if invoice.journal_id.company_id.partner_id.responsability_id.code not in resp_class: raise osv.except_osv(_('Invalid emisor'), _('Your responsability with AFIP dont let you generate this kind of document.')) # Partner can receive this document? resp_class = [ rc.receptor_id.code for rc in obj_resp_class.browse(cr, uid, resp_class_ids) ] if False and invoice.partner_id.responsability_id.code not in resp_class: raise osv.except_osv(_('Invalid receptor'), _('Your partner cant recive this document. Check AFIP responsability of the partner, or Journal Account of the invoice.')) # If Final Consumer have pay more than 1000$, you need more information to generate document. if invoice.partner_id.responsability_id.code == 'CF' and invoice.amount_total > 1000 and \ (invoice.partner_id.document_type.code in [ None, 'Sigd' ] or invoice.partner_id.document_number is None): raise osv.except_osv(_('Partner without Identification for total invoices > $1000.-'), _('You must define valid document type and number for this Final Consumer.')) return True
def confirm_indent(self, cr, uid, ids,context=None): product_obj = self.pool.get('product.product') """ Indent approve """ for t in self.browse(cr,uid,ids): if not t.dep_indent_line: raise osv.except_osv( _('Empty Department Indent'), _('You can not confirm an empty Department Indent')) depindent_line = t.dep_indent_line[0] depindent_line_id = depindent_line.id if t.dep_indent_line[0].qty==0: raise osv.except_osv( _('Error'), _('Department Indent quantity can not be zero')) for line in t.dep_indent_line: product_record = product_obj.browse(cr,uid,line.product_id.id) if line.uom.id != product_record.uom_po_id.id: new_po_qty = line.qty / product_record.po_uom_coeff #self.write(cr,uid,line.id,{'po_qty' : new_po_qty}) self.write(cr,uid,ids,{'state':'confirm'}) return True
def create_invoices(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) # Additional case, Line Percentage if wizard.advance_payment_method == "line_percentage": if not wizard.line_percent: raise osv.except_osv(_("Warning!"), _("You did not specify installment!")) # Getting Sale Order Line IDs of this SO sale_obj = self.pool.get("sale.order") sale_ids = context.get("active_ids", []) order = sale_obj.browse(cr, uid, sale_ids[0]) order_line_ids = [] if order.invoiced_rate + wizard.line_percent > 100: raise osv.except_osv( _("Warning!"), _("This percentage is too high, it make overall " "invoiced rate exceed 100%!") ) for order_line in order.order_line: order_line_ids.append(order_line.id) # Assign them into active_ids context.update({"active_ids": order_line_ids}) context.update({"line_percent": wizard.line_percent}) sale_order_line_make_invoice_obj = self.pool.get("sale.order.line.make.invoice") res = sale_order_line_make_invoice_obj.make_invoices(cr, uid, ids, context=context) # Update invoice if res.get("res_id"): self.pool.get("account.invoice").button_compute(cr, uid, [res.get("res_id")], context=context) return res else: return super(sale_advance_payment_inv, self).create_invoices(cr, uid, ids, context=context)
def act_update(self, cr, uid, ids, context=None): ''' Function called by the wizard. ''' if context is None: context = {} flag, gengo = self.gengo_authentication(cr, uid, context=context) if not flag: raise osv.except_osv(_('Gengo Authentication Error'), gengo) for wizard in self.browse(cr, uid, ids, context=context): supported_langs = self.pool.get('ir.translation')._get_all_supported_languages(cr, uid, context=context) language = self.pool.get('ir.translation')._get_gengo_corresponding_language(wizard.lang_id.code) if language not in supported_langs: raise osv.except_osv(_("Warning"), _('This language is not supported by the Gengo translation services.')) ctx = context.copy() ctx['gengo_language'] = wizard.lang_id.id if wizard.sync_limit > 200 or wizard.sync_limit < 1: raise osv.except_osv(_("Warning"), _('Sync limit should between 1 to 200 for Gengo translation services.')) if wizard.sync_type in ['send', 'both']: self._sync_request(cr, uid, wizard.sync_limit, context=ctx) if wizard.sync_type in ['receive', 'both']: self._sync_response(cr, uid, wizard.sync_limit, context=ctx) return {'type': 'ir.actions.act_window_close'}
def act_export_ats(self, cr, uid, ids, context): inv_obj = self.pool.get('account.invoice') wiz = self.browse(cr, uid, ids)[0] period_id = wiz.period_id.id ruc = wiz.company_id.partner_id.ced_ruc ats = etree.Element('iva') etree.SubElement(ats, 'TipoIDInformante').text = 'R' etree.SubElement(ats, 'IdInformante').text = str(ruc) etree.SubElement(ats, 'razonSocial').text = wiz.company_id.name period = self.pool.get('account.period').browse(cr, uid, [period_id])[0] # noqa etree.SubElement(ats, 'Anio').text = time.strftime('%Y', time.strptime(period.date_start, '%Y-%m-%d')) # noqa etree.SubElement(ats, 'Mes'). text = time.strftime('%m', time.strptime(period.date_start, '%Y-%m-%d')) # noqa etree.SubElement(ats, 'numEstabRuc').text = wiz.num_estab_ruc.zfill(3) total_ventas = self._get_ventas(cr, period_id) etree.SubElement(ats, 'totalVentas').text = total_ventas etree.SubElement(ats, 'codigoOperativo').text = 'IVA' compras = etree.Element('compras') # Facturas de Compra con retenciones inv_ids = inv_obj.search(cr, uid, [('state', 'in', ['open', 'paid']), ('period_id', '=', period_id), ('type', 'in', ['in_invoice', 'liq_purchase']), # noqa ('company_id', '=', wiz.company_id.id)]) # noqa self.__logger.info("Compras registradas: %s" % len(inv_ids)) for inv in inv_obj.browse(cr, uid, inv_ids): detallecompras = etree.Element('detalleCompras') etree.SubElement(detallecompras, 'codSustento').text = inv.sustento_id.code # noqa if not inv.partner_id.ced_ruc: raise osv.except_osv('Datos incompletos', 'No ha ingresado toda los datos de %s' % inv.partner_id.name) # noqa etree.SubElement(detallecompras, 'tpIdProv').text = tpIdProv[inv.partner_id.type_ced_ruc] # noqa etree.SubElement(detallecompras, 'idProv').text = inv.partner_id.ced_ruc # noqa if inv.auth_inv_id: tcomp = inv.auth_inv_id.type_id.code else: tcomp = '03' etree.SubElement(detallecompras, 'tipoComprobante').text = tcomp etree.SubElement(detallecompras, 'fechaRegistro').text = self.convertir_fecha(inv.date_invoice) # noqa if inv.type == 'in_invoice': se = inv.auth_inv_id.serie_entidad pe = inv.auth_inv_id.serie_emision sec = '%09d' % int(inv.reference) auth = inv.auth_inv_id.name elif inv.type == 'liq_purchase': se = inv.journal_id.auth_id.serie_entidad pe = inv.journal_id.auth_id.serie_emision sec = inv.number[8:] auth = inv.journal_id.auth_id.name etree.SubElement(detallecompras, 'establecimiento').text = se etree.SubElement(detallecompras, 'puntoEmision').text = pe etree.SubElement(detallecompras, 'secuencial').text = sec etree.SubElement(detallecompras, 'fechaEmision').text = self.convertir_fecha(inv.date_invoice) # noqa etree.SubElement(detallecompras, 'autorizacion').text = auth etree.SubElement(detallecompras, 'baseNoGraIva').text = inv.amount_novat == 0 and '0.00' or '%.2f' % inv.amount_novat # noqa etree.SubElement(detallecompras, 'baseImponible').text = '%.2f' % inv.amount_vat_cero # noqa etree.SubElement(detallecompras, 'baseImpGrav').text = '%.2f' % inv.amount_vat # noqa etree.SubElement(detallecompras, 'baseImpExe').text = '0.00' etree.SubElement(detallecompras, 'montoIce').text = '0.00' etree.SubElement(detallecompras, 'montoIva').text = '%.2f' % inv.amount_tax # noqa valRetBien10, valRetServ20, valorRetBienes, valorRetServicios, valorRetServ100 = self._get_ret_iva(inv) # noqa etree.SubElement(detallecompras, 'valRetBien10').text = '%.2f' % valRetBien10 # noqa etree.SubElement(detallecompras, 'valRetServ20').text = '%.2f' % valRetServ20 # noqa etree.SubElement(detallecompras, 'valorRetBienes').text = '%.2f' % valorRetBienes # noqa # etree.SubElement(detallecompras, 'valorRetBienes').text = '%.2f'%abs(inv.taxed_ret_vatb) # noqa etree.SubElement(detallecompras, 'valorRetServicios').text = '%.2f' % valorRetServicios # noqa etree.SubElement(detallecompras, 'valRetServ100').text = '%.2f' % valorRetServ100 # noqa etree.SubElement(detallecompras, 'totbasesImpReemb').text = '0.00' pagoExterior = etree.Element('pagoExterior') etree.SubElement(pagoExterior, 'pagoLocExt').text = '01' etree.SubElement(pagoExterior, 'paisEfecPago').text = 'NA' etree.SubElement(pagoExterior, 'aplicConvDobTrib').text = 'NA' etree.SubElement(pagoExterior, 'pagExtSujRetNorLeg').text = 'NA' detallecompras.append(pagoExterior) if inv.amount_pay >= wiz.pay_limit: formasDePago = etree.Element('formasDePago') etree.SubElement(formasDePago, 'formaPago').text = '02' detallecompras.append(formasDePago) if inv.retention_ir or inv.no_retention_ir: air = etree.Element('air') data_air = self.process_lines(cr, uid, inv.tax_line) for da in data_air: detalleAir = etree.Element('detalleAir') etree.SubElement(detalleAir, 'codRetAir').text = da['codRetAir'] # noqa etree.SubElement(detalleAir, 'baseImpAir').text = '%.2f' % da['baseImpAir'] # noqa etree.SubElement(detalleAir, 'porcentajeAir').text = '%.2f' % da['porcentajeAir'] # noqa etree.SubElement(detalleAir, 'valRetAir').text = '%.2f' % da['valRetAir'] # noqa air.append(detalleAir) detallecompras.append(air) flag = False if inv.retention_id and (inv.retention_ir or inv.retention_vat): flag = True etree.SubElement(detallecompras, 'estabRetencion1').text = flag and inv.journal_id.auth_ret_id.serie_entidad or '000' # noqa etree.SubElement(detallecompras, 'ptoEmiRetencion1').text = flag and inv.journal_id.auth_ret_id.serie_emision or '000' # noqa etree.SubElement(detallecompras, 'secRetencion1').text = flag and inv.retention_id.num_document[6:] or '%09d' % 0 # noqa etree.SubElement(detallecompras, 'autRetencion1').text = flag and inv.journal_id.auth_ret_id.name or '%010d' % 0 # noqa etree.SubElement(detallecompras, 'fechaEmiRet1').text = flag and self.convertir_fecha(inv.retention_id.date) # noqa compras.append(detallecompras) ats.append(compras) if float(total_ventas) > 0: # VENTAS DECLARADAS ventas = etree.Element('ventas') inv_ids = inv_obj.search(cr, uid, [ ('state', 'in', ['open', 'paid']), ('period_id', '=', period_id), ('type', 'in', ['out_invoice', 'out_refund']), ('company_id', '=', wiz.company_id.id)]) pdata = {} self.__logger.info("Ventas registradas: %s" % len(inv_ids)) for inv in inv_obj.browse(cr, uid, inv_ids): part_id = inv.partner_id.id tipoComprobante = inv.journal_id.auth_id.type_id.code keyp = '%s-%s' % (part_id, tipoComprobante) partner_data = { keyp: { 'tpIdCliente': inv.partner_id.type_ced_ruc, 'idCliente': inv.partner_id.ced_ruc, 'numeroComprobantes': 0, 'basenoGraIva': 0, 'baseImponible': 0, 'baseImpGrav': 0, 'montoIva': 0, 'valorRetRenta': 0, 'tipoComprobante': tipoComprobante, 'valorRetIva': 0 } } if not pdata.get(keyp, False): pdata.update(partner_data) elif pdata[keyp]['tipoComprobante'] == tipoComprobante: pdata[keyp]['numeroComprobantes'] += 1 else: pdata.update(partner_data) pdata[keyp]['basenoGraIva'] += inv.amount_novat pdata[keyp]['baseImponible'] += inv.amount_vat_cero pdata[keyp]['baseImpGrav'] += inv.amount_vat pdata[keyp]['montoIva'] += inv.amount_tax if inv.retention_ir: data_air = self.process_lines(cr, uid, inv.tax_line) for dt in data_air: pdata[keyp]['valorRetRenta'] += dt['valRetAir'] pdata[keyp]['valorRetIva'] += abs(inv.taxed_ret_vatb) + abs(inv.taxed_ret_vatsrv) # noqa for k, v in pdata.items(): detalleVentas = etree.Element('detalleVentas') etree.SubElement(detalleVentas, 'tpIdCliente').text = tpIdCliente[v['tpIdCliente']] # noqa etree.SubElement(detalleVentas, 'idCliente').text = v['idCliente'] # noqa etree.SubElement(detalleVentas, 'parteRelVtas').text = 'NO' etree.SubElement(detalleVentas, 'tipoComprobante').text = v['tipoComprobante'] # noqa etree.SubElement(detalleVentas, 'numeroComprobantes').text = str(v['numeroComprobantes']) # noqa etree.SubElement(detalleVentas, 'baseNoGraIva').text = '%.2f' % v['basenoGraIva'] # noqa etree.SubElement(detalleVentas, 'baseImponible').text = '%.2f' % v['baseImponible'] # noqa etree.SubElement(detalleVentas, 'baseImpGrav').text = '%.2f' % v['baseImpGrav'] # noqa etree.SubElement(detalleVentas, 'montoIva').text = '%.2f' % v['montoIva'] # noqa etree.SubElement(detalleVentas, 'valorRetIva').text = '%.2f' % v['valorRetIva'] # noqa etree.SubElement(detalleVentas, 'valorRetRenta').text = '%.2f' % v['valorRetRenta'] # noqa ventas.append(detalleVentas) ats.append(ventas) # Ventas establecimiento ventasEstablecimiento = etree.Element('ventasEstablecimiento') ventaEst = etree.Element('ventaEst') etree.SubElement(ventaEst, 'codEstab').text = inv.journal_id.auth_id.serie_emision # noqa etree.SubElement(ventaEst, 'ventasEstab').text = self._get_ventas(cr, period_id) # noqa ventasEstablecimiento.append(ventaEst) ats.append(ventasEstablecimiento) # Documentos Anulados anulados = etree.Element('anulados') inv_ids = inv_obj.search(cr, uid, [('state', '=', 'cancel'), ('period_id', '=', period_id), ('type', '=', 'out_invoice'), ('company_id', '=', wiz.company_id.id)]) # noqa self.__logger.info("Ventas Anuladas: %s" % len(inv_ids)) for inv in inv_obj.browse(cr, uid, inv_ids): detalleAnulados = etree.Element('detalleAnulados') etree.SubElement(detalleAnulados, 'tipoComprobante').text = inv.journal_id.auth_id.type_id.code # noqa etree.SubElement(detalleAnulados, 'establecimiento').text = inv.journal_id.auth_id.serie_entidad # noqa etree.SubElement(detalleAnulados, 'puntoEmision').text = inv.journal_id.auth_id.serie_emision # noqa etree.SubElement(detalleAnulados, 'secuencialInicio').text = str(int(inv.number[8:])) # noqa etree.SubElement(detalleAnulados, 'secuencialFin').text = str(int(inv.number[8:])) # noqa etree.SubElement(detalleAnulados, 'autorizacion').text = inv.journal_id.auth_id.name # noqa anulados.append(detalleAnulados) # Liquidaciones de compra liq_ids = inv_obj.search(cr, uid, [('state', '=', 'cancel'), ('period_id', '=', period_id), ('type', '=', 'liq_purchase'), ('company_id', '=', wiz.company_id.id)]) # noqa for inv in inv_obj.browse(cr, uid, liq_ids): detalleAnulados = etree.Element('detalleAnulados') etree.SubElement(detalleAnulados, 'tipoComprobante').text = inv.journal_id.auth_id.type_id.code # noqa etree.SubElement(detalleAnulados, 'establecimiento').text = inv.journal_id.auth_id.serie_entidad # noqa etree.SubElement(detalleAnulados, 'puntoEmision').text = inv.journal_id.auth_id.serie_emision # noqa etree.SubElement(detalleAnulados, 'secuencialInicio').text = str(int(inv.number[8:])) # noqa etree.SubElement(detalleAnulados, 'secuencialFin').text = str(int(inv.number[8:])) # noqa etree.SubElement(detalleAnulados, 'autorizacion').text = inv.journal_id.auth_id.name # noqa anulados.append(detalleAnulados) retention_obj = self.pool.get('account.retention') ret_ids = retention_obj.search(cr, uid, [('state', '=', 'cancel'), ('in_type', '=', 'ret_out_invoice'), # noqa ('date', '>=', wiz.period_id.date_start), # noqa ('date', '<=', wiz.period_id.date_stop)]) # noqa for ret in retention_obj.browse(cr, uid, ret_ids): detalleAnulados = etree.Element('detalleAnulados') etree.SubElement(detalleAnulados, 'tipoComprobante').text = ret.auth_id.type_id.code # noqa etree.SubElement(detalleAnulados, 'establecimiento').text = ret.auth_id.serie_entidad # noqa etree.SubElement(detalleAnulados, 'puntoEmision').text = ret.auth_id.serie_emision # noqa etree.SubElement(detalleAnulados, 'secuencialInicio').text = str(int(ret.num_document[8:])) # noqa etree.SubElement(detalleAnulados, 'secuencialFin').text = str(int(ret.num_document[8:])) # noqa etree.SubElement(detalleAnulados, 'autorizacion').text = ret.auth_id.name # noqa anulados.append(detalleAnulados) ats.append(anulados) file_path = os.path.join(os.path.dirname(__file__), 'XSD/ats.xsd') schema_file = open(file_path) file_ats = etree.tostring(ats, pretty_print=True, encoding='iso-8859-1') # validata schema xmlschema_doc = etree.parse(schema_file) xmlschema = etree.XMLSchema(xmlschema_doc) if not wiz.no_validate: try: xmlschema.assertValid(ats) except DocumentInvalid as e: raise osv.except_osv( 'Error de Datos', u"""El sistema generó el XML pero los datos no pasan la validación XSD del SRI. \nLos errores mas comunes son:\n * RUC,Cédula o Pasaporte contiene caracteres no válidos. \n* Números de documentos están duplicados.\n\n El siguiente error contiene el identificador o número de documento en conflicto:\n\n %s""" % str(e)) # noqa buf = StringIO.StringIO() buf.write(file_ats) out = base64.encodestring(buf.getvalue()) buf.close() name = "%s%s%s.XML" % ( "AT", wiz.period_id.name[:2], wiz.period_id.name[3:8] ) self.write(cr, uid, ids, { 'state': 'export', 'data': out, 'fcname': name }) return { 'type': 'ir.actions.act_window', 'res_model': 'wizard.ats', 'view_mode': ' form', 'view_type': ' form', 'res_id': wiz.id, 'views': [(False, 'form')], 'target': 'new', }
def create_packing(self, cr, uid, ids, context=None): picking_id = self.browse(cr, uid, ids, context=context) if picking_id.retur == True: for move_line in picking_id.move_lines: code = False field = False retur_line_id = False if move_line.retur_beli_line_id.retur_id.retur_type == 'Barang': code = 'outgoing' field = 'retur_beli_line_id' retur_line_id = move_line.retur_beli_line_id.id warning1 = "Pengembalian barang ke supplier belum lengkap" elif move_line.retur_jual_line_id.retur_id.retur_type == 'Barang': code = 'incoming' field = 'retur_jual_line_id' retur_line_id = move_line.retur_jual_line_id.id warning1 = "Pengembalian barang dari customer belum lengkap" if code and field and retur_line_id: move_search = move_line.search([(field,'=',retur_line_id),('picking_id.picking_type_id.code','=',code),('state','!=','done')]) if move_search: raise osv.except_osv(('Perhatian !'), (warning1)) else: move_search = move_line.search([('picking_id.origin','=',picking_id.origin),('picking_id.picking_type_id.code','=',code),('state','!=','done'),('retur_beli_line_id','=',False),('retur_jual_line_id','=',False)]) if move_search: raise osv.except_osv(('Perhatian !'), (warning1)) if picking_id.branch_id.branch_type == 'MD' and picking_id.division == 'Unit' and picking_id.picking_type_code == 'incoming' and not picking_id.is_reverse and picking_id.state != 'done' : raise osv.except_osv(('Perhatian !'), ("Untuk penerimaan Unit MD silahkan create di menu Showroom > Good Receipt Note MD")) packing_draft = self.pool.get('dym.stock.packing').search(cr, uid, [ ('picking_id','=',picking_id.id), ('state','=','draft') ]) if picking_id.state == 'done' or packing_draft : return self.view_packing(cr,uid,ids,context) obj_packing = self.pool.get('dym.stock.packing') obj_packing_line = self.pool.get('dym.stock.packing.line') branch_sender_id = False if picking_id.picking_type_code == 'interbranch_in' : branch_sender_id = picking_id.location_id.branch_id.id packing_vals = { 'picking_id': picking_id.id, 'branch_sender_id': branch_sender_id, 'picking_type_id': picking_id.picking_type_id.id, # 'division':picking_id.division, } id_packing = obj_packing.create(cr, uid, packing_vals, context=context) if (picking_id.picking_type_code == 'outgoing' and picking_id.rel_branch_type == 'DL') or picking_id.division == 'Umum' or picking_id.is_reverse : ids_move = self.get_ids_move(cr, uid, ids, context) for move in picking_id.move_lines: if move.state not in ['draft','cancel']: if picking_id.picking_type_code == 'incoming' and not picking_id.is_reverse : current_reserved = 0 stock_available = self.get_seharusnya(cr, uid, ids, context)[move.product_id] elif picking_id.is_reverse : current_reserved = self.get_current_reserved(cr, uid, ids, move.product_id.id, move.location_id.id, ids_move, context) if picking_id.picking_type_code in ('outgoing','interbranch_out'): stock_available = self.get_stock_available(cr, uid, ids, move.product_id.id, move.location_id.id, context) else: stock_available = 0 elif move.product_id.categ_id.isParentName('Extras') : current_reserved = self.get_current_reserved(cr, uid, ids, move.product_id.id, move.location_id.id, ids_move, context) stock_available = self.get_stock_available_extras(cr, uid, ids, move.product_id.id, move.location_id.id, context) else : current_reserved = self.get_current_reserved(cr, uid, ids, move.product_id.id, move.location_id.id, ids_move, context) stock_available = self.get_stock_available(cr, uid, ids, move.product_id.id, move.location_id.id, context) seharusnya = self.get_seharusnya(cr, uid, ids, context)[move.product_id] packing_line_vals = { 'packing_id': id_packing, 'template_id': move.product_tmpl_id.id, 'product_id': move.product_id.id, # 'quantity': self.get_qty(cr, uid, ids, picking_id, move.product_id, move.product_uom_qty, context), 'quantity': seharusnya, 'seharusnya': seharusnya, 'serial_number_id': move.restrict_lot_id.id, 'engine_number': move.restrict_lot_id.name, 'chassis_number': move.restrict_lot_id.chassis_no, 'source_location_id': move.restrict_lot_id.location_id.id if move.restrict_lot_id and move.picking_id.picking_type_code in ('outgoing','interbranch_out','internal') else move.location_id.id, 'destination_location_id': move.location_dest_id.id, 'tahun_pembuatan': move.restrict_lot_id.tahun, 'ready_for_sale': self.convert_rfs(cr, uid, ids, move.restrict_lot_id.ready_for_sale, context), 'current_reserved': current_reserved, 'stock_available': stock_available, 'purchase_line_id': move.purchase_line_id.id, 'move_id': move.id, } obj_packing_line.create(cr, uid, packing_line_vals) return self.view_packing(cr, uid, ids, context)
def change_password(self, cr, uid, old_passwd, new_passwd, context=None): self.check(cr.dbname, uid, old_passwd) if new_passwd: return self.write(cr, SUPERUSER_ID, uid, {'password': new_passwd, 'active': True}) raise osv.except_osv(_('Warning!'), _("Setting empty passwords is not allowed for security reasons!"))
def create(self, cr, uid, values, context=None): # overridden to automatically invite user to sign up if context and context.get('reset_password'): context.pop('reset_password') if context and context.get('create_patient'): values['active'] = False values['tmp_name'] = values['login'] if values['use_email']: values['login'] = values['email'] user_id = super(res_users, self).create(cr, uid, values, context=context) user = self.browse(cr, uid, user_id, context=context) token = random_token() if context and context.get('create_patient') and user.partner_id: country = self.pool.get('res.country').search(cr, uid, [('code', '=', 'EC')]) state = self.pool.get('res.country.state').search(cr, uid, [('country_id', '=', country[0]), ('code', '=', 'PIC')]) self.pool.get('res.partner').write(cr, uid, [user.partner_id.id], { 'name': values['first_name'] + ' ' + values['last_name'] + ' ' + values['slastname'], 'user_id': user_id, 'country_id': country[0], 'state_id': state[0], 'city': 'Quito', 'signup_token': token, 'signup_type': 'signup', 'signup_expiration': now(days=+1), 'notification_email_send': 'none', 'tz': 'America/Guayaquil' }, context=None) self.pool.get('oemedical.patient').create(cr, uid, { 'partner_id': user.partner_id.id, 'ref': self.pool.get('ir.sequence').get(cr, uid, 'oemedical.patient'), }, context=None) patient_group = self.pool.get('ir.model.data').get_object(cr, uid, 'oemedical', 'patient_group') portal_group = self.pool.get('ir.model.data').get_object(cr, uid, 'portal', 'group_portal') employee_group = self.pool.get('ir.model.data').get_object(cr, uid, 'base', 'group_user') if patient_group: self.write(cr, uid, [user_id], { 'groups_id': [(4, patient_group.id)] }, context=context) if portal_group: self.write(cr, uid, [user_id], { 'groups_id': [(3, portal_group.id)] }, context=context) if employee_group: self.write(cr, uid, [user_id], { 'groups_id': [(3, employee_group.id)] }, context=context) else: is_patient = False is_doctor = False patient_group = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oemedical', 'patient_group') patient_group_id = filter(lambda g: g.id == patient_group[1], user.groups_id) if len(patient_group_id): is_patient = True self.pool.get('oemedical.patient').create(cr, uid, { 'partner_id': user.partner_id.id, 'ref': self.pool.get('ir.sequence').get(cr, uid, 'oemedical.patient'), }, context=None) doctor_group = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oemedical', 'doctor_group') doctor_group_id = filter(lambda g: g.id == doctor_group[1], user.groups_id) if len(doctor_group_id): is_doctor = True self.pool.get('oemedical.physician').create(cr, uid, { 'physician_id': user.partner_id.id }, context=None) self.pool.get('res.partner').write(cr, uid, [user.partner_id.id], { 'user_id': user_id, 'signup_token': token, 'signup_type': 'reset', 'signup_expiration': now(days=+1), 'is_patient': is_patient, 'is_doctor': is_doctor }, context=None) if context and context.get('create_patient'): template = self.pool.get('ir.model.data').get_object(cr, uid, 'oemedical_auth_signup', 'activation_account_email') else: template = self.pool.get('ir.model.data').get_object(cr, uid, 'oemedical_auth_signup', 'activation_created_account_email') try: if not template: raise osv.except_osv(_("Cannot send email: email template not found."), user.name) if not user.email: raise osv.except_osv(_("Cannot send email: user has no email address."), user.name) mail_id = self.pool.get('email.template').send_mail(cr, uid, template.id, user.id, True, context=context) mail_obj = self.pool.get('mail.mail') mail_state = mail_obj.read(cr, uid, mail_id, ['state'], context=context) if mail_state and mail_state['state'] == 'exception': raise osv.except_osv(_("Cannot send email: no outgoing email server configured.\nYou can configure it under Settings/General Settings."), user.name) except ValueError as e: _logger.exception(e.message) pass return user_id
def print_fee_analysis_ms_excel(self, cr, uid, ids, data): print("print_fee_analysis_ms_excel called") result = [] book = xlwt.Workbook() header_top = xlwt.Style.easyxf( 'font: bold 0, color white, height 250;' 'align: vertical center, horizontal center, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour gray80;') header_feetypes = xlwt.Style.easyxf( 'font: bold 0, color white, , height 250;' 'align: vertical center, horizontal center, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour light_blue;') header_months = xlwt.Style.easyxf( 'font: bold 0, color black, height 250;' 'align: vertical center, horizontal center, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour light_green;') student_white_rows = xlwt.Style.easyxf( 'font: bold 0, color black, height 250;' 'align: vertical center, horizontal left, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour white;') student_grey_rows = xlwt.Style.easyxf( 'font: bold 0, color black, height 250;' 'align: vertical center, horizontal left, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour gray25 ;') paid_fee = xlwt.Style.easyxf( 'font: bold 0, color black, height 250;' 'align: vertical center, horizontal left, wrap on;' 'borders: left thin, right thin, bottom thick;' 'pattern: pattern solid, fore_colour white;') unpaid_fee = xlwt.Style.easyxf( 'font: bold 0, color black, height 250;' 'align: vertical center, horizontal left, wrap on;' 'borders:top_color red, bottom_color red, right_color red, left_color red,\ left thin, right thin, top thin, bottom thin;' 'pattern: pattern solid, fore_colour white;' 'font: color red') selected_fee_list = [] for f in self.browse(cr, uid, ids): if not f.fee_type_list: raise osv.except_osv( ('Please Select Fee'), ('Defaulter Excel Report Fees to be included')) for s in f.fee_type_list: selected_fee_list.append(s.id) #classes = self.pool.get('sms.academiccalendar').browse(cr,uid,41) #loop via classes, for each class there will be 1 sheet collected_classes = [] for f in self.browse(cr, uid, ids): if f.class_id: for cls2 in f.class_id: collected_classes.append(cls2.id) # sql1 = """SELECT id,name from sms_academiccalendar where id in""" +str(collected_classes +"""" ORDER BY name """ # cr.execute(sql1) # classes = cr.fetchall() classes = self.pool.get('sms.academiccalendar').browse( cr, uid, collected_classes) class_ctr = 1 row = 0 for this_class in classes: print("this_class.name", this_class.name) sheet1 = book.add_sheet(str(class_ctr) + " " + str(this_class.class_id.name), cell_overwrite_ok=True) title = this_class.class_id.name class_ctr = class_ctr + 1 _col = (sheet1.col(0)).width = 100 * 20 _col = (sheet1.col(1)).width = 400 * 20 # _col = (sheet1.row(2)).height = 300 * 15 # _col = (sheet1.row(2)).height = 200 * 15 sheet1.write(3, 0, 'Rego NO', header_top) sheet1.write(3, 1, 'Name', header_top) #Find all fee types of this class and arrange in one reow of excel #changes: added subtype in select query sqlfees = """ SELECT smsfee_feetypes.id,smsfee_feetypes.name, CASE WHEN (subtype != 'Monthly_Fee') THEN '01' WHEN (subtype= 'Monthly_Fee') THEN '02' ELSE '00' END AS sequence_no from smsfee_feetypes where smsfee_feetypes.category = '"""+str(f.category)+ """' ORDER BY sequence_no,smsfee_feetypes.name """ # changes: interchanged category.name and seq no cr.execute(sqlfees) feerec = cr.fetchall() col_fee = 2 # this is the column no in sheet for fee header fee_ids_list = [] month_dict_ids = {} adm_dict_ids = {} annual_dict_ids = {} feerec2 = [] for feere in feerec: for id in selected_fee_list: if id == feere[0]: feerec2.append(feere) for fee in feerec2: fee_ids_list.append(fee[0]) print("this_class", this_class, "this_class.session_id", this_class.session_id, "/nthis_class.session_id.id", this_class.session_id.id) sql3 = """SELECT id,name from sms_session_months where session_id = """ + str( this_class.session_id.id ) + """ order by session_year, to_date(name,'Month') """ cr.execute(sql3) months = cr.fetchall() annual_number = 4 #testing git branch 2 if fee[0] == 2: if fee[0] == 2: month_ids_list = [] for this_month in months: if f.developer_mode: ft_name = str(fee[1]) + "\n" + str( this_month[1] ) + "\nmonth_id:" + str( this_month[0]) + "\nfee_id:" + str( fee[0]) else: ft_name = str(fee[1]) + "\n" + str( this_month[1])[:3].upper() + str( this_month[1])[-5:] sheet1.write_merge(r1=0, c1=0, r2=2, c2=11) _col = ( sheet1.row(col_fee)).height = 100 * 10 #cell width for fee type other than months _col = ( sheet1.col(col_fee)).width = 200 * 20 sheet1.write(0, 2, title, header_top) sheet1.write(3, col_fee, ft_name, header_feetypes) month_ids_list.append(this_month[0]) month_dict_ids[this_month[0] + fee[0]] = col_fee col_fee = col_fee + 1 else: annual_dict_ids[fee[0]] = col_fee annual_number = annual_number + 1 sheet1.write_merge(r1=0, c1=0, r2=2, c2=11) _col = (sheet1.row(col_fee)).height = 100 * 10 _col = (sheet1.col(col_fee)).width = 200 * 20 sheet1.write(0, 2, title, header_feetypes) if f.developer_mode: ft_name = str(fee[1]) + "\nfee_id:" + str( fee[0]) else: ft_name = str(fee[1]) sheet1.write(3, col_fee, ft_name, header_feetypes) #popluate dict1 for non mnthly fees col_fee = col_fee + 1 #get students for selected class print "total " + str( fee_ids_list) + " fee ids in fee_ids_list" print("this_class_id ", this_class.id) sql4 = """ SELECT id,registration_no, name,state from sms_student where current_class= """ + str( this_class.id) + """ order by registration_no,name """ cr.execute(sql4) students = cr.fetchall() row = 4 color = True #set column again to start iele left most for this_student in students: color = not color _col = (sheet1.col(1)).width = 200 * 20 _col = (sheet1.col(1)).height = 400 * 20 _col = (sheet1.row(row)).height = 200 * 10 if color: sheet1.write(row, 0, this_student[1], student_grey_rows) sheet1.write(row, 1, this_student[2], student_grey_rows) else: sheet1.write(row, 0, this_student[1], student_white_rows) sheet1.write(row, 1, this_student[2], student_white_rows) # print("student id",this_student[0],"\nmonth ids",month_ids_list ,"\nfee ids",fee_ids_list ) #now loop via the fees dictionaru for this student col_fee = 2 col_month = 25 col_adminiistrative = 13 for fees2 in fee_ids_list: if 2 in selected_fee_list: for month2 in month_ids_list: sql5 = """select id,fee_month,fee_amount,generic_fee_type,state,receipt_no,date_fee_paid from smsfee_studentfee where student_id = """ + str( this_student[0]) + """ and generic_fee_type= """ + str( fees2 ) + """ and fee_month=""" + str(month2) cr.execute(sql5) stdfee = cr.fetchall() print("stdfee", stdfee) for found_fee in stdfee: #print( "generic fee type",fees2,"fee_month",month2,"this_student",this_student[0]) if found_fee[3] == 2: if found_fee[4] == 'fee_paid': if f.developer_mode: label = 'Paid Amount:\n' + str( found_fee[2] ) + "\nmonth_id:" + str( month2 ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3] ) + '\n' + 'Bill No:' + str( found_fee[5] ) + '\n' + 'Date On :\n' + str( found_fee[6]) print 'labellll', label else: label = 'Paid Amount:\n' + str( found_fee[2] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On:\n' + str( found_fee[6]) sheet1.write( row, month_dict_ids[month2 + fees2], label, paid_fee) col_month = col_month + 1 col_fee = col_fee + 1 else: if f.developer_mode: label = 'Fee Amount:\n' + str( found_fee[2] ) + "\nmonth_id:" + str( month2 ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3]) else: label = 'Fee Amount\n' + str( found_fee[2]) sheet1.write( row, month_dict_ids[month2 + fees2], label, unpaid_fee) col_month = col_month + 1 col_fee = col_fee + 1 else: if found_fee[4] == 'fee_paid': if f.developer_mode: label = 'Paid Amount:\n' + str( found_fee[2] ) + "\nmonth_id:" + str( month2 ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3]) else: label = 'Paid Amount:\n' + str( found_fee[2] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On:\n' + str( found_fee[6]) sheet1.write( row, annual_dict_ids[fees2], label, student_white_rows) else: if f.developer_mode: label = 'Fee Amount:\n' + str( found_fee[2] ) + "\nmonth_id:" + str( month2 ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3]) else: label = 'Fee Amount:\n ' + str( found_fee[2]) sheet1.write( row, annual_dict_ids[fees2], label, student_white_rows) # if found_fee[3] !='02': # sheet1.write(row,annual_dict_ids[fees2[0]], label,student_rows) # print("found fee",found_fee ,"\nsearch on ______generic id____",fees2,"\nthis_student.......",this_student[0],"\nmonth",month2) # # label = str(found_fee[2])+"\nmonth_id:"+str(month2)+"\nfee_id:"+str(fees2)+"\nfee_id_genric:"+str(found_fee[3]) # print "label:",label # sheet1.write(row,col_fee, label,student_rows) col_fee = col_fee + 1 else: sql6 = """select id,fee_month,fee_amount,generic_fee_type,state from smsfee_studentfee where student_id = """ + str( this_student[0]) + """ and generic_fee_type= """ + str( fees2) cr.execute(sql6) stdfee = cr.fetchall() for found_fee in stdfee: #print( "generic fee type",fees2,"fee_month",month2,"this_student",this_student[0]) if found_fee[3] == 2: if found_fee[4] == 'fee_paid': if f.developer_mode: label = 'Paid Amount\n' + str( found_fee[2] ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3] ) + '\n' + 'Bill No:' + str( found_fee[5] ) + '\n' + 'Date On :\n' + str( found_fee[6]) else: label = 'Paid Amount\n: ' + str( found_fee[2] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On:\n' + str( found_fee[6]) sheet1.write( row, month_dict_ids[fees2], label, paid_fee) col_month = col_month + 1 col_fee = col_fee + 1 else: if f.developer_mode: label = 'Fee Amount:\n ' + str( found_fee[2] ) + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3]) else: label = 'Fee Amount:\n ' + str( found_fee[2]) sheet1.write( row, month_dict_ids[fees2], label, unpaid_fee) col_month = col_month + 1 col_fee = col_fee + 1 else: if found_fee[4] == 'fee_paid': if f.developer_mode: label = 'Paid Amount:\n' + str( found_fee[2] ) + "\nmonth_id:" + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On:\n' + str( found_fee[6]) else: label = 'Paid Amount:\n ' + str( found_fee[2] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On :' + str( found_fee[6]) sheet1.write( row, annual_dict_ids[fees2], label, student_white_rows) else: if f.developer_mode: label = 'Fee Amount:\n ' + str( found_fee[2] ) + "\nmonth_id:" + "\nfee_id:" + str( fees2 ) + "\nfee_id_genric:" + str( found_fee[3] ) + '\nBill No:' + str( found_fee[5] ) + '\n' + 'Date On:\n' + str( found_fee[6]) else: label = 'Fee Amount:\n ' + str( found_fee[2]) sheet1.write( row, annual_dict_ids[fees2], label, student_white_rows) # if found_fee[3] !='02': # sheet1.write(row,annual_dict_ids[fees2[0]], label,student_rows) # print("found fee",found_fee ,"\nsearch on ______generic id____",fees2,"\nthis_student.......",this_student[0],"\nmonth",month2) # # label = str(found_fee[2])+"\nmonth_id:"+str(month2)+"\nfee_id:"+str(fees2)+"\nfee_id_genric:"+str(found_fee[3]) # print "label:",label # sheet1.write(row,col_fee, label,student_rows) col_fee = col_fee + 1 row = row + 1 print "generating exel" path = os.path.join(os.path.expanduser('~'), 'file.xls') book.save(path)
def _prepare_shipping_invoice_line(self, cr, uid, picking, invoice, context=None): """Prepare the invoice line to add to the shipping costs to the shipping's invoice. :param browse_record picking: the stock picking being invoiced :param browse_record invoice: the stock picking's invoice :return: dict containing the values to create the invoice line, or None to create nothing """ carrier_obj = self.pool.get('delivery.carrier') grid_obj = self.pool.get('delivery.grid') if not picking.carrier_id or \ any(inv_line.product_id.id == picking.carrier_id.product_id.id for inv_line in invoice.invoice_line): return None grid_id = carrier_obj.grid_get(cr, uid, [picking.carrier_id.id], picking.partner_id.id, context=context) if not grid_id: raise osv.except_osv(_('Warning!'), _('The carrier %s (id: %d) has no delivery grid!') \ % (picking.carrier_id.name, picking.carrier_id.id)) quantity = sum([line.product_uom_qty for line in picking.move_lines]) price = grid_obj.get_price_from_picking(cr, uid, grid_id, invoice.amount_untaxed, picking.weight, picking.volume, quantity, context=context) account_id = picking.carrier_id.product_id.property_account_income.id if not account_id: account_id = picking.carrier_id.product_id.categ_id\ .property_account_income_categ.id taxes = picking.carrier_id.product_id.taxes_id partner = picking.partner_id or False if partner: account_id = self.pool.get('account.fiscal.position').map_account( cr, uid, partner.property_account_position, account_id) taxes_ids = self.pool.get('account.fiscal.position').map_tax( cr, uid, partner.property_account_position, taxes) else: taxes_ids = [x.id for x in taxes] return { 'name': picking.carrier_id.name, 'invoice_id': invoice.id, 'uos_id': picking.carrier_id.product_id.uos_id.id, 'product_id': picking.carrier_id.product_id.id, 'account_id': account_id, 'price_unit': price, 'quantity': 1, 'invoice_line_tax_id': [(6, 0, taxes_ids)], }
def _create_refund_to_discount(self, cr, uid, invoice, context=None): """ Crea la nota de credito donde se aplica el descuento comercial, volumen y mezcla """ obj_journal = self.pool.get('account.journal') cur_obj = self.pool.get('res.currency') inv_obj = self.pool.get('account.invoice') inv_line_obj = self.pool.get('account.invoice.line') if context is None: context = {} type_dict = { 'out_invoice': 'out_refund', # Customer Invoice 'in_invoice': 'in_refund', # Supplier Invoice 'out_refund': 'out_invoice', # Customer Refund 'in_refund': 'in_invoice', # Supplier Refund } invoice_data = {} for field in [ 'name', 'reference', 'comment', 'date_due', 'partner_id', 'company_id', 'account_id', 'currency_id', 'payment_term', 'user_id', 'fiscal_position' ]: if invoice._all_columns[field].column._type == 'many2one': invoice_data[field] = invoice[field].id else: invoice_data[ field] = invoice[field] if invoice[field] else False tax_lines = filter(lambda l: l['manual'], invoice.tax_line) tax_lines = inv_obj._refund_cleanup_lines(cr, uid, tax_lines, context=context) # Obtenemos el diario para la nota de debito refund_journal = invoice.journal_id.journal_refund_id # Valida que exista if not refund_journal: raise osv.except_osv( _('Error!'), _("Diario automatico para nota de debito, no configurado, configure el diario sobre diario de credito" )) if refund_journal.type not in ('sale_refund', 'purchase_refund'): raise osv.except_osv( _('Error!'), _("Configurar el diario de nota de debito con: credito de compra o credito de venta" )) date = time.strftime('%Y-%m-%d') invoice_data.update({ 'type': type_dict[invoice['type']], 'date_invoice': date, 'state': 'draft', 'number': False, #'tax_line': tax_lines, 'journal_id': refund_journal.id or False, 'invoice_id': invoice.id }) # Agrega el campo de tipo de nota de credito si lo trae entre los parametros if context.get('default_filter_refund', False): invoice_data['filter_refund'] = context.get( 'default_filter_refund', False) invoice_id = inv_obj.create(cr, uid, invoice_data, context=context) cur = invoice.currency_id # Recorre las lineas de la factura for line in invoice.invoice_line: # Obtiene el monto del descuento de venta por la linea price = line.price_subtotal amount_discount = 0.0 discount_sale = 0.0 # Aplica al subtotal el descuento comercial y al impuesto if line.discount_com > 0: discount_sale = price * (line.discount_com / 100) price = price - discount_sale amount_discount += discount_sale # Aplica al subtotal el descuento de mezcla y al impuesto if line.discount_mez > 0: discount_sale = price * (line.discount_mez / 100) price = price - discount_sale amount_discount += discount_sale # Aplica al subtotal el descuento de volumen y al impuesto if line.discount_vol > 0: discount_sale = price * (line.discount_vol / 100) price = price - discount_sale amount_discount += discount_sale # Valida que el descuento no sea cero if amount_discount == 0.0: continue #tax = line. amount_discount = cur_obj.round(cr, uid, cur, amount_discount) vals = { 'product_id': line.product_id.id or False, 'name': 'Descuento (Comercial: %s %%, Volumen: %s %%, Mezcla: %s %%) - %s ' % (line.discount_com, line.discount_vol, line.discount_mez, line.name), 'quantity': 1, 'uos_id': line.uos_id.id, 'price_unit': amount_discount, #'tax_line': tax_lines, 'account_id': line.account_id.id or False, 'invoice_line_tax_id': [(6, 0, [x.id for x in line.invoice_line_tax_id])], 'invoice_id': invoice_id } #print "****************** vals despues de agregar tax de create refund *************",vals inv_line_obj.create(cr, uid, vals, context=context) # Actualiza los totales de la factura inv_obj.write(cr, uid, [invoice_id], {}, context=context) return invoice_id
def action_employee_confirm(self, cr, uid, ids, context=None): for x in self.browse(cr, uid, ids, context=None): query = {'db': cr.dbname} nm = x.name.name iddd = x.name.id joindate = x.join_date dateOfConf = x.date_of_confirmation url = x.signup_url points_id = x.points_ids joining_date_year = int(x.join_date[:4]) joining_date_month = int(x.join_date[5:7]) joining_date_date = int(x.join_date[8:10]) con_date_year = int(x.date_of_confirmation[:4]) con_date_month = int(x.date_of_confirmation[5:7]) con_date_date = int(x.date_of_confirmation[8:10]) jd_date = str( date(joining_date_year, joining_date_month, joining_date_date)) conDate = str(date(con_date_year, con_date_month, con_date_date)) date_after_3months = str( date(joining_date_year, joining_date_month, joining_date_date) + relativedelta(months=+3)) date_after_6months = str( date(joining_date_year, joining_date_month, joining_date_date) + relativedelta(months=+6)) if (conDate < jd_date) or (conDate < date_after_3months): raise osv.except_osv(_('Warning!'), _("Please Select Appropriate Date")) if not points_id: raise osv.except_osv( _('Warning!'), _("Please click on 'Display' and rate the Employee's performance during his probationary period on a scale of 1 to 5 then click on 'Submit'." )) if x.name.parent_id and x.name.parent_id.user_id: self.message_subscribe_users( cr, uid, [x.id], user_ids=[x.name.parent_id.user_id.id, x.name.hro.id, 52], context=context) search_rating_details = self.pool.get('hr.employee.points').search( cr, uid, [('point_id', '=', ids[0])]) count = 0 for t in self.pool.get('hr.employee.points').browse( cr, uid, search_rating_details): rating = t.rating print t.rating, 'Value of tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt' count = count + 1 if not rating: raise osv.except_osv( _('Warning!'), _("Please give the rating for point no %s") % (count)) emp_user_id = iddd if uid == emp_user_id: raise osv.except_osv( _('Warning!'), _('You cannot validate your own confirmation')) message = _( "<b>Employee confirmation for %s : Submitted to Reporting Manager</b>" ) % (nm) self.message_post(cr, uid, ids, body=message, type='comment', subtype='mt_comment', context=context) return self.write(cr, uid, ids, { 'on_hold_till_date': date_after_6months, 'state': 'Submitted to Mgmt' })
def entry_accept(self, cr, uid, ids, context=None): rec = self.browse(cr, uid, ids[0]) journal_obj = self.pool.get('account.journal') journal_ids = self.pool.get('account.journal').search( cr, uid, [('type', '=', 'purchase')]) if journal_ids == []: raise osv.except_osv( _('Book Configuration Warning !!'), _('Type is purchase book should be created !!')) journal_rec = self.pool.get('account.journal').browse( cr, uid, journal_ids[0]) if rec.state == 'approved': ## Advance code added start ## adjusted_amt = 0.00 balance_amt = 0.00 cus_adv_obj = self.pool.get('kg.subcontract.advance') cus_adv_inv_obj = self.pool.get('ch.foundry.advance.details') for line in rec.line_ids_b: print "line.order_id", line.order_id adv_ids = self.pool.get('kg.subcontract.advance').search( cr, uid, [('fou_wo_id', '=', line.order_id.id)]) print "adv_ids", adv_ids adv_rec = self.pool.get('kg.subcontract.advance').browse( cr, uid, adv_ids[0]) adjusted_amt = adv_rec.adjusted_amt + line.current_adv_amt balance_amt = line.current_adv_amt - adjusted_amt cus_adv_obj.write(cr, uid, line.sub_advance_id.id, { 'adjusted_amt': adjusted_amt, 'balance_amt': balance_amt }) ## Advance code added end ## total_value_amt = 0.00 for line in rec.line_ids: total_value_amt += line.total_value self.write( cr, uid, ids, { 'balance_receivable': rec.amount_total, 'state': 'done', 'done_user_id': uid, 'done_date': time.strftime('%Y-%m-%d %H:%M:%S') }) ## Account Posting Process Start vou_obj = self.pool.get('account.voucher') move_vals = { 'name': rec.name, 'journal_id': journal_rec.id, 'narration': rec.narration, 'source_id': rec.id, 'date': rec.entry_date, 'division_id': rec.division_id.id, 'trans_type': 'FI', } move_id = vou_obj.create_account_move(cr, uid, move_vals) if rec.contractor_id: account_id = rec.contractor_id.property_account_payable.id if not account_id: raise osv.except_osv( _('Contractor Configuration Warning !!'), _('Contractor account should be configured !!')) credit = rec.amount_total debit = 0.00 move_line_vals = { 'move_id': move_id, 'account_id': account_id, 'credit': credit, 'debit': debit, 'journal_id': journal_rec.id, 'date': rec.entry_date, 'name': rec.name, } move_line_id = vou_obj.create_account_move_line( cr, uid, move_line_vals) for expense in rec.line_ids_a: ex_account_id = expense.expense.account_id.id if not ex_account_id: raise osv.except_osv( _('Expense Configuration Warning !!'), _('Expense account should be configured !!')) move_line_vals = { 'move_id': move_id, 'account_id': ex_account_id, 'credit': 0.00, 'debit': expense.amount, 'journal_id': journal_rec.id, 'date': rec.entry_date, 'name': rec.name, } move_line_id = vou_obj.create_account_move_line( cr, uid, move_line_vals) tax_sql = """ select sub_query.acc_col_id,sum(sub_query.debit) as debit from ( select ac_tax.account_collected_id as acc_col_id, sum((line_exp.amount * ac_tax.amount)) as debit from fettling_invoice_expense_taxe line_tax left join ch_fettling_invoice_expense_track line_exp on(line_exp.id=line_tax.invoice_id) left join account_tax ac_tax on(ac_tax.id=line_tax.tax_id) left join kg_fettling_invoice inv on(inv.id=line_exp.header_id) where line_exp.header_id = %s group by 1 union all select ac_tax.account_collected_id as acc_col_id, sum(((inv.amount_untaxed - inv.total_discount) * ac_tax.amount)) as debit from fettling_invoice_taxes line_tax left join kg_fettling_invoice inv on(inv.id=line_tax.invoice_id) left join account_tax ac_tax on(ac_tax.id=line_tax.tax_id) where inv.id = %s group by 1) as sub_query group by 1""" % (rec.id, rec.id) cr.execute(tax_sql) data = cr.dictfetchall() for vals in data: if vals['acc_col_id'] is None: raise osv.except_osv( _('Account Configuration Warning !!'), _('Tax account should be configured !!')) move_line_vals = { 'move_id': move_id, 'account_id': vals['acc_col_id'], 'credit': 0.00, 'debit': vals['debit'], 'journal_id': journal_rec.id, 'date': rec.entry_date, 'name': rec.name, } move_line_id = vou_obj.create_account_move_line( cr, uid, move_line_vals) discount = 0.00 if rec.amount_untaxed > 0: discount = 0.00 if rec.discount > 0: discount = rec.discount else: discount = (total_value_amt * rec.discount_per) / 100 account_ids = self.pool.get('account.account').search( cr, uid, [('code', '=', 'CON INV')]) if account_ids == []: raise osv.except_osv( _('Account Configuration Warning !!'), _('code name is CON INV account should be created !!')) account_rec = self.pool.get('account.account').browse( cr, uid, account_ids[0]) account_id = account_rec.id if not account_id: raise osv.except_osv( _('Invoice Configuration Warning !!'), _('Invoice account should be configured !!')) credit = 0.00 debit = (rec.amount_untaxed + rec.round_off_amt) - discount move_line_vals = { 'move_id': move_id, 'account_id': account_id, 'credit': credit, 'debit': debit, 'journal_id': journal_rec.id, 'date': rec.entry_date, 'name': rec.name, } move_line_id = vou_obj.create_account_move_line( cr, uid, move_line_vals) return True else: pass
def load_document(self, cr, uid, ids, context=None): ''' Load document of new file ''' if context is None: context = {} # Pool used: company_pool = self.pool.get('res.company') uom_pool = self.pool.get('product.uom') picking_pool = self.pool.get('stock.picking') type_pool = self.pool.get('stock.picking.type') product_pool = self.pool.get('product.product') move_pool = self.pool.get('stock.move') quant_pool = self.pool.get('stock.quant') line_pool = self.pool.get('stock.picking.input.file.line') current_proxy = self.browse(cr, uid, ids, context=context)[0] # Parameter: company_id = company_pool.search(cr, uid, [], context=context)[0] state = context.get('import_state', 'load') # passed draft or load now = ('%s' % datetime.now())[:19] type_ids = type_pool.search(cr, uid, [ ('code', '=', 'incoming'), ], context=context) if not type_ids: raise osv.except_osv( _('Error'), _('Need setup of incoming stock.picking.type!'), ) picking_type = type_pool.browse(cr, uid, type_ids, context=context)[0] location_id = picking_type.default_location_src_id.id location_dest_id = picking_type.default_location_dest_id.id # --------------------------------------------------------------------- # Clean situation: # --------------------------------------------------------------------- picking_id = current_proxy.picking_id.id or False partner = current_proxy.partner_id # --------------------------------------------------------------------- # Read file: # --------------------------------------------------------------------- if state == 'draft': filename = os.path.join( os.path.expanduser(partner.electrical_path), current_proxy.name, ) _logger.warning('Reading file: %s' % filename) # Load data depend on partner: origin, rows = self.extract_data_from_supplier_file( cr, uid, partner, filename, context=context) # ----------------------------------------------------------------- # Create new empty pick: # ----------------------------------------------------------------- # Data: data = { 'partner_id': partner.id, 'date': now, 'min_date': now, 'origin': origin, 'picking_type_id': picking_type.id, 'pick_move': 'in', # XXX dept to add! 'pick_state': 'delivered', #'state': 'delivered', # XXX not real! } if picking_id: picking_pool.write(cr, uid, picking_id, data, context=context) else: picking_id = picking_pool.create(cr, uid, data, context=context) # ----------------------------------------------------------------- # Add lines: # ----------------------------------------------------------------- line_ids = [] # File line created error = False for row in rows: # Error management: product_id = row['product_id'] if not product_id: error = True # Create line not linked (done after): line_id = line_pool.create(cr, uid, row, context=context) line_ids.append(line_id) # ----------------------------------------------------------------- # Update document file: # ----------------------------------------------------------------- self.write(cr, uid, current_proxy.id, { 'state': state, 'line_ids': [(6, 0, line_ids)], 'picking_id': picking_id, 'error': error, }, context=context) # --------------------------------------------------------------------- # Load picking: # --------------------------------------------------------------------- else: # load mode picking = current_proxy.picking_id default_account = current_proxy.account_id.id or False for line in sorted(current_proxy.line_ids, key=lambda x: x.sequence): product_id = line.product_id.id uom_id = line.product_id.uom_id.id or 1 if line.create_new: create_code = line.create_code product_ids = product_pool.search( cr, uid, [ ('default_code', '=', create_code), ], context=context) if product_ids: product_id = product_ids[0] else: uom_ids = uom_pool.search( cr, uid, [ '|', ('metel_code', '=', line.uom), ('name', '=', line.uom), ], context=context) uom_id = uom_ids[0] if uom_ids else 1 # ----------------------------------------------------- # Insert also brand code for update with METEL import: # ----------------------------------------------------- #brand_code = create_code[:3].upper() #if '-' in brand_code: # brand_code = False # Internal code product_id = product_pool.create( cr, uid, { # METEL Brand (needed for sync with import proc.) #'metel_brand_code': brand_code, #'metel_producer_code': brand_code, 'name': line.name, 'default_code': create_code, 'standard_price': line.standard_price, 'uom_id': uom_id, 'uos_id': uom_id, 'uom_po_id': uom_id, # TODO extra data? }, context=context) if not product_id: raise osv.except_osv( _('Error'), _('Error no product selected!'), ) # Parameters: product_qty = line.product_qty # TODO Use WK button in load procedure (fast_stock_move)? # ------------------------------------------------------------- # Create stock move: # ------------------------------------------------------------- move_id = move_pool.create( cr, uid, { 'name': line.name, 'product_uom': uom_id, 'picking_id': picking.id, 'picking_type_id': picking_type.id, 'origin': picking.origin, 'product_id': product_id, 'product_uom_qty': product_qty, 'date': now, 'location_id': location_id, 'location_dest_id': location_dest_id, 'state': 'done', 'price_unit': line.standard_price, # Auto pick out data: 'auto_account_out_id': line.account_id.id or default_account }, context=context) # ------------------------------------------------------------- # Create stock quant: # ------------------------------------------------------------- quant_pool.create( cr, uid, { 'stock_move_id': move_id, # Back link 'qty': product_qty, 'cost': line.standard_price, 'location_id': location_dest_id, 'company_id': company_id, 'product_id': product_id, 'in_date': now, #'propagated_from_id' #'package_id' #'lot_id' #'reservation_id' #'owner_id' #'packaging_type_id' #'negative_move_id' }, context=context) # Update product product data: picking_pool.update_standard_price_product(cr, uid, [picking.id], context=context) # Correct error state (if present): self.write(cr, uid, ids, { 'state': state, 'error': False, }, context=context) return True
def do_change_standard_price(self, cr, uid, ids, datas, context=None): """ Changes the Standard Price of Product and creates an account move accordingly. @param datas : dict. contain default datas like new_price, stock_output_account, stock_input_account, stock_journal @param context: A standard dictionary @return: """ location_obj = self.pool.get('stock.location') move_obj = self.pool.get('account.move') move_line_obj = self.pool.get('account.move.line') if context is None: context = {} new_price = datas.get('new_price', 0.0) stock_output_acc = datas.get('stock_output_account', False) stock_input_acc = datas.get('stock_input_account', False) journal_id = datas.get('stock_journal', False) move_ids = [] loc_ids = location_obj.search(cr, uid, [('usage', '=', 'internal')]) for product in self.browse(cr, uid, ids, context=context): if product.valuation != 'real_time': continue account_valuation = product.categ_id.property_stock_valuation_account_id account_valuation_id = account_valuation and account_valuation.id or False if not account_valuation_id: raise osv.except_osv( _('Error!'), _('Specify valuation Account for Product Category: %s.') % (product.categ_id.name)) for location in location_obj.browse(cr, uid, loc_ids, context=context): c = context.copy() c.update({'location': location.id, 'compute_child': False}) # qty_available depends of the location in the context qty = self.read(cr, uid, [product.id], ['qty_available'], context=c)[0]['qty_available'] diff = product.standard_price - new_price if not diff: raise osv.except_osv( _('Error!'), _("No difference between standard price and new price!" )) if qty: company_id = location.company_id and location.company_id.id or False if not company_id: raise osv.except_osv( _('Error!'), _('Please specify company in Location.')) # # Accounting Entries # if not journal_id: journal_id = product.categ_id.property_stock_journal and product.categ_id.property_stock_journal.id or False if not journal_id: raise osv.except_osv(_('Error!'), _('Please define journal '\ 'on the product category: "%s" (id: %d).') % \ (product.categ_id.name, product.categ_id.id,)) move_id = move_obj.create(cr, uid, { 'journal_id': journal_id, 'company_id': company_id }) move_ids.append(move_id) if diff > 0: if not stock_input_acc: stock_input_acc = product.\ property_stock_account_input.id if not stock_input_acc: stock_input_acc = product.categ_id.\ property_stock_account_input_categ.id if not stock_input_acc: raise osv.except_osv(_('Error!'), _('Please define stock input account ' \ 'for this product: "%s" (id: %d).') % \ (product.name, product.id,)) amount_diff = qty * diff move_line_obj.create( cr, uid, { 'name': product.name, 'account_id': stock_input_acc, 'debit': amount_diff, 'move_id': move_id, }) move_line_obj.create( cr, uid, { 'name': product.categ_id.name, 'account_id': account_valuation_id, 'credit': amount_diff, 'move_id': move_id }) elif diff < 0: if not stock_output_acc: stock_output_acc = product.\ property_stock_account_output.id if not stock_output_acc: stock_output_acc = product.categ_id.\ property_stock_account_output_categ.id if not stock_output_acc: raise osv.except_osv(_('Error!'), _('Please define stock output account ' \ 'for this product: "%s" (id: %d).') % \ (product.name, product.id,)) amount_diff = qty * -diff move_line_obj.create( cr, uid, { 'name': product.name, 'account_id': stock_output_acc, 'credit': amount_diff, 'move_id': move_id }) move_line_obj.create( cr, uid, { 'name': product.categ_id.name, 'account_id': account_valuation_id, 'debit': amount_diff, 'move_id': move_id }) self.write(cr, uid, ids, {'standard_price': new_price}) return move_ids
def process_sheet(self, cr, uid, ids, context=None): 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') for slip in self.browse(cr, uid, ids, context=context): line_ids = [] debit_sum = 0.0 credit_sum = 0.0 if not slip.period_id: ctx = dict(context or {}, account_period_prefer_normal=True) search_periods = period_pool.find(cr, uid, slip.date_to, context=ctx) period_id = search_periods[0] else: period_id = slip.period_id.id default_partner_id = slip.employee_id.address_home_id.id name = _('Payslip of %s') % (slip.employee_id.name) move = { 'narration': name, 'date': timenow, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'period_id': period_id, } for line in slip.details_by_salary_rule_category: amt = slip.credit_note and -line.total or line.total if float_is_zero(amt, precision_digits=precision): continue partner_id = line.salary_rule_id.register_id.partner_id and line.salary_rule_id.register_id.partner_id.id or default_partner_id debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name': line.name, 'date': timenow, 'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_debit.type in ('receivable', 'payable')) and partner_id or False, 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt > 0.0 and amt or 0.0, 'credit': amt < 0.0 and -amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_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, }) 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': timenow, 'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_credit.type in ('receivable', 'payable')) and partner_id or False, 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt < 0.0 and -amt or 0.0, 'credit': amt > 0.0 and amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_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, }) 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': timenow, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': 0.0, 'credit': debit_sum - credit_sum, }) line_ids.append(adjust_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': timenow, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': credit_sum - debit_sum, 'credit': 0.0, }) line_ids.append(adjust_debit) move.update({'line_id': line_ids}) move_id = move_pool.create(cr, uid, move, context=context) self.write(cr, uid, [slip.id], { 'move_id': move_id, 'period_id': period_id }, context=context) if slip.journal_id.entry_posted: move_pool.post(cr, uid, [move_id], context=context) return super(hr_payslip, self).process_sheet(cr, uid, [slip.id], context=context)
def create_employee_from_applicant(self, cr, uid, ids, context=None): """ Create an hr.employee from the hr.applicants """ if context is None: context = {} hr_employee = self.pool.get('hr.employee') model_data = self.pool.get('ir.model.data') act_window = self.pool.get('ir.actions.act_window') emp_id = False for applicant in self.browse(cr, uid, ids, context=context): address_id = contact_name = False if applicant.partner_id: address_id = self.pool.get('res.partner').address_get( cr, uid, [applicant.partner_id.id], ['contact'])['contact'] contact_name = self.pool.get('res.partner').name_get( cr, uid, [applicant.partner_id.id])[0][1] if applicant.job_id and (applicant.partner_name or contact_name): applicant.job_id.write({ 'no_of_hired_employee': applicant.job_id.no_of_hired_employee + 1 }) create_ctx = dict(context, mail_broadcast=True) emp_id = hr_employee.create( cr, uid, { 'name': applicant.partner_name or contact_name, 'job_id': applicant.job_id.id, 'address_home_id': address_id, 'department_id': applicant.department_id.id or False, 'address_id': applicant.company_id and applicant.company_id.partner_id and applicant.company_id.partner_id.id or False, 'work_email': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.email or False, 'work_phone': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.phone or False, }, context=create_ctx) self.write(cr, uid, [applicant.id], {'emp_id': emp_id}, context=context) self.pool['hr.job'].message_post( cr, uid, [applicant.job_id.id], body=_('New Employee %s Hired') % applicant.partner_name if applicant.partner_name else applicant.name, subtype="hr_recruitment.mt_job_applicant_hired", context=context) else: raise osv.except_osv( _('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.' )) action_model, action_id = model_data.get_object_reference( cr, uid, 'hr', 'open_view_employee_list') dict_act_window = act_window.read(cr, uid, [action_id], [])[0] if emp_id: dict_act_window['res_id'] = emp_id dict_act_window['view_mode'] = 'form,tree' return dict_act_window
def get_object(self, data): ''' Search all product elements ''' # pool used: company_pool = self.pool.get('res.company') partner_pool = self.pool.get('res.partner') product_pool = self.pool.get('product.product') supplier_pool = self.pool.get('product.supplierinfo') company_ids = company_pool.search(self.cr, self.uid, []) company_proxy = company_pool.browse(self.cr, self.uid, company_ids)[0] # Data parameters: only_with_stock = data.get('only_with_stock', False) # --------------------------------------------------------------------- # Search partner in supplier info: # --------------------------------------------------------------------- partner_id = data.get('partner_id', False) supplierinfo_ids = supplier_pool.search(self.cr, self.uid, [('name', '=', partner_id)]) # --------------------------------------------------------------------- # A. Get template product supplier by partner (supplier under product) # --------------------------------------------------------------------- # XXX DEBUG: debug_f = '/home/administrator/photo/xls/status.txt' pickle_file = '/home/administrator/photo/dicts.pickle' # TODO debug_file = open(debug_f, 'w') product_tmpl_ids = [] for supplier in supplier_pool.browse(self.cr, self.uid, supplierinfo_ids): product_tmpl_ids.append(supplier.product_tmpl_id.id) debug_file.write('\nTemplate selected:\n%s\n' % (product_tmpl_ids)) # --------------------------------------------------------------------- # B. Get product supplier by partner (field: first_supplier_id # --------------------------------------------------------------------- first_supplier_product_ids = product_pool.search( self.cr, self.uid, [('first_supplier_id', '=', partner_id)]) debug_file.write('\nFirst supplier product:\n%s\n' % (first_supplier_product_ids)) # --------------------------------------------------------------------- # Get product form template: # --------------------------------------------------------------------- product_ids = product_pool.search( self.cr, self.uid, [('product_tmpl_id', 'in', product_tmpl_ids)]) debug_file.write('\nProduct ID record (prod>suppl) %s' % (len(product_ids))) # Extend list: product_ids.extend(first_supplier_product_ids) debug_file.write('\nProduct ID record (suppl) %s' % (len(first_supplier_product_ids))) debug_file.write('\nProduct ID record totals %s' % (len(product_ids))) if not product_ids: raise osv.except_osv( _('Report error'), _('No data for this partner (no first suppl. or in product)'), ) products = {} product_mask = company_proxy.product_mask or '%s' # if not configured products_code = [] # For search in other database clean_product_ids = [] for product in product_pool.browse(self.cr, self.uid, product_ids): default_code = product.default_code # or '' products_code.append(product_mask % default_code) if default_code in products: # Jump bouble (TODO use sets not list!!!) continue products[default_code] = product clean_product_ids.append(product.id) product_ids = clean_product_ids # TODO not so clean ... use sets!!! debug_file.write('\nProduct ID record cleaned %s\n' % (len(product_ids))) debug_file.write('\n\nProduct code searched in other DB\n%s' % (products_code, )) # XXX DEBUG debug_file.write('\n\nProduct selected:\n%s' % (product_ids, )) # XXX DEBUG # ---------------------- # Call master procedure: # ---------------------- # MASTER: # products before unloads = {} loads = {} virtual_loads = {} orders = {} partner_pool.stock_movement_inventory_data( self.cr, self.uid, product_ids, False, debug_file, dicts=[ loads, # load document unloads, # unload document orders, # order not delivered virtual_loads, # procurement not received ], context=None) # ===================================================================== # Call remote procedure: # ===================================================================== # REMOTE: # products before remote_unloads = {} remote_loads = {} remote_virtual_loads = {} remote_orders = {} # TODO call XMLRPC procedure: # ERPPEEK CLIENT: try: erp = erppeek.Client( 'http://%s:%s' % (company_proxy.remote_hostname, company_proxy.remote_port), db=company_proxy.remote_name, user=company_proxy.remote_username, password=company_proxy.remote_password, ) except: raise osv.except_osv( _('XMLRPC error'), _( 'Cannot connect to second: %s:%s/%s %s' % ( company_proxy.remote_hostname, company_proxy.remote_port, company_proxy.remote_name, company_proxy.remote_username, ), )) if not erp: raise osv.except_osv(_('XMLRPC error'), _('Cannot connect to second company', )) erp_partner_pool = erp.ResPartner # Pack dicts: dicts = ( remote_loads, # load document remote_unloads, # unload document remote_orders, # order not delivered remote_virtual_loads, # procurement not received ) # Pickle dump dict: pickle_f = open(pickle_file, 'w') pickle.dump(dicts, pickle_f) pickle_f.close() # Close lof file: debug_file.close() both_products = erp_partner_pool.erpeek_stock_movement_inventory_data( products_code, debug_f) # Reopen for append: debug_file = open(debug_f, 'a') debug_file.write('\n\nCode in remote DB: %s\n\n' % (both_products, )) # Pickle load dict: pickle_f = open(pickle_file, 'r') dicts = pickle.load(pickle_f) pickle_f.close() # Unpack dict passed: ( remote_loads, # TODO check if has records (maybe never!) remote_unloads, # TODO check if has records (maybe never!) remote_orders, remote_virtual_loads, # TODO check if has records (maybe never!) ) = dicts # ===================================================================== # --------------------------------------------------------------------- # Transform in iteritems for report: # --------------------------------------------------------------------- res = [] debug_file.write('\n\nInventory:\nCode;Q.\n') for key in sorted(products): default_code = products[key].default_code remote_code = product_mask % default_code inventory = products[key].mx_start_qty or 0.0 # ex inventory_start debug_file.write('%s;%s\n' % (default_code, inventory)) # XXX NOTE remote not used! load = loads.get(default_code, 0.0) + \ remote_loads.get(remote_code, 0.0) unload = unloads.get(default_code, 0.0) + \ remote_unloads.get(remote_code, 0.0) order = orders.get(default_code, 0.0) + \ remote_orders.get(remote_code, 0.0) procurement = virtual_loads.get(default_code, 0.0) + \ remote_virtual_loads.get(remote_code, 0.0) dispo = int(inventory + load - unload) virtual = int(dispo + procurement - order) if only_with_stock and not dispo and not virtual: # If request, jump empry stock product: continue # no quantity res.append(( products[key], int(inventory), int(load), int(unload), int(order), int(procurement), dispo, virtual, )) return res
def data_save(self, cr, uid, ids, context=None): """ This function close account fiscalyear and create entries in new fiscalyear @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of Account fiscalyear close state’s IDs """ def _reconcile_fy_closing(cr, uid, ids, context=None): """ This private function manually do the reconciliation on the account_move_line given as `ids´, and directly through psql. It's necessary to do it this way because the usual `reconcile()´ function on account.move.line object is really resource greedy (not supposed to work on reconciliation between thousands of records) and it does a lot of different computation that are useless in this particular case. """ #check that the reconcilation concern journal entries from only one company cr.execute( 'select distinct(company_id) from account_move_line where id in %s', (tuple(ids), )) if len(cr.fetchall()) > 1: raise osv.except_osv( _('Warning!'), _('The entries to reconcile should belong to the same company.' )) r_id = self.pool.get('account.move.reconcile').create( cr, uid, { 'type': 'auto', 'opening_reconciliation': True }) cr.execute( 'update account_move_line set reconcile_id = %s where id in %s', ( r_id, tuple(ids), )) obj_acc_move_line.invalidate_cache(cr, uid, ['reconcile_id'], ids, context=context) return r_id obj_acc_period = self.pool.get('account.period') obj_acc_fiscalyear = self.pool.get('account.fiscalyear') obj_acc_journal = self.pool.get('account.journal') obj_acc_move = self.pool.get('account.move') obj_acc_move_line = self.pool.get('account.move.line') obj_acc_account = self.pool.get('account.account') obj_acc_journal_period = self.pool.get('account.journal.period') currency_obj = self.pool.get('res.currency') data = self.browse(cr, uid, ids, context=context) if context is None: context = {} fy_id = data[0].fy_id.id cr.execute( "SELECT id FROM account_period WHERE date_stop < (SELECT date_start FROM account_fiscalyear WHERE id = %s)", (str(data[0].fy2_id.id), )) fy_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall())) cr.execute( "SELECT id FROM account_period WHERE date_start > (SELECT date_stop FROM account_fiscalyear WHERE id = %s)", (str(fy_id), )) fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall())) if not fy_period_set or not fy2_period_set: raise osv.except_osv( _('User Error!'), _('The periods to generate opening entries cannot be found.')) period = obj_acc_period.browse(cr, uid, data[0].period_id.id, context=context) new_fyear = obj_acc_fiscalyear.browse(cr, uid, data[0].fy2_id.id, context=context) old_fyear = obj_acc_fiscalyear.browse(cr, uid, fy_id, context=context) new_journal = data[0].journal_id.id new_journal = obj_acc_journal.browse(cr, uid, new_journal, context=context) company_id = new_journal.company_id.id if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id: raise osv.except_osv( _('User Error!'), _('The journal must have default credit and debit account.')) if (not new_journal.centralisation) or new_journal.entry_posted: raise osv.except_osv( _('User Error!'), _('The journal must have centralized counterpart without the Skipping draft state option checked.' )) #delete existing move and move lines if any move_ids = obj_acc_move.search(cr, uid, [('journal_id', '=', new_journal.id), ('period_id', '=', period.id)]) if move_ids: move_line_ids = obj_acc_move_line.search( cr, uid, [('move_id', 'in', move_ids)]) obj_acc_move_line._remove_move_reconcile( cr, uid, move_line_ids, opening_reconciliation=True, context=context) obj_acc_move_line.unlink(cr, uid, move_line_ids, context=context) obj_acc_move.unlink(cr, uid, move_ids, context=context) cr.execute("SELECT id FROM account_fiscalyear WHERE date_stop < %s", (str(new_fyear.date_start), )) result = cr.dictfetchall() fy_ids = ','.join([str(x['id']) for x in result]) query_line = obj_acc_move_line._query_get( cr, uid, obj='account_move_line', context={'fiscalyear': fy_ids}) #create the opening move vals = { 'name': '/', 'ref': '', 'period_id': period.id, 'date': period.date_start, 'journal_id': new_journal.id, } move_id = obj_acc_move.create(cr, uid, vals, context=context) #1. report of the accounts with defferal method == 'unreconciled' cr.execute( ''' SELECT a.id FROM account_account a LEFT JOIN account_account_type t ON (a.user_type = t.id) WHERE a.active AND a.type not in ('view', 'consolidation') AND a.company_id = %s AND t.close_method = %s''', ( company_id, 'unreconciled', )) account_ids = map(lambda x: x[0], cr.fetchall()) if account_ids: cr.execute( ''' INSERT INTO account_move_line ( name, create_uid, create_date, write_uid, write_date, statement_id, journal_id, currency_id, date_maturity, partner_id, blocked, credit, state, debit, ref, account_id, period_id, date, move_id, amount_currency, quantity, product_id, company_id) (SELECT name, create_uid, create_date, write_uid, write_date, statement_id, %s,currency_id, date_maturity, partner_id, blocked, credit, 'draft', debit, ref, account_id, %s, (%s) AS date, %s, amount_currency, quantity, product_id, company_id FROM account_move_line WHERE account_id IN %s AND ''' + query_line + ''' AND reconcile_id IS NULL)''', ( new_journal.id, period.id, period.date_start, move_id, tuple(account_ids), )) #We have also to consider all move_lines that were reconciled #on another fiscal year, and report them too cr.execute( ''' INSERT INTO account_move_line ( name, create_uid, create_date, write_uid, write_date, statement_id, journal_id, currency_id, date_maturity, partner_id, blocked, credit, state, debit, ref, account_id, period_id, date, move_id, amount_currency, quantity, product_id, company_id) (SELECT b.name, b.create_uid, b.create_date, b.write_uid, b.write_date, b.statement_id, %s, b.currency_id, b.date_maturity, b.partner_id, b.blocked, b.credit, 'draft', b.debit, b.ref, b.account_id, %s, (%s) AS date, %s, b.amount_currency, b.quantity, b.product_id, b.company_id FROM account_move_line b WHERE b.account_id IN %s AND b.reconcile_id IS NOT NULL AND b.period_id IN (''' + fy_period_set + ''') AND b.reconcile_id IN (SELECT DISTINCT(reconcile_id) FROM account_move_line a WHERE a.period_id IN (''' + fy2_period_set + ''')))''', ( new_journal.id, period.id, period.date_start, move_id, tuple(account_ids), )) self.invalidate_cache(cr, uid, context=context) #2. report of the accounts with defferal method == 'detail' cr.execute( ''' SELECT a.id FROM account_account a LEFT JOIN account_account_type t ON (a.user_type = t.id) WHERE a.active AND a.type not in ('view', 'consolidation') AND a.company_id = %s AND t.close_method = %s''', ( company_id, 'detail', )) account_ids = map(lambda x: x[0], cr.fetchall()) if account_ids: cr.execute( ''' INSERT INTO account_move_line ( name, create_uid, create_date, write_uid, write_date, statement_id, journal_id, currency_id, date_maturity, partner_id, blocked, credit, state, debit, ref, account_id, period_id, date, move_id, amount_currency, quantity, product_id, company_id) (SELECT name, create_uid, create_date, write_uid, write_date, statement_id, %s,currency_id, date_maturity, partner_id, blocked, credit, 'draft', debit, ref, account_id, %s, (%s) AS date, %s, amount_currency, quantity, product_id, company_id FROM account_move_line WHERE account_id IN %s AND ''' + query_line + ''') ''', ( new_journal.id, period.id, period.date_start, move_id, tuple(account_ids), )) self.invalidate_cache(cr, uid, context=context) #3. report of the accounts with defferal method == 'balance' cr.execute( ''' SELECT a.id FROM account_account a LEFT JOIN account_account_type t ON (a.user_type = t.id) WHERE a.active AND a.type not in ('view', 'consolidation') AND a.company_id = %s AND t.close_method = %s''', ( company_id, 'balance', )) account_ids = map(lambda x: x[0], cr.fetchall()) query_1st_part = """ INSERT INTO account_move_line ( debit, credit, name, date, move_id, journal_id, period_id, account_id, currency_id, amount_currency, company_id, state) VALUES """ query_2nd_part = "" query_2nd_part_args = [] for account in obj_acc_account.browse(cr, uid, account_ids, context={'fiscalyear': fy_id}): company_currency_id = self.pool.get('res.users').browse( cr, uid, uid).company_id.currency_id if not currency_obj.is_zero(cr, uid, company_currency_id, abs(account.balance)): if query_2nd_part: query_2nd_part += ',' query_2nd_part += "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" query_2nd_part_args += ( account.balance > 0 and account.balance or 0.0, account.balance < 0 and -account.balance or 0.0, data[0].report_name, period.date_start, move_id, new_journal.id, period.id, account.id, account.currency_id and account.currency_id.id or None, account.foreign_balance if account.currency_id else 0.0, account.company_id.id, 'draft') if query_2nd_part: cr.execute(query_1st_part + query_2nd_part, tuple(query_2nd_part_args)) self.invalidate_cache(cr, uid, context=context) #validate and centralize the opening move obj_acc_move.validate(cr, uid, [move_id], context=context) #reconcile all the move.line of the opening move ids = obj_acc_move_line.search( cr, uid, [('journal_id', '=', new_journal.id), ('period_id.fiscalyear_id', '=', new_fyear.id)]) if ids: reconcile_id = _reconcile_fy_closing(cr, uid, ids, context=context) #set the creation date of the reconcilation at the first day of the new fiscalyear, in order to have good figures in the aged trial balance self.pool.get('account.move.reconcile').write( cr, uid, [reconcile_id], {'create_date': new_fyear.date_start}, context=context) #create the journal.period object and link it to the old fiscalyear new_period = data[0].period_id.id ids = obj_acc_journal_period.search( cr, uid, [('journal_id', '=', new_journal.id), ('period_id', '=', new_period)]) if not ids: ids = [ obj_acc_journal_period.create( cr, uid, { 'name': (new_journal.name or '') + ':' + (period.code or ''), 'journal_id': new_journal.id, 'period_id': period.id }) ] cr.execute('UPDATE account_fiscalyear ' \ 'SET end_journal_period_id = %s ' \ 'WHERE id = %s', (ids[0], old_fyear.id)) obj_acc_fiscalyear.invalidate_cache(cr, uid, ['end_journal_period_id'], [old_fyear.id], context=context) return {'type': 'ir.actions.act_window_close'}
def gainloss_move_line_create(self, cr, uid, register, move_id, context=None): if context is None: context = {} company = register.company_id ctx = context.copy() ctx.update({'date': register.date}) amount_payin_company_currency = self._convert_amount( cr, uid, register.amount_payin, register.id, context=ctx) # make the rounding as defined in company currency. currency_obj = self.pool.get('res.currency') amount_payin_company_currency = currency_obj.round( cr, uid, company.currency_id, amount_payin_company_currency) paid_amount_in_company_currency = currency_obj.round( cr, uid, company.currency_id, register.paid_amount_in_company_currency) writeoff_amount_local = currency_obj.round( cr, uid, company.currency_id, register.writeoff_amount_local) # amount to post amount = amount_payin_company_currency - paid_amount_in_company_currency + writeoff_amount_local if abs(amount) < 10**-4: return False if not company.income_currency_exchange_account_id or not company.expense_currency_exchange_account_id: raise osv.except_osv( _('Accounting Error !'), _('Gain/Loss Exchange Rate Account is not setup properly! Please see Settings > Configuration > Accounting.' )) move_line = { 'journal_id': register.journal_id.id, 'period_id': register.period_id.id, 'name': register.name or '/', 'account_id': amount > 0 and company.income_currency_exchange_account_id.id or company.expense_currency_exchange_account_id.id, 'move_id': move_id, 'partner_id': register.partner_id.id, 'currency_id': False, #'analytic_account_id': register_brw.account_analytic_id and register_brw.account_analytic_id.id or False, 'amount_currency': 0.0, 'quantity': 1, 'credit': amount > 0 and amount or 0.0, 'debit': amount < 0 and -amount or 0.0, 'date': register.date } move_line_id = self.pool.get('account.move.line').create( cr, uid, move_line) # Assign amount to gainloss_amount field self.write(cr, uid, [register.id], {'gainloss_amount': amount}) return move_line_id
def invoice_cost_create(self, cr, uid, ids, data=None, context=None): analytic_account_obj = self.pool.get('account.analytic.account') account_payment_term_obj = self.pool.get('account.payment.term') invoice_obj = self.pool.get('account.invoice') product_obj = self.pool.get('product.product') invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor') fiscal_pos_obj = self.pool.get('account.fiscal.position') product_uom_obj = self.pool.get('product.uom') invoice_line_obj = self.pool.get('account.invoice.line') invoices = [] if context is None: context = {} if data is None: data = {} journal_types = {} for line in self.pool.get('account.analytic.line').browse( cr, uid, ids, context=context): if line.journal_id.type not in journal_types: journal_types[line.journal_id.type] = set() journal_types[line.journal_id.type].add(line.account_id.id) for journal_type, account_ids in journal_types.items(): for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context): partner = account.partner_id if (not partner) or not (account.pricelist_id): raise osv.except_osv( _('Analytic Account incomplete !'), _('Contract incomplete. Please fill in the Customer and Pricelist fields.' )) date_due = False if partner.property_payment_term: pterm_list = account_payment_term_obj.compute( cr, uid, partner.property_payment_term.id, value=1, date_ref=time.strftime('%Y-%m-%d')) if pterm_list: pterm_list = [line[0] for line in pterm_list] pterm_list.sort() date_due = pterm_list[-1] curr_invoice = { 'name': time.strftime('%d/%m/%Y') + ' - ' + account.name, 'partner_id': account.partner_id.id, 'company_id': account.company_id.id, 'payment_term': partner.property_payment_term.id or False, 'account_id': partner.property_account_receivable.id, 'currency_id': account.pricelist_id.currency_id.id, 'date_due': date_due, 'fiscal_position': account.partner_id.property_account_position.id } context2 = context.copy() context2['lang'] = partner.lang # set company_id in context, so the correct default journal will be selected context2['force_company'] = curr_invoice['company_id'] # set force_company in context so the correct product properties are selected (eg. income account) context2['company_id'] = curr_invoice['company_id'] last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context2) invoices.append(last_invoice) cr.execute( """SELECT product_id, user_id, to_invoice, sum(unit_amount), product_uom_id FROM account_analytic_line as line LEFT JOIN account_analytic_journal journal ON (line.journal_id = journal.id) WHERE account_id = %s AND line.id IN %s AND journal.type = %s AND to_invoice IS NOT NULL GROUP BY product_id, user_id, to_invoice, product_uom_id""", (account.id, tuple(ids), journal_type)) for product_id, user_id, factor_id, qty, uom in cr.fetchall(): if data.get('product'): product_id = data['product'][0] product = product_obj.browse(cr, uid, product_id, context=context2) if not product: raise osv.except_osv( _('Error!'), _('There is no product defined. Please select one or force the product through the wizard.' )) factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2) factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1] if factor.customer_name: factor_name += ' - ' + factor.customer_name ctx = context.copy() ctx.update({'uom': uom}) price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, ctx) general_account = product.property_account_income or product.categ_id.property_account_income_categ if not general_account: raise osv.except_osv( _("Configuration Error!"), _("Please define income account for product '%s'.") % product.name) taxes = product.taxes_id or general_account.tax_ids tax = fiscal_pos_obj.map_tax( cr, uid, account.partner_id.property_account_position, taxes) curr_line = { 'price_unit': price, 'quantity': qty, 'discount': factor.factor, 'invoice_line_tax_id': [(6, 0, tax)], 'invoice_id': last_invoice, 'name': factor_name, 'product_id': product_id, 'invoice_line_tax_id': [(6, 0, tax)], 'uos_id': uom, 'account_id': general_account.id, 'account_analytic_id': account.id, } # # Compute for lines # cr.execute( "SELECT * FROM account_analytic_line WHERE account_id = %s and id IN %s AND product_id=%s and to_invoice=%s ORDER BY account_analytic_line.date", (account.id, tuple(ids), product_id, factor_id)) line_ids = cr.dictfetchall() note = [] for line in line_ids: # set invoice_line_note details = [] if data.get('date', False): details.append(line['date']) if data.get('time', False): if line['product_uom_id']: details.append( "%s %s" % (line['unit_amount'], product_uom_obj.browse( cr, uid, [line['product_uom_id']], context2)[0].name)) else: details.append("%s" % (line['unit_amount'], )) if data.get('name', False): details.append(line['name']) note.append(u' - '.join( map(lambda x: unicode(x) or '', details))) if note: curr_line['name'] += "\n" + ("\n".join( map(lambda x: unicode(x) or '', note))) invoice_line_obj.create(cr, uid, curr_line, context=context) cr.execute( "update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids))) invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context) return invoices
def add_payment(self, cr, uid, order_id, data, context=None): """Create a new payment for the order""" context = dict(context or {}) statement_line_obj = self.pool.get('account.bank.statement.line') property_obj = self.pool.get('ir.property') order = self.browse(cr, uid, order_id, context=context) args = { 'amount': data['amount'], 'date': data.get('payment_date', time.strftime('%Y-%m-%d')), 'name': order.name + ': ' + (data.get('payment_name', '') or ''), 'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner( order.partner_id).id or False, 'check_number': data.get('check_number', ''), } journal_id = data.get('journal', False) statement_id = data.get('statement_id', False) assert journal_id or statement_id, "No statement_id or journal_id passed to the method!" journal = self.pool['account.journal'].browse(cr, uid, journal_id, context=context) # use the company of the journal and not of the current user company_cxt = dict(context, force_company=journal.company_id.id) account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=company_cxt) args['account_id'] = (order.partner_id and order.partner_id.property_account_receivable \ and order.partner_id.property_account_receivable.id) or (account_def and account_def.id) or False if not args['account_id']: if not args['partner_id']: msg = _( 'There is no receivable account defined to make payment.') else: msg = _( 'There is no receivable account defined to make payment for the partner: "%s" (id:%d).' ) % ( order.partner_id.name, order.partner_id.id, ) raise osv.except_osv(_('Configuration Error!'), msg) context.pop('pos_session_id', False) for statement in order.session_id.statement_ids: if statement.id == statement_id: journal_id = statement.journal_id.id break elif statement.journal_id.id == journal_id: statement_id = statement.id break if not statement_id: raise osv.except_osv(_('Error!'), _('You have to open at least one cashbox.')) args.update({ 'statement_id': statement_id, 'pos_statement_id': order_id, 'journal_id': journal_id, 'ref': order.session_id.name, }) statement_line_obj.create(cr, uid, args, context=context) # return {'context':{'treasury_statement_id':statement_id}, 'statement_id':statement_id} # self.localcontext.update({'treasury_statement_id':statement_id}) return statement_id
def unlink(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context=context): if rec.state != 'draft': raise osv.except_osv(_('Warning!'),_('You can only delete draft expenses!')) return super(hr_utilidades, self).unlink(cr, uid, ids, context)
def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context=None): account_obj = self.pool.get('account.account') move_obj = self.pool.get('account.move') move_rec_obj = self.pool.get('account.move.reconcile') partner_obj = self.pool.get('res.partner') currency_obj = self.pool.get('res.currency') lines = self.browse(cr, uid, ids, context=context) unrec_lines = filter(lambda x: not x['reconcile_id'], lines) credit = debit = 0.0 currency = 0.0 account_id = False partner_id = False if context is None: context = {} company_list = [] for line in lines: if company_list and line.company_id.id not in company_list: raise osv.except_osv( _('Warning!'), _('To reconcile the entries company ' 'should be the same for all entries.')) company_list.append(line.company_id.id) for line in unrec_lines: if line.state != 'valid': raise osv.except_osv( _('Error!'), _('Entry "%s" is not valid !') % line.name) credit += line['credit'] debit += line['debit'] currency += line['amount_currency'] or 0.0 account_id = line['account_id']['id'] partner_id = \ (line['partner_id'] and line['partner_id']['id']) or False writeoff = debit - credit # Ifdate_p in context => take this date if 'date_p' in context and context['date_p']: date = context['date_p'] else: date = time.strftime('%Y-%m-%d') cr.execute('SELECT account_id, reconcile_id ' 'FROM account_move_line ' 'WHERE id IN %s ' 'GROUP BY account_id,reconcile_id', (tuple(ids), )) r = cr.fetchall() # kittiu: remove this to cancle KV with reconcilable account > 1 # if len(r) != 1: # raise osv.except_osv(_('Error'), # _('Entries are not of the same account or already reconciled ! ')) if not unrec_lines: raise osv.except_osv( _('Error!'), _('Entry is already reconciled.')) account = account_obj.browse(cr, uid, account_id, context=context) if not account.reconcile: raise osv.except_osv( _('Error'), _('The account is not defined to be reconciled !')) if r[0][1] is not None: raise osv.except_osv( _('Error!'), _('Some entries are already reconciled.')) is_zero_1 = currency_obj.is_zero( cr, uid, account.company_id.currency_id, writeoff) is_zero_2 = currency_obj.is_zero( cr, uid, account.currency_id, currency) if (not is_zero_1) or (account.currency_id and (not is_zero_2)): # DO NOT FORWARD PORT if not writeoff_acc_id: company = account.company_id if writeoff > 0: writeoff_acc_id = \ company.expense_currency_exchange_account_id.id else: writeoff_acc_id = \ company.income_currency_exchange_account_id.id if not writeoff_acc_id: raise osv.except_osv( _('Warning!'), _('You have to provide an account for the ' 'write off/exchange difference entry.')) if writeoff > 0: debit = writeoff credit = 0.0 self_credit = writeoff self_debit = 0.0 else: debit = 0.0 credit = -writeoff self_credit = 0.0 self_debit = -writeoff # If comment exist in context, take it if 'comment' in context and context['comment']: libelle = context['comment'] else: libelle = _('Write-Off') cur_obj = self.pool.get('res.currency') cur_id = False amount_currency_writeoff = 0.0 if context.get('company_currency_id', False) != \ context.get('currency_id', False): cur_id = context.get('currency_id', False) for line in unrec_lines: if line.currency_id and line.currency_id.id == \ context.get('currency_id', False): amount_currency_writeoff += line.amount_currency else: tmp_amount = cur_obj.compute( cr, uid, line.account_id.company_id.currency_id.id, context.get('currency_id', False), abs(line.debit-line.credit), context={'date': line.date}) amount_currency_writeoff += \ (line.debit > 0) and tmp_amount or -tmp_amount writeoff_lines = [ (0, 0, { 'name': libelle, 'debit': self_debit, 'credit': self_credit, 'account_id': account_id, 'date': date, 'partner_id': partner_id, 'currency_id': cur_id or (account.currency_id.id or False), 'amount_currency': (amount_currency_writeoff and -1 * amount_currency_writeoff or (account.currency_id.id and -1 * currency or 0.0)) }), (0, 0, { 'name': libelle, 'debit': debit, 'credit': credit, 'account_id': writeoff_acc_id, 'analytic_account_id': context.get('analytic_id', False), 'date': date, 'partner_id': partner_id, 'currency_id': cur_id or (account.currency_id.id or False), 'amount_currency': (amount_currency_writeoff and amount_currency_writeoff or (account.currency_id.id and currency or 0.0)) }) ] # DO NOT FORWARD PORT # In some exceptional situations (partial payment from a bank # statement in foreign # currency), a write-off can be introduced at the very last moment # due to currency # conversion. We record it on the bank statement account move. if context.get('bs_move_id'): writeoff_move_id = context['bs_move_id'] for l in writeoff_lines: self.create(cr, uid, dict(l[2], move_id=writeoff_move_id), dict(context, novalidate=True)) if not move_obj.validate(cr, uid, writeoff_move_id, context=context): raise osv.except_osv( _('Error!'), _('You cannot validate a non-balanced entry.')) else: writeoff_move_id = move_obj.create(cr, uid, { 'period_id': writeoff_period_id, 'journal_id': writeoff_journal_id, 'date': date, 'state': 'draft', 'line_id': writeoff_lines }) writeoff_line_ids = self.search( cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)]) if account_id == writeoff_acc_id: writeoff_line_ids = [writeoff_line_ids[1]] ids += writeoff_line_ids # marking the lines as reconciled does not change # their validity, so there is no need # to revalidate their moves completely. reconcile_context = dict(context, novalidate=True) r_id = move_rec_obj.create(cr, uid, {'type': type}, context=reconcile_context) self.write(cr, uid, ids, {'reconcile_id': r_id, 'reconcile_partial_id': False}, context=reconcile_context) # the id of the move.reconcile is written # in the move.line (self) by the create method above # because of the way the line_id are defined: (4, x, False) for id in ids: workflow.trg_trigger(uid, 'account.move.line', id, cr) if lines and lines[0]: partner_id = lines[0].partner_id and \ lines[0].partner_id.id or False if partner_id and not partner_obj.has_something_to_reconcile( cr, uid, partner_id, context=context): partner_obj.mark_as_reconciled(cr, uid, [partner_id], context=context) return r_id
def price_calculation(self, cr, uid, ids, context=None): ''' This method puts the right price on the stock move, adapts the price on the product when necessary and creates the necessary stock move matchings It returns a list of tuples with (move_id, match_id) which is used for generating the accounting entries when FIFO/LIFO ''' product_obj = self.pool.get('product.product') currency_obj = self.pool.get('res.currency') matching_obj = self.pool.get('stock.move.matching') uom_obj = self.pool.get('product.uom') product_avail = {} res = {} for move in self.browse(cr, uid, ids, context=context): # Initialize variables res[move.id] = [] move_qty = move.product_qty move_uom = move.product_uom.id company_id = move.company_id.id ctx = context.copy() user = self.pool.get('res.users').browse(cr, uid, uid, context=context) ctx['force_company'] = move.company_id.id product = product_obj.browse(cr, uid, move.product_id.id, context=ctx) cost_method = product.cost_method product_uom_qty = uom_obj._compute_qty(cr, uid, move_uom, move_qty, product.uom_id.id, round=False) if not product.id in product_avail: product_avail[product.id] = product.qty_available # Check if out -> do stock move matchings and if fifo/lifo -> update price # only update the cost price on the product form on stock moves of type == 'out' because if a valuation has to be made without PO, # for inventories for example we want to use the last value used for an outgoing move if move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal': fifo = (cost_method != 'lifo') tuples = product_obj.get_stock_matchings_fifolifo(cr, uid, [product.id], move_qty, fifo, move_uom, move.company_id.currency_id.id, context=ctx) #TODO Would be better to use price_currency_id for migration? price_amount = 0.0 amount = 0.0 #Write stock matchings for match in tuples: matchvals = {'move_in_id': match[0], 'qty': match[1], 'move_out_id': move.id} match_id = matching_obj.create(cr, uid, matchvals, context=context) res[move.id].append(match_id) price_amount += match[1] * match[2] amount += match[1] #Write price on out move if product_avail[product.id] >= product_uom_qty and product.cost_method in ['fifo', 'lifo']: if amount > 0: self.write(cr, uid, move.id, {'price_unit': price_amount / amount}, context=context) product_obj.write(cr, uid, product.id, {'standard_price': price_amount / product_uom_qty}, context=ctx) else: raise osv.except_osv(_('Error'), _("Something went wrong finding stock moves ") + str(tuples) + str(self.search(cr, uid, [('company_id','=', company_id), ('qty_remaining', '>', 0), ('state', '=', 'done'), ('location_id.usage', '!=', 'internal'), ('location_dest_id.usage', '=', 'internal'), ('product_id', '=', product.id)], order = 'date, id', context=context)) + str(move_qty) + str(move_uom) + str(move.company_id.currency_id.id)) else: new_price = uom_obj._compute_price(cr, uid, product.uom_id.id, product.standard_price, move_uom) self.write(cr, uid, move.id, {'price_unit': new_price}, context=ctx) #Adjust product_avail when not average and move returned from if (not move.move_returned_from or product.cost_method != 'average'): product_avail[product.id] -= product_uom_qty #Check if in => if price 0.0, take standard price / Update price when average price and price on move != standard price if move.location_id.usage != 'internal' and move.location_dest_id.usage == 'internal': if move.price_unit == 0.0: new_price = uom_obj._compute_price(cr, uid, product.uom_id.id, product.standard_price, move_uom) self.write(cr, uid, move.id, {'price_unit': new_price}, context=ctx) elif product.cost_method == 'average': move_product_price = uom_obj._compute_price(cr, uid, move_uom, move.price_unit, product.uom_id.id) if product_avail[product.id] > 0.0: amount_unit = product.standard_price new_std_price = ((amount_unit * product_avail[product.id])\ + (move_product_price * product_uom_qty))/(product_avail[product.id] + product_uom_qty) else: new_std_price = move_product_price product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price}, context=ctx) # Should create the stock move matchings for previous outs for the negative stock that can be matched with is in if product_avail[product.id] < 0.0: resneg = self._generate_negative_stock_matchings(cr, uid, [move.id], product, context=ctx) res[move.id] += resneg product_avail[product.id] += product_uom_qty #The return of average products at average price (could be made optional) if move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal' and cost_method == 'average' and move.move_returned_from: move_orig = move.move_returned_from new_price = uom_obj._compute_price(cr, uid, move_orig.product_uom, move_orig.price_unit, product.uom_id.id) if (product_avail[product.id]- product_uom_qty) >= 0.0: amount_unit = product.standard_price new_std_price = ((amount_unit * product_avail[product.id])\ - (new_price * product_uom_qty))/(product_avail[product.id] - product_uom_qty) self.write(cr, uid, [move.id],{'price_unit': move_orig.price_unit,}) product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price}, context=ctx) product_avail[product.id] -= product_uom_qty return res
def write(self, cr, user, ids, vals, context={}): if 'report_sxw_content_data' in vals: if vals['report_sxw_content_data']: try: base64.decodestring(vals['report_sxw_content_data']) except binascii.Error: vals['report_sxw_content_data'] = False if type(ids) == list: ids = ids[0] record = self.browse(cr, user, ids) #if context and 'model' in vals and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['model'])]): # raise osv.except_osv(_('Object model is not correct !'),_('Please check "Object" field !') ) if vals.get('report_type', record.report_type) == 'aeroo': if vals.get('report_wizard') and vals.get('active', record.active) and \ (record.replace_report_id and vals.get('replace_report_id', True) or not record.replace_report_id): vals['wizard_id'] = self._set_report_wizard(cr, user, ids, ids, linked_report_id=vals.get('replace_report_id'), context=context) record.report_wizard = True record.wizard_id = vals['wizard_id'] elif 'report_wizard' in vals and not vals['report_wizard'] and record.report_wizard: self._unset_report_wizard(cr, user, ids, context) vals['wizard_id'] = False record.report_wizard = False record.wizard_id = False parser = rml_parse if vals.get('parser_state', False) == 'loc': parser = self.load_from_file(vals.get('parser_loc', False) or record.parser_loc, cr.dbname, record.id) or parser elif vals.get('parser_state', False) == 'def': parser = self.load_from_source("from report import report_sxw\n" + ( vals.get('parser_loc', False) or record.parser_def or '')) or parser elif vals.get('parser_state', False) == 'default': parser = rml_parse elif record.parser_state == 'loc': parser = self.load_from_file(record.parser_loc, cr.dbname, record.id) or parser elif record.parser_state == 'def': parser = self.load_from_source("from report import report_sxw\n" + record.parser_def) or parser elif record.parser_state == 'default': parser = rml_parse if vals.get('parser_loc', False): parser = self.load_from_file(vals['parser_loc'], cr.dbname, record.id) or parser elif vals.get('parser_def', False): parser = self.load_from_source("from report import report_sxw\n" + vals['parser_def']) or parser if vals.get('report_name', False) and vals['report_name'] != record.report_name: self.delete_report_service(record.report_name) report_name = vals['report_name'] else: self.delete_report_service(record.report_name) report_name = record.report_name ##### Link / unlink inherited report ##### link_vals = {} now_unlinked = False if 'replace_report_id' in vals and vals.get('active', record.active): if vals['replace_report_id']: if record.replace_report_id and vals['replace_report_id'] != record.replace_report_id.id: ctx = context.copy() ctx['keep_wizard'] = True # keep window action for wizard, if only inherit report changed link_vals.update(self.unlink_inherit_report(cr, user, ids, ctx)) now_unlinked = True link_vals.update( self.link_inherit_report(cr, user, record, new_replace_report_id=vals['replace_report_id'], context=context)) self.register_report(cr, report_name, vals.get('model', record.model), vals.get('report_rml', record.report_rml), parser) else: link_vals.update(self.unlink_inherit_report(cr, user, ids, context=context)) now_unlinked = True ########################################## try: if vals.get('active', record.active): self.register_report(cr, report_name, vals.get('model', record.model), vals.get('report_rml', record.report_rml), parser) if not record.active and vals.get('replace_report_id', record.replace_report_id): link_vals.update(self.link_inherit_report(cr, user, record, new_replace_report_id=vals.get('replace_report_id', False), context=context)) elif not vals.get('active', record.active): self.unregister_report(cr, report_name) if not now_unlinked: link_vals.update(self.unlink_inherit_report(cr, user, ids, context=context)) except Exception, e: print e raise osv.except_osv(_('Report registration error !'), _('Report was not registered in system !')) vals.update(link_vals) res = super(report_xml, self).write(cr, user, ids, vals, context) return res
def onchange_employee(self, cr, uid, ids, employee_id, context=None): res = { 'value': { 'job_id': False, 'department_id': False, 'joining_date': False, 'confirmation_status': False, 'resign_id': False, 'capture_date': False, 'last_date': False, 'nodues_id': False, } } joining_date = '' last_date = '' if employee_id: exit_ids = self.search(cr, uid, [('employee_id', '=', employee_id)], context=context) if len(exit_ids) > 0: raise osv.except_osv( _('Warning!'), _('Full & Final has already been in progress/done for this employee.' )) ee = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context) if ee: notice_period_days = int(ee.notice) if notice_period_days > 0: res['value']['np_required'] = 'yes' res['value']['job_id'] = ee.job_id.id res['value']['department_id'] = ee.department_id.id res['value']['dob'] = ee.birthday res['value']['division_id'] = ee.division.id res['value']['location_id'] = ee.office_location.id res['value']['gender'] = ee.gender res['value']['mobile_no'] = ee.mobile_phone joining_date = res['value']['joining_date'] = ee.joining_date res['value'][ 'confirmation_status'] = ee.confirmation_status.title() emp_ff_leave_obj = self.pool.get('ids.employee.ff.leave') leave_ids = emp_ff_leave_obj._get_leave_details(cr, uid, ids, employee_id, context=None) res['value']['leave_detail_ids'] = leave_ids if ee.service_agreement == True: res['value']['service_agreement'] = 'yes' res['value']['start_date'] = ee.agreement_start_date res['value']['end_date'] = ee.agreement_end_date else: res['value']['service_agreement'] = 'no' emp_sep_id = self.pool.get('ids.hr.employee.separation').search( cr, uid, [('employee_id', '=', employee_id), ('state', '=', 'done')], context=context) if emp_sep_id: es = self.pool.get('ids.hr.employee.separation').browse( cr, uid, emp_sep_id[0], context=context) if es: res['value']['resign_id'] = es.id res['value']['capture_date'] = es.capture_date last_date = res['value']['last_date'] = es.last_date emp_contract = self.pool.get('hr.contract').search( cr, uid, [('employee_id', '=', employee_id)], context=context) if emp_contract: ec = self.pool.get('hr.contract').browse(cr, uid, emp_contract[0], context=context) if ec: res['value']['last_wages'] = ec.basic emp_nodues_id = self.pool.get('emp.no.dues').search( cr, uid, [('employee_id', '=', employee_id)], context=context) if emp_nodues_id: en = self.pool.get('emp.no.dues').browse(cr, uid, emp_nodues_id[0], context=context) if en: res['value']['nodues_id'] = en.id res['value']['icard_return'] = en.icard_return res['value']['access_card_return'] = en.access_card_return res['value']['keys_return'] = en.keys_return res['value']['headphone_return'] = en.headphone_return res['value']['name_delete'] = en.name_delete res['value']['canteen_dues'] = en.canteen_dues res['value']['library_book'] = en.library_book res['value']['remarks'] = en.remarks res['value'][ 'submitted_by_facility'] = en.submitted_by_facility res['value'][ 'submitted_on_facility'] = en.submitted_on_facility res['value']['email_control'] = en.email_control res['value']['email_remarks'] = en.email_remarks res['value']['internet_control'] = en.internet_control res['value']['internet_remarks'] = en.internet_remarks res['value']['remote_control'] = en.remote_control res['value']['remote_remarks'] = en.remote_remarks res['value'][ 'software_requirement'] = en.software_requirement res['value']['software_remarks'] = en.software_remarks res['value']['application_share'] = en.application_share res['value'][ 'application_remarks'] = en.application_remarks res['value']['data_backup'] = en.data_backup res['value'][ 'data_backup_remarks'] = en.data_backup_remarks res['value']['handover_takeover'] = en.handover_takeover res['value']['handover_remarks'] = en.handover_remarks res['value'][ 'submitted_by_operation'] = en.submitted_by_operation res['value'][ 'submitted_on_operation'] = en.submitted_on_operation res['value']['login_name_tech'] = en.login_name_tech res['value']['login_name_disable'] = en.login_name_disable res['value']['login_remarks_tech'] = en.login_remarks_tech res['value'][ 'allocation_it_asset'] = en.allocation_it_asset res['value']['it_assets_disable'] = en.it_assets_disable res['value']['asset_remarks_tech'] = en.asset_remarks_tech res['value']['email_id_tech'] = en.email_id_tech res['value']['email_id_disable'] = en.email_id_disable res['value']['email_remarks_tech'] = en.email_remarks_tech res['value'][ 'internet_control_tech'] = en.internet_control_tech res['value']['internal_disable'] = en.internal_disable res['value'][ 'internet_remarks_tech'] = en.internet_remarks_tech res['value']['backup_setup_tech'] = en.backup_setup_tech res['value'][ 'backup_setup_disable'] = en.backup_setup_disable res['value'][ 'backup_remarks_tech'] = en.backup_remarks_tech res['value'][ 'software_requirement_tech'] = en.software_requirement_tech res['value']['software_disable'] = en.software_disable res['value'][ 'software_remarks_tech'] = en.software_remarks_tech res['value'][ 'application_share_tech'] = en.application_share_tech res['value'][ 'appliaction_share_disable'] = en.appliaction_share_disable res['value'][ 'application_remarks_tech'] = en.application_remarks_tech res['value'][ 'submitted_by_technical'] = en.submitted_by_technical res['value'][ 'submitted_on_technical'] = en.submitted_on_technical if (joining_date and last_date): res['value'][ 'gratuity_years'] = self._calculate_years_between_two_dates( cr, uid, ids, joining_date, last_date, context=None)[1] res['value'][ 'service_period'] = self._calculate_years_between_two_dates( cr, uid, ids, joining_date, last_date, context=None)[0] return res
def unlink(self, cr, uid, ids, context=None): for rpt in self.read(cr, uid, ids, ['state'], context=context): if rpt['state'] not in ('draft','cancel'): raise osv.except_osv(_('Error'),_('Only order with Draft/Cancel state can be delete!')) return super(hr_rpt_attend_emp_day, self).unlink(cr, uid, ids, context=context)
def create_financial_voucher(self, cr, uid, ids, context=None): """ Method that transfers the cost of maintenance to the voucher and creates a ratification for car's maintenance request . @return: Dictionary of values """ names = '' voucher_obj = self.pool.get('account.voucher') voucher_line_obj = self.pool.get('account.voucher.line') for request in self.browse(cr, uid, ids, context=context): for pro in request.faults: names += pro.name + '\n' notes = _( "Car Maintenance : %s \nMaintenance Type: %s.\nSpare Part: %s." ) % (request.name, request.maintenance_type, names) config_id = self.pool.get('admin_affairs.account').search( cr, uid, [('company_id', '=', request.company_id.id)], context=context) if not config_id: raise osv.except_osv( _('Invalid action !'), _('Please insert the Company Configruation Account For Car Maintenance' )) account_config = self.pool.get('admin_affairs.account').browse( cr, uid, config_id[0]) # Creating Voucher / Ratitication voucher_id = voucher_obj.create( cr, uid, { 'amount': request.total_amount, 'type': 'ratification', 'date': time.strftime('%Y-%m-%d'), 'partner_id': request.partner_id.id, 'department_id': request.department_id.id, 'journal_id': account_config.maintenance_jorunal_id.id, 'state': 'draft', 'notes': request.notes, 'narration': notes, }, context=context) voucher_line_dict = { 'voucher_id': voucher_id, 'account_id': account_config.maintenance_account_id.id, 'account_analytic_id': account_config.maintenance_analytic_id.id or request.department_id.analytic_account_id.id, 'amount': request.total_amount, 'type': 'dr', 'name': request.department_id.name, } voucher_line_obj.create(cr, uid, voucher_line_dict, context=context) #################### update workflow state############### voucher_state = 'draft' if record.company_id.affairs_voucher_state: voucher_state = record.company_id.affairs_voucher_state if voucher_id: wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, 'account.voucher', voucher_id, voucher_state, cr) voucher_obj.write( cr, uid, voucher_id, { 'type': 'ratification', 'ratification': True, 'state': voucher_state }, context) # Selecting Voucher Number / Refernece #voucher_number = voucher_obj.browse(cr,uid,voucher_id,context=context).number self.write(cr, uid, request.id, {'voucher_no': voucher_id}, context=context) return True
def send_notification(self, cr, uid, ids, signal, context=None): for reg in self.browse(cr, SUPERUSER_ID, ids): model_obj = openerp.pooler.get_pool(cr.dbname).get('ir.model.data') groups = { 'wait': 'group_director_of_hr', 'assigned': 'base.group_user', 'assigned2': 'base.group_user', 'check': 'base.group_user', 'done': 'base.group_user', 'cancel': 'base.group_user', 'created_reg': 'base.group_user', 'send_pomak': 'group_regulation_president', 'to_allow': 'base.group_user', 'to_reject': 'base.group_user', } states = { 'wait': u'Шийд хүлээсэн', 'assigned': u'"Шийд хүлээсэн" → "Хариуцагч томилогдсон" төлөвт шилжсэн', 'assigned2': u'"Хийгдэж байна" → "Хариуцагчтай(II шат) томилогдсон" төлөвт шилжсэн', 'check': u'"Хийгдэж байна or Хйигдэж байна(II)" → "БХГ-ийн захиралд илгээгдсэн" төлөвт шилжсэн', 'done': u'"БХГ-ийн захиралд илгээгдсэн" → "Дууссан" төлөвт шилжсэн', 'cancel': u'Цуцлагдсан', 'created_reg': u'"Дууссан" → "Тушаал үүссэн" төлөвт шилжсэн', 'send_pomak': u'"Дууссан" → "Ерөнхийлөгчид илгээсэн" төлөвт шилжсэн', 'to_allow': u'"Ерөнхийлөгчид илгээсэн" → "Ерөнхийлөгч зөвшөөрсөн" төлөвт шилжсэн', 'to_reject': u'"Ерөнхийлөгчид илгээсэн" → "Ерөнхийлөгч татгалзсан" төлөвт шилжсэн', } group_user_ids = [] notif_groups = [] sel_user_ids = [] if reg.state == 'draft': notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', 'regulation_user') template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation', 'mak_hr_email_template_to_assigned')[1] else: if signal in ['assigned','done','to_allow','to_reject']: # notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', # groups[signal]) template_id = \ self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation', 'reg_email_template_to_user')[1] group_user_ids = self.pool.get('res.users').search(cr, SUPERUSER_ID, [('id', '=', reg.assigned_id.id)]) # notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', # 'regulation_user') # print 'NOTIFF GROUPS \n\n',notif_groups,group_user_ids elif signal in ['assigned2','done','to_allow','to_reject']: # notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', # groups[signal]) template_id = \ self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation', 'reg_email_template_to_user')[1] group_user_ids = self.pool.get('res.users').search(cr, SUPERUSER_ID, [('id', '=', reg.assigned_id2.id)]) elif signal in ['check','to_allow','to_reject']: notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', 'regulation_user') template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation', 'reg_email_template_to_user')[1] elif signal in ['send_pomak']: notif_groups = model_obj.get_object_reference(cr, SUPERUSER_ID, 'mak_regulation', 'regulation_president') template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation', 'reg_email_template_to_pomak')[1] if notif_groups: sel_user_ids = self.pool.get('res.users').search(cr, SUPERUSER_ID, [('groups_id', 'in', [notif_groups[1]])]) domain = self.pool.get("ir.config_parameter").get_param(cr, uid, "mail.catchall.domain", context=None) data = { 'doc_name': reg.doc_name, 'department': reg.department_id.name, 'base_url': self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'), 'action_id': self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mak_regulation','action_mak_regulation_window')[1], 'sequence_id': reg.sequence_id, 'id': reg.id, 'db_name': request.session.db, 'state': states[signal], 'date_deadline': reg.date_deadline, 'doc_type': reg.type_doc, 'date': reg.date, 'last_name': reg.employee_id.last_name, 'department_id': reg.employee_id.department_id.name, 'job_id': reg.employee_id.job_id.name, 'num_received_document': reg.num_received_document, 'employee_id': reg.employee_id.name, 'sender': self.pool.get('res.users').browse(cr, uid, uid).name, } if not group_user_ids: group_user_ids = self.pool.get('res.users').search(cr, SUPERUSER_ID, [('id', 'in', sel_user_ids)]) if group_user_ids: # group_user_ids = self.pool.get('res.users').search(cr, SUPERUSER_ID, [('id', 'in', sel_user_ids)]) users = self.pool.get('res.users').browse(cr, uid, group_user_ids) user_emails = [] for user in users: user_emails.append(user.login) self.pool.get('email.template').send_mail(cr, uid, template_id, user.id, force_send=True, context=data) email = u'' + states[signal] + u'.\n Дараах хэрэглэгч рүү имэйл илгээгдэв : ' + ( '<b>' + ('</b>, <b>'.join(user_emails)) + '</b>') self.pool.get('mak.regulation').message_post(cr, uid, ids, body=email, context=None) else: raise osv.except_osv(_('Warning!'), _(u'Хүлээн авах хүн олдсонгүй! Та хариуцагчийг бүртгэнэ үү!')) return True
def export_woocommerce_customers(self): active_ids = self.env.context.get('active_ids') # default_email = self.env.user.company_id.email # no podemos usar default email porque nos e puede duplicar el dato de email cust_n = 0 cust_records = '' cust_records = self.env['res.partner'].search([('id','in',active_ids)]) woocommerce = self.woocommerce_export_api_config() for cust in cust_records: # rechazamos clientes sin NIF porque es su username if not cust.vat: continue mapping_rec = self.env['channel.partner.mappings'].search([('odoo_partner','=',cust.id),('channel_id.id','=',self.id)]) if not mapping_rec: # para cliente con RE hay que asociar el role creado en WOC de cliente_re if cust.property_account_position and 'Recargo' in str(cust.property_account_position.name): rol = 'cliente_re' else: rol = 'customer' # para cliente sin correo uno inventado con su [email protected] if cust.email: if len(cust.email) ==0: cust_mail = str(cust.id) + "@ex.com" else: cust_mail = cust.email else: cust_mail = str(cust.id) + "@ex.com" if self.api_version == 'legacyv3': cust_value_dict = {'customer':{ "email": cust_mail, "first_name": cust.name, "username": str(cust.vat)[2:], "password": str(cust.ref)[-4:], "role":rol, "billing_address":{ "first_name": cust.name, "email": cust_mail, }, } } else: cust_value_dict = { "email": cust_mail, "first_name": cust.name, "username": str(cust.vat)[2:], "password": str(cust.ref)[-4:], "role":rol, "billing":{ "first_name": cust.name, "email": cust_mail, }, } _logger.error('########### Valor de cust_value_dict en wooc export customers: %s', cust_value_dict) return_value_dict = woocommerce.post( 'customers', cust_value_dict ).json() _logger.error('########### Valor de return_value_dict en wooc export customers: %s', return_value_dict) if return_value_dict.has_key('errors'): error = return_value_dict['errors'] raise osv.except_osv(_('Error'),_('Error in Creating customers '+str(error[0]['message']))) else: if self.api_version == 'wpapi' and return_value_dict.has_key('message'): raise osv.except_osv(_('Error'),_('Error in Creating customers '+return_value_dict['message'])) if self.api_version == 'legacyv3': result = return_value_dict['customer'] else: result = return_value_dict _logger.error('########### Valor de result en wooc export customers: %s', result) cust_n += 1 mapping_dict={ 'channel_id' : self.id, 'store_customer_id' : result['id'], 'odoo_partner_id' : cust.id, 'odoo_partner' : cust.id, } obj = self.env['channel.partner.mappings'] self._create_mapping(obj, mapping_dict) self._cr.commit() return cust_n
def onchange_employee(self, cr, uid, ids, employee_id, context=None): res = { 'value': { 'job_id': False, 'department_id': False, 'joining_date': False, 'confirmation_status': False, 'resign_id': False, 'capture_date': False, 'last_date': False, } } joining_date = '' last_date = '' if employee_id: exit_ids = self.search(cr, uid, [('employee_id', '=', employee_id)], context=context) if len(exit_ids) > 0: raise osv.except_osv( _('Warning!'), _('No Dues has already been in progress/done for this employee.' )) ee = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context) if ee: res['value']['job_id'] = ee.job_id.id res['value']['department_id'] = ee.department_id.id res['value']['dob'] = ee.birthday res['value']['division_id'] = ee.division.id res['value']['location_id'] = ee.office_location.id res['value']['gender'] = ee.gender res['value']['mobile_no'] = ee.mobile_phone joining_date = res['value']['joining_date'] = ee.joining_date res['value'][ 'confirmation_status'] = ee.confirmation_status.title() emp_sep_id = self.pool.get('ids.hr.employee.separation').search( cr, uid, [('employee_id', '=', employee_id), ('state', '=', 'done')], context=context) if emp_sep_id: es = self.pool.get('ids.hr.employee.separation').browse( cr, uid, emp_sep_id[0], context=context) if es: res['value']['resign_id'] = es.id res['value']['capture_date'] = es.capture_date last_date = res['value']['last_date'] = es.last_date emp_busi_id = self.pool.get('ids.business.information').search( cr, uid, [('employee_id', '=', employee_id)], context=context) if emp_busi_id: eb = self.pool.get('ids.business.information').browse( cr, uid, emp_busi_id[0], context=context) if eb: res['value']['email_control'] = eb.email_control res['value']['internet_control'] = eb.internet_control res['value']['remote_control'] = eb.remote_control res['value'][ 'software_requirement'] = eb.software_requirements res['value'][ 'application_share'] = eb.application_share_access res['value']['data_backup'] = eb.backup_remarks emp_tech_id = self.pool.get('ids.technical.information').search( cr, uid, [('employee_id', '=', employee_id)], context=context) if emp_tech_id: et = self.pool.get('ids.technical.information').browse( cr, uid, emp_tech_id[0], context=context) if et: res['value'][ 'allocation_it_asset'] = et.allocation_of_itassets res['value']['email_id_tech'] = et.email_created res['value'][ 'internet_control_tech'] = et.internet_access_control res['value']['backup_setup_tech'] = et.backup_setup res['value'][ 'software_requirement_tech'] = et.software_provisioning_and_access_control res['value'][ 'application_share_tech'] = et.application_share_access return res
def process_reconciliation(self, cr, uid, id, mv_line_dicts, context=None): """ Creates a move line for each item of mv_line_dicts and for the statement line. Reconcile a new move line with its counterpart_move_line_id if specified. Finally, mark the statement line as reconciled by putting the newly created move id in the column journal_entry_id. :param int id: id of the bank statement line :param list of dicts mv_line_dicts: move lines to create. If counterpart_move_line_id is specified, reconcile with it """ if context is None: context = {} st_line = self.browse(cr, uid, id, context=context) company_currency = st_line.journal_id.company_id.currency_id statement_currency = st_line.journal_id.currency or company_currency bs_obj = self.pool.get('account.bank.statement') am_obj = self.pool.get('account.move') aml_obj = self.pool.get('account.move.line') currency_obj = self.pool.get('res.currency') # Checks if st_line.journal_entry_id.id: raise osv.except_osv(_('Error!'), _('The bank statement line was already reconciled.')) for mv_line_dict in mv_line_dicts: for field in ['debit', 'credit', 'amount_currency']: if field not in mv_line_dict: mv_line_dict[field] = 0.0 if mv_line_dict.get('counterpart_move_line_id'): mv_line = aml_obj.browse(cr, uid, mv_line_dict.get('counterpart_move_line_id'), context=context) if mv_line.reconcile_id: raise osv.except_osv(_('Error!'), _('A selected move line was already reconciled.')) # Create the move move_name = st_line.statement_id.name + "/" + str(st_line.sequence) move_vals = bs_obj._prepare_move(cr, uid, st_line, move_name, context=context) move_id = am_obj.create(cr, uid, move_vals, context=context) # Create the move line for the statement line amount = currency_obj.compute(cr, uid, st_line.statement_id.currency.id, company_currency.id, st_line.amount, context=context) bank_st_move_vals = bs_obj._prepare_bank_move_line(cr, uid, st_line, move_id, amount, company_currency.id, context=context) aml_obj.create(cr, uid, bank_st_move_vals, context=context) # Complete the dicts st_line_currency = st_line.currency_id or statement_currency st_line_currency_rate = st_line.currency_id and statement_currency.id == company_currency.id and (st_line.amount_currency / st_line.amount) or False to_create = [] for mv_line_dict in mv_line_dicts: mv_line_dict['ref'] = move_name mv_line_dict['move_id'] = move_id mv_line_dict['period_id'] = st_line.statement_id.period_id.id mv_line_dict['journal_id'] = st_line.journal_id.id mv_line_dict['company_id'] = st_line.company_id.id mv_line_dict['statement_id'] = st_line.statement_id.id if mv_line_dict.get('counterpart_move_line_id'): mv_line = aml_obj.browse(cr, uid, mv_line_dict['counterpart_move_line_id'], context=context) mv_line_dict['account_id'] = mv_line.account_id.id if st_line_currency.id != company_currency.id: mv_line_dict['amount_currency'] = mv_line_dict['debit'] - mv_line_dict['credit'] mv_line_dict['currency_id'] = st_line_currency.id if st_line.currency_id and statement_currency.id == company_currency.id and st_line_currency_rate: debit_at_current_rate = self.pool.get('res.currency').round(cr, uid, company_currency, mv_line_dict['debit'] / st_line_currency_rate) credit_at_current_rate = self.pool.get('res.currency').round(cr, uid, company_currency, mv_line_dict['credit'] / st_line_currency_rate) else: debit_at_current_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['debit'], context=context) credit_at_current_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['credit'], context=context) if mv_line_dict.get('counterpart_move_line_id'): #post an account line that use the same currency rate than the counterpart (to balance the account) and post the difference in another line ctx = context.copy() ctx['date'] = mv_line.date debit_at_old_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['debit'], context=ctx) credit_at_old_rate = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, mv_line_dict['credit'], context=ctx) mv_line_dict['credit'] = credit_at_old_rate mv_line_dict['debit'] = debit_at_old_rate if debit_at_old_rate - debit_at_current_rate: currency_diff = debit_at_current_rate - debit_at_old_rate to_create.append(self.get_currency_rate_line(cr, uid, st_line, currency_diff, move_id, context=context)) if credit_at_old_rate - credit_at_current_rate: currency_diff = credit_at_current_rate - credit_at_old_rate to_create.append(self.get_currency_rate_line(cr, uid, st_line, currency_diff, move_id, context=context)) else: mv_line_dict['debit'] = debit_at_current_rate mv_line_dict['credit'] = credit_at_current_rate to_create.append(mv_line_dict) # Create move lines move_line_pairs_to_reconcile = [] for mv_line_dict in to_create: counterpart_move_line_id = None # NB : this attribute is irrelevant for aml_obj.create() and needs to be removed from the dict if mv_line_dict.get('counterpart_move_line_id'): counterpart_move_line_id = mv_line_dict['counterpart_move_line_id'] del mv_line_dict['counterpart_move_line_id'] new_aml_id = aml_obj.create(cr, uid, mv_line_dict, context=context) if counterpart_move_line_id != None: move_line_pairs_to_reconcile.append([new_aml_id, counterpart_move_line_id]) # Reconcile for pair in move_line_pairs_to_reconcile: # TODO : too slow aml_obj.reconcile_partial(cr, uid, pair, context=context) # Mark the statement line as reconciled self.write(cr, uid, id, {'journal_entry_id': move_id}, context=context)
def execute(self, cr, uid, ids, context=None): context = context or {} invoice_obj = self.pool.get('account.invoice') partner_obj = self.pool.get('res.partner') document_type_obj = self.pool.get('afip.document_type') v_r = [] for qi in self.browse(cr, uid, ids): conn = qi.journal_id.afip_connection_id serv = qi.journal_id.afip_connection_id.server_id sequence = qi.journal_id.sequence_id interpolation_dict = sequence._interpolation_dict() interpolated_prefix = sequence._interpolate( sequence.prefix or "", interpolation_dict) interpolated_suffix = sequence._interpolate( sequence.suffix or "", interpolation_dict) number_format = "%s%%0%sd%s" % (interpolated_prefix, qi.journal_id.sequence_id.padding, interpolated_suffix) if qi.first_invoice_number > qi.last_invoice_number: raise osv.except_osv( _(u'Qrong invoice range numbers'), _('Please, first invoice number must be less than last invoice' )) def _fch_(s): if s and len(s) == 8: return datetime.strptime( s, "%Y%m%d").strftime('%Y-%m-%d %H:%M:%S') elif s and len(s) > 8: return datetime.strptime( s, "%Y%m%d%H%M%S").strftime('%Y-%m-%d %H:%M:%S') else: return False for inv_number in range(qi.first_invoice_number, qi.last_invoice_number + 1): r = serv.wsfe_query_invoice( conn.id, qi.journal_id.journal_class_id.afip_code, inv_number, qi.journal_id.point_of_sale) r = r[serv.id] if r['EmisionTipo'] == 'CAE': invoice_domain = eval( _queries[qi.update_domain], {}, dict(r.items() + [['invoice_number', number_format % inv_number]])) inv_ids = invoice_obj.search( cr, uid, [('journal_id', '=', qi.journal_id.id)] + invoice_domain) if inv_ids and qi.update_invoices and len(inv_ids) == 1: # Update Invoice _logger.debug("Update invoice number: %s" % (number_format % inv_number)) invoice_obj.write( cr, uid, inv_ids, { 'date_invoice': _fch_(r['CbteFch']), 'internal_number': number_format % inv_number, 'afip_cae': r['CodAutorizacion'], 'afip_cae_due': _fch_(r['FchProceso']), 'afip_service_start': _fch_(r['FchServDesde']), 'afip_service_end': _fch_(r['FchServHasta']), 'amount_total': r['ImpTotal'], }) msg = 'Updated from AFIP (%s)' % (number_format % inv_number) invoice_obj.message_post( cr, uid, inv_ids, body=msg, subtype="l10n_ar_wsafip_fe.mt_invoice_ws_action", context=context) v_r.extend(inv_ids) elif inv_ids and qi.update_invoices and len(inv_ids) > 1: # Duplicated Invoices _logger.info( "Duplicated invoice number: %s %s" % (number_format % inv_number, tuple(inv_ids))) msg = 'Posible duplication from AFIP (%s)' % ( number_format % inv_number) for inv_id in inv_ids: invoice_obj.message_post( cr, uid, inv_id, body=msg, subtype= "l10n_ar_wsafip_fe.mt_invoice_ws_action", context=context) elif not inv_ids and qi.create_invoices: partner_id = partner_obj.search( cr, uid, [ ('document_type_id.afip_code', '=', r['DocTipo']), ('document_number', '=', r['DocNro']), ]) if partner_id: # Take partner partner_id = partner_id[0] else: # Create partner _logger.debug("Creating partner doc number: %s" % r['DocNro']) document_type_id = document_type_obj.search( cr, uid, [ ('afip_code', '=', r['DocTipo']), ]) assert len(document_type_id) == 1 document_type_id = document_type_id[0] partner_id = partner_obj.create( cr, uid, { 'name': r['DocNro'], 'document_type_id': document_type_id, 'document_number': r['DocNro'], }) _logger.debug("Creating invoice number: %s" % (number_format % inv_number)) partner = partner_obj.browse(cr, uid, partner_id) if not partner.property_account_receivable.id: raise osv.except_osv( _(u'Partner has not set a receivable account'), _('Please, first set the receivable account for %s' ) % partner.name) inv_id = invoice_obj.create( cr, uid, { 'company_id': qi.journal_id.company_id.id, 'account_id': partner.property_account_receivable.id, 'internal_number': number_format % inv_number, 'name': 'Created from AFIP (%s)' % number_format % inv_number, 'journal_id': qi.journal_id.id, 'partner_id': partner_id, 'date_invoice': _fch_(r['CbteFch']), 'afip_cae': r['CodAutorizacion'], 'afip_cae_due': _fch_(r['FchProceso']), 'afip_service_start': _fch_(r['FchServDesde']), 'afip_service_end': _fch_(r['FchServHasta']), 'amount_total': r['ImpTotal'], 'state': 'draft', }) msg = 'Created from AFIP (%s)' % (number_format % inv_number) invoice_obj.message_post( cr, uid, inv_id, body=msg, subtype="l10n_ar_wsafip_fe.mt_invoice_ws_action", context=context) v_r.append(inv_id) else: _logger.debug("Ignoring invoice: %s" % (number_format % inv_number)) return { 'name': _('Invoices'), 'domain': [('id', 'in', _ids)], 'res_model': 'account.invoice', 'type': 'ir.actions.act_window', 'view_id': False, 'view_mode': 'tree,form', 'view_type': 'form', 'limit': 80, }