def view_init(self, cr, uid, fields_list, context=None): """ Creates view dynamically and adding fields at runtime. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view with new columns. """ res = super(AccountBalanceCommonWizard, self).view_init(cr, uid, fields_list, context=context) for index in range(self.COMPARISON_LEVEL): # create columns for each comparison page self._columns.update({ "comp%s_filter" % (index,): fields.selection(self.COMPARE_SELECTION, string="Compare By", required=True), "comp%s_fiscalyear_id" % (index,): fields.many2one('account.fiscalyear', 'Fiscal year'), "comp%s_period_from" % (index,): fields.many2one('account.period', 'Start period'), "comp%s_period_to" % (index,): fields.many2one('account.period', 'End period'), "comp%s_date_from" % (index,): fields.date("Start Date"), "comp%s_date_to" % (index,): fields.date("End Date"), }) return res
def __init__(self, pool, cr): """ Dynamically add columns """ super(report_prompt_class, self).__init__(pool, cr) for counter in range(0, MAX_PARAMS): field_name = PARAM_XXX_STRING_VALUE % counter self._columns[field_name] = fields.char('String Value', size=64) field_name = PARAM_XXX_BOOLEAN_VALUE % counter self._columns[field_name] = fields.boolean('Boolean Value') field_name = PARAM_XXX_INTEGER_VALUE % counter self._columns[field_name] = fields.integer('Integer Value') field_name = PARAM_XXX_NUMBER_VALUE % counter self._columns[field_name] = fields.float('Number Value') field_name = PARAM_XXX_DATE_VALUE % counter self._columns[field_name] = fields.date('Date Value') field_name = PARAM_XXX_TIME_VALUE % counter self._columns[field_name] = fields.datetime('Time Value') self.paramfile = False
class res_partner(osv.osv): _description = 'Partner' _name = "res.partner" _order = "name" _columns = { 'name': fields.char('Name', size=128, required=True, select=True), 'date': fields.date('Date', select=1), 'title': fields.many2one('res.partner.title', 'Partner Form'), 'parent_id': fields.many2one('res.partner', 'Parent Partner'), 'child_ids': fields.one2many('res.partner', 'parent_id', 'Partner Ref.'), 'ref': fields.char('Reference', size=64, select=1), 'lang': fields.selection( _lang_get, 'Language', size=32, help= "If the selected language is loaded in the system, all documents related to this partner will be printed in this language. If not, it will be english." ), 'user_id': fields.many2one( 'res.users', 'Salesman', help= 'The internal user that is in charge of communicating with this partner if any.' ), 'vat': fields.char( 'VAT', size=32, help= "Value Added Tax number. Check the box if the partner is subjected to the VAT. Used by the VAT legal statement." ), 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'), 'website': fields.char('Website', size=64, help="Website of Partner"), 'comment': fields.text('Notes'), 'address': fields.one2many('res.partner.address', 'partner_id', 'Contacts'), 'category_id': fields.many2many('res.partner.category', 'res_partner_category_rel', 'partner_id', 'category_id', 'Categories'), 'events': fields.one2many('res.partner.event', 'partner_id', 'Events'), 'credit_limit': fields.float(string='Credit Limit'), 'ean13': fields.char('EAN13', size=13), 'active': fields.boolean('Active'), 'customer': fields.boolean('Customer', help="Check this box if the partner is a customer."), 'supplier': fields.boolean( 'Supplier', help= "Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order." ), 'city': fields.related('address', 'city', type='char', string='City'), 'phone': fields.related('address', 'phone', type='char', string='Phone'), 'mobile': fields.related('address', 'mobile', type='char', string='Mobile'), 'country': fields.related('address', 'country_id', type='many2one', relation='res.country', string='Country'), 'employee': fields.boolean('Employee', help="Check this box if the partner is an Employee."), 'email': fields.related('address', 'email', type='char', size=240, string='E-mail'), 'company_id': fields.many2one('res.company', 'Company', select=1), } def _default_category(self, cr, uid, context={}): if 'category_id' in context and context['category_id']: return [context['category_id']] return [] _defaults = { 'active': lambda *a: 1, 'customer': lambda *a: 1, 'category_id': _default_category, 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get( cr, uid, 'res.partner', context=c), } def copy(self, cr, uid, id, default={}, context={}): name = self.read(cr, uid, [id], ['name'])[0]['name'] default.update({'name': name + _(' (copy)'), 'events': []}) return super(res_partner, self).copy(cr, uid, id, default, context) def do_share(self, cr, uid, ids, *args): return True def _check_ean_key(self, cr, uid, ids, context=None): for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read( cr, uid, ids, [ 'ean13', ]): thisean = partner_o['ean13'] if thisean and thisean != '': if len(thisean) != 13: return False sum = 0 for i in range(12): if not (i % 2): sum += int(thisean[i]) else: sum += 3 * int(thisean[i]) if math.ceil(sum / 10.0) * 10 - sum != int(thisean[12]): return False return True # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])] def name_get(self, cr, uid, ids, context={}): if not len(ids): return [] if context.get('show_ref', False): rec_name = 'ref' else: rec_name = 'name' res = [(r['id'], r[rec_name]) for r in self.read(cr, uid, ids, [rec_name], context)] return res def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if not context: context = {} if name: ids = self.search(cr, uid, [('ref', '=', name)] + args, limit=limit, context=context) if not ids: ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context) else: ids = self.search(cr, uid, args, limit=limit, context=context) return self.name_get(cr, uid, ids, context) def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None): partners = self.browse(cr, uid, ids) for partner in partners: if len(partner.address): if partner.address[0].email: tools.email_send(email_from, [partner.address[0].email], subject, body, on_error) return True def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''): while len(ids): self.pool.get('ir.cron').create( cr, uid, { 'name': 'Send Partner Emails', 'user_id': uid, # 'nextcall': False, 'model': 'res.partner', 'function': '_email_send', 'args': repr( [ids[:16], email_from, subject, body, on_error]) }) ids = ids[16:] return True def address_get(self, cr, uid, ids, adr_pref=['default']): address_obj = self.pool.get('res.partner.address') address_ids = address_obj.search(cr, uid, [('partner_id', '=', ids)]) address_rec = address_obj.read(cr, uid, address_ids, ['type']) res = list(tuple(addr.values()) for addr in address_rec) adr = dict(res) # get the id of the (first) default address if there is one, # otherwise get the id of the first address in the list if res: default_address = adr.get('default', res[0][1]) else: default_address = False result = {} for a in adr_pref: result[a] = adr.get(a, default_address) return result def gen_next_ref(self, cr, uid, ids): if len(ids) != 1: return True # compute the next number ref cr.execute( "select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1" ) res = cr.dictfetchall() ref = res and res[0]['ref'] or '0' try: nextref = int(ref) + 1 except: raise osv.except_osv( _('Warning'), _("Couldn't generate the next id because some partners have an alphabetic id !" )) # update the current partner cr.execute("update res_partner set ref=%s where id=%s", (nextref, ids[0])) return True def view_header_get(self, cr, uid, view_id, view_type, context): res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context) if res: return res if (not context.get('category_id', False)): return False return _('Partners: ') + self.pool.get('res.partner.category').browse( cr, uid, context['category_id'], context).name def main_partner(self, cr, uid): ''' Return the id of the main partner ''' model_data = self.pool.get('ir.model.data') return model_data.browse( cr, uid, model_data.search(cr, uid, [('module', '=', 'base'), ('name', '=', 'main_partner')])[0], ).res_id
class l10n_es_aeat_mod340(osv.osv): def button_calculate(self, cr, uid, ids, args, context=None): if not context: context = {} calculate_obj = self.pool.get('l10n.es.aeat.mod340.calculate_records') calculate_obj._wkf_calculate_records(cr, uid, ids, context) return True def button_recalculate(self, cr, uid, ids, context=None): if context is None: context = {} calculate_obj = self.pool.get('l10n.es.aeat.mod340.calculate_records') calculate_obj._calculate_records(cr, uid, ids, context) return True def button_export(self, cr, uid, ids, context=None): #FUNCION CALCADA DEL MODELO 347, inoperativa de momento #raise osv.except_osv(_('No disponible:'), _('En desarrollo')) if context is None: context = {} export_obj = self.pool.get("l10n.es.aeat.mod340.export_to_boe") export_obj._export_boe_file(cr, uid, ids, self.browse(cr, uid, ids and ids[0])) return True def _name_get(self, cr, uid, ids, field_name, arg, context={}): """ Returns the report name """ result = {} for report in self.browse(cr, uid, ids, context): result[report.id] = report.number return result def _get_number_records(self, cr, uid, ids, field_name, args, context): result = {} for id in ids: result[id] = {}.fromkeys( ['number_records', 'total_taxable', 'total_sharetax', 'total'], 0.0) for model in self.browse(cr, uid, ids, context): for issue in model.issued: result[model.id]['number_records'] += len(issue.tax_line_ids) result[model.id]['total_taxable'] += issue.base_tax result[model.id]['total_sharetax'] += issue.amount_tax result[model.id]['total'] += issue.base_tax + issue.amount_tax for issue in model.received: result[model.id]['number_records'] += len(issue.tax_line_ids) result[model.id]['total_taxable'] += issue.base_tax result[model.id]['total_sharetax'] += issue.amount_tax result[model.id]['total'] += issue.base_tax + issue.amount_tax return result _inherit = "l10n.es.aeat.report" _name = 'l10n.es.aeat.mod340' _description = 'Model 340' _columns = { 'name': fields.function(_name_get, method=True, type="char", size="64", string="Name"), 'contact_phone': fields.char("Phone", size=9), 'phone_contact': fields.char('Phone Contact', size=9), 'name_contact': fields.char('Name And Surname Contact', size=40), 'period': fields.selection([('1T', 'First quarter'), ('2T', 'Second quarter'), ('3T', 'Third quarter'), ('4T', 'Fourth quarter'), ('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'), ('05', 'May'), ('06', 'June'), ('07', 'July'), ('08', 'August'), ('09', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December')], 'Period'), 'issued': fields.one2many('l10n.es.aeat.mod340.issued', 'mod340_id', 'Invoices Issued'), 'received': fields.one2many('l10n.es.aeat.mod340.received', 'mod340_id', 'Invoices Received'), 'investment': fields.one2many('l10n.es.aeat.mod340.investment', 'mod340_id', 'Property Investment'), 'intracomunitarias': fields.one2many('l10n.es.aeat.mod340.intracomunitarias', 'mod340_id', 'Operations Intracomunitarias'), 'ean13': fields.char('Electronic Code VAT reverse charge', size=16), 'total_taxable': fields.function( _get_number_records, method=True, type='float', string='Total Taxable', multi='recalc', help= "The declaration will include partners with the total of operations over this limit" ), 'total_sharetax': fields.function( _get_number_records, method=True, type='float', string='Total Share Tax', multi='recalc', help= "The declaration will include partners with the total of operations over this limit" ), 'number_records': fields.function( _get_number_records, method=True, type='integer', string='Records', multi='recalc', help= "The declaration will include partners with the total of operations over this limit" ), 'total': fields.function( _get_number_records, method=True, type='float', string="Total", multi='recalc', help= "The declaration will include partners with the total of operations over this limit" ), 'calculation_date': fields.date('Calculation date', readonly=True), } _defaults = { 'support_type': lambda *a: 'Telemático', 'number': lambda *a: '340', 'type': lambda *a: 'Normal' } def set_done(self, cr, uid, id, *args): self.write(cr, uid, id, { 'calculation_date': time.strftime('%Y-%m-%d'), 'state': 'done', }) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, 'l10n.es.aeat.mod340', id, 'done', cr) return True def _check_report_lines(self, cr, uid, ids, context=None): """checks report lines""" # if context is None: context = {} # for item in self.browse(cr, uid, ids, context): # ## Browse partner record lines to check if all are correct (all fields filled) # for partner_record in item.partner_record_ids: # if not partner_record.partner_state_code: # raise osv.except_osv(_('Error!'), _("All partner state code field must be filled.")) # if not partner_record.partner_vat: # raise osv.except_osv(_('Error!'), _("All partner vat number field must be filled.")) # # for real_state_record in item.real_state_record_ids: # if not real_state_record.state_code: # raise osv.except_osv(_('Error!'), _("All real state records state code field must be filled.")) return True def check_report(self, cr, uid, ids, context=None): """Different check out in report""" if context is None: context = {} self._check_report_lines(cr, uid, ids, context) return True def action_confirm(self, cr, uid, ids, context=None): """set to done the report and check its records""" if context is None: context = {} self.check_report(cr, uid, ids, context) self.write(cr, uid, ids, {'state': 'done'}) return True def confirm(self, cr, uid, ids, context=None): """set to done the report and check its records""" self.write(cr, uid, ids, {'state': 'done'}) return True def cancel(self, cr, uid, ids, context=None): """set to done the report and check its records""" self.write(cr, uid, ids, {'state': 'canceled'}) return True
class hr_nomina(osv.osv): _name = 'hr.nomina' _description = 'Nominas de Empleados' _columns = { 'name': fields.char('Nómina', size=20), 'employee_id': fields.many2one('hr.employee', 'Empleado', required=True, select="1"), 'retribucion_bruta': fields.float('Retribución Bruta', digits=(16, 2)), 'ss_empresa': fields.float('S.S a Cargo de la empresa', digits=(16, 2)), 'ss_trabajador': fields.float('S.S a cargo del Trabajador', digits=(16, 2)), 'irpf': fields.float('Retención IRPF (%)', digits=(16, 2)), 'fecha_nomina': fields.date('Fecha de la Nómina', select="1"), 'state': fields.selection( (('borrador', 'Borrador'), ('confirmada', 'Confirmada'), ('pagada', 'Pagada'), ('cancelada', 'Cancelada')), 'Estado Nómina', readonly=True, select="1"), 'numero': fields.char( 'Número de nomina', size=32, readonly=True, help= "Número único de nómina, se asigna automáticamente cuando se crea la nómina", select="1"), 'extra': fields.boolean('Paga Extra'), 'asiento_nomina_confirmada': fields.many2one('account.move', 'Asiento Nómina confirmada', readonly=True), 'asiento_nomina_pagada': fields.many2one('account.move', 'Asiento Nómina pagada', readonly=True), } _defaults = { 'state': lambda *a: 'borrador', } def comprueba_mes(self, fecha_anticipo, fecha_nomina): anticipo = time.strptime(fecha_anticipo, '%Y-%m-%d') nomina = time.strptime(fecha_nomina, '%Y-%m-%d') dateNomina = datetime.datetime(nomina[0], nomina[1], nomina[2]) dateAnterior = time.strptime( (dateNomina - datetime.timedelta(nomina[2] + 1)).strftime('%Y-%m-%d'), '%Y-%m-%d') if (anticipo[0] == dateAnterior[0]) and ( dateAnterior[1] == anticipo[1]): #Si se solicito anticipo el mes pasado return True else: return False def comprueba_anticipo(self, cr, uid, ids, fechaNomina, empleado_id): ################################################################ # OBJETOS ################################################################ anticipo_obj = self.pool.get('hr.anticipo') ################################################################ anticipo_ids = anticipo_obj.search(cr, uid, [('employee_id', '=', empleado_id)]) for anticipo in anticipo_ids: obj_anticipo = anticipo_obj.browse(cr, uid, anticipo) if self.comprueba_mes( obj_anticipo.fecha_anticipo, fechaNomina) and obj_anticipo.state == 'pagado': return obj_anticipo.cantidad return 0 def confirmar_nomina(self, cr, uid, ids, *args): ################################################################## # OBJETOS ################################################################## account_journal_obj = self.pool.get('account.journal') account_period_obj = self.pool.get('account.period') account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') ################################################################## cuentas = get_configuration(cr, uid, ids) for nom in self.browse(cr, uid, ids): if nom.state != 'borrador': continue journal_id = cuentas['diario_destino'] numero = self.pool.get('ir.sequence').get(cr, uid, 'hr.nomina') journal = account_journal_obj.browse(cr, uid, journal_id) fechaNomina = nom.fecha_nomina line = {} period_ids = account_period_obj.search(cr, uid, [ ('date_start', '<=', fechaNomina or time.strftime('%Y-%m-%d')), ('date_stop', '>=', fechaNomina or time.strftime('%Y-%m-%d')) ]) if len(period_ids): periodo_id = period_ids[0] else: raise osv.except_osv( _('No existe un periodo para esa fecha de nomina!'), _('No se pueden generar nóminas cuya fecha esté en un periodo que no existe, \nsi desea generarla por favor cree el periodo contable correspondiente.' )) referencia = str(numero) + ' : ' + str( nom.employee_id.name) + ' - ' + str(fechaNomina) if nom.extra: referencia = "Paga Extra: " + str( nom.employee_id.name) + ' - ' + str(fechaNomina) move_val = { 'ref': referencia, 'journal_id': journal_id, 'date': fechaNomina, 'period_id': periodo_id, } move_id = account_move_obj.create(cr, uid, move_val) #Cuenta del empleado cuenta_id = nom.employee_id.cuenta_id.id #si no tiene cuenta lanzamos un error if not cuenta_id: raise osv.except_osv( _('No existe una cuenta configurada para el empleado!'), _('Por favor configure una cuenta en la ficha del empleado en la que generar los asientos de la nómina.' )) retencion_irpf = (nom.retribucion_bruta * nom.irpf) / 100 anticipo = self.comprueba_anticipo(cr, uid, ids, fechaNomina, nom.employee_id.id) sueldo_neto = nom.retribucion_bruta - retencion_irpf - nom.ss_trabajador if anticipo and nom.extra == False: sueldo_neto -= anticipo val = { 'account_id': cuentas['cuenta_anticipos'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Anticipo', 'credit': anticipo, 'ref': referencia } account_move_line_obj.create(cr, uid, val) account = { 'account_id': cuenta_id, 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Sueldo Bruto', 'debit': nom.retribucion_bruta, 'ref': referencia } account_move_line_obj.create(cr, uid, account) ss_empresa = { 'account_id': cuentas['cuenta_ss_empresa'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'S.S. Empresa', 'debit': nom.ss_empresa, 'ref': referencia } account_move_line_obj.create(cr, uid, ss_empresa) hacienda_publica = { 'account_id': cuentas['cuenta_hacienda_publica'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'IRPF', 'credit': retencion_irpf, 'ref': referencia } account_move_line_obj.create(cr, uid, hacienda_publica) ss_acreedores = { 'account_id': cuentas['cuenta_ss_acreedores'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'S.S. Acreedores ', 'credit': nom.ss_trabajador + nom.ss_empresa, 'ref': referencia } account_move_line_obj.create(cr, uid, ss_acreedores) pendientes_pago = { 'account_id': cuentas['cuenta_pendientes_pago'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Sueldo Neto', 'credit': sueldo_neto, 'ref': referencia } account_move_line_obj.create(cr, uid, pendientes_pago) account_move_obj.write(cr, uid, [move_id], {'date': fechaNomina}) account_move_obj.post(cr, uid, [move_id]) self.write(cr, uid, ids, {'numero': numero}) self.write(cr, uid, ids, { 'state': 'confirmada', 'asiento_nomina_confirmada': move_id }) return True def pagar_nomina(self, cr, uid, ids, *args): ################################################################## # OBJETOS ################################################################## account_journal_obj = self.pool.get('account.journal') account_period_obj = self.pool.get('account.period') account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') ################################################################## cuentas = get_configuration(cr, uid, ids) for nom in self.browse(cr, uid, ids): if nom.state != 'confirmada': continue journal_id = cuentas['diario_destino'] journal = account_journal_obj.browse(cr, uid, journal_id) fechaNomina = nom.fecha_nomina line = {} period_ids = account_period_obj.search(cr, uid, [ ('date_start', '<=', fechaNomina or time.strftime('%Y-%m-%d')), ('date_stop', '>=', fechaNomina or time.strftime('%Y-%m-%d')) ]) if len(period_ids): periodo_id = period_ids[0] referencia = nom.numero + ' : Pago ' + nom.employee_id.name + ' - ' + fechaNomina if nom.extra: referencia = "Pago de Paga Extra: " + nom.employee_id.name + ' - ' + fechaNomina move = { 'ref': referencia, 'journal_id': journal_id, 'date': fechaNomina, 'period_id': periodo_id } move_id = account_move_obj.create(cr, uid, move) retencion_irpf = (nom.retribucion_bruta * nom.irpf) / 100 sueldo_neto = nom.retribucion_bruta - retencion_irpf - nom.ss_trabajador anticipo = self.comprueba_anticipo(cr, uid, ids, fechaNomina, nom.employee_id.id) if anticipo and nom.extra == False: sueldo_neto -= anticipo cuenta_banco = { 'account_id': cuentas['cuenta_bancos'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Banco', 'credit': sueldo_neto, 'ref': referencia, } account_move_line_obj.create(cr, uid, cuenta_banco) cuenta_pendiente = { 'account_id': cuentas['cuenta_pendientes_pago'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Renumeraciones pendientes', 'debit': sueldo_neto, 'ref': referencia, } account_move_line_obj.create(cr, uid, cuenta_pendiente) self.write(cr, uid, ids, { 'state': 'pagada', 'asiento_nomina_pagada': move_id }) account_move_obj.write(cr, uid, [move_id], {'date': fechaNomina}) account_move_obj.post(cr, uid, [move_id]) return True def cancelar_nomina(self, cr, uid, ids, *args): for nom in self.browse(cr, uid, ids): acc_obj = self.pool.get('account.move') if nom.state == 'confirmada': acc_obj.button_cancel(cr, uid, [nom.asiento_nomina_confirmada.id]) self.write(cr, uid, ids, {'state': 'cancelada'}) return True
class chricar_tenant(osv.osv): _name = "chricar.tenant" def _price_per_m2(self, cr, uid, ids, field_name, arg, context=None): result = {} for tenant in self.browse(cr, uid, ids, context): lease = tenant.lease surface = tenant.top_id.surface result[tenant.id] = 0.0 if surface and surface > 0.0: #print lease / surface result[tenant.id] = lease / surface return result def _dirname(self, cr, uid, ids, field_name, arg, context=None): result = {} for dirname in self.browse(cr, uid, ids, context): result[dirname.id] = str( dirname.name) + ' ' + dirname.partner_id.name return result def _get_state(self, cr, uid, ids, field_name, arg, context=None): result = {} for tenant in self.browse(cr, uid, ids, context): result[tenant.id] = 'past' today = time.strftime('%Y-%m-%d') if tenant.name <= today and (not tenant.to_date or tenant.to_date >= today): result[tenant.id] = 'current' if tenant.name > today: result[tenant.id] = 'future' return result _columns = { 'contract': fields.char('Contract ', size=64), 'date_contract': fields.date('Contract Date'), 'lease': fields.float('Lease monthly', digits=(8, 2)), 'limited': fields.boolean('Limited'), 'name': fields.date( 'From Date', required=True, help="Date Contract Starts", ), 'note': fields.text('Notes'), 'notice_period': fields.integer('Notice Period Month', help="Notice period in month"), 'termination_date': fields.selection([('month', 'Month End'), ('quater', 'Quater End')], 'Termination Date', size=24), 'partner_id': fields.many2one('res.partner', 'Tenant', select=True, required=True), 'price': fields.function( _price_per_m2, method=True, string=u"Price / m²", type='float', digits=(16, 2), ), 'sort': fields.related('top_id', 'sort', tpye='integer', relation='chricar.top', string="Sort", readonly=True), 'surface': fields.related('top_id', 'surface', tpye='float', relation='chricar.top', string="Surface", readonly=True), 'to_date': fields.date('To Date', help="Date Contract Ends"), 'top_id': fields.many2one('chricar.top', 'Top', select=True, required=True), 'location_id': fields.related('top_id', 'location_id', type='many2one', relation='stock.location', string="Location", readonly=True), 'waiver_of_termination': fields.integer( 'Waiver of Termination', help="Duration in month bofore the tenant can terminate the lease" ), 'lease_free': fields.integer('Initial free month', help="Duration in month the tenant does not pay rent"), #'dirname' : fields.function(_dirname, method=True, string="Dirname",type='char',size=128, store=True), 'state': fields.function(_get_state, method=True, string='Status', type='char', readonly=True), 'ref_top': fields.related('top_id', 'ref_top', type='char', relation='chricar.top', string="Ref Top", readonly=True), } _defaults = {} _order = "name desc" def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): super(chricar_tenant, self).name_search(cr, user, name, args, operator='=', context=context, limit=limit)
class Pembelian_Barang(osv.osv): STATES = [('draft', 'Draft'), ('confirm', 'Check'), ('confirm2', 'Confirm'), ('purchase', 'Purchase'), ('done', 'Done'), ('cancel', 'Cancel'), ('edit', 'Edit PB')] # FOR STATE FIELD def _getParentState(self, cr, uid, ids, field_name, args, context={}): res = {} for data in self.browse(cr, uid, ids, context): line = [x.id for x in data.detail_pb_ids] state_done = [ y.id for y in data.detail_pb_ids if y.state == "done" ] operation = context.get('operation', False) action_state = context.get('action_state', False) if line == state_done: res[data.id] = "done" if operation == "create": res[data.id] = "draft" elif action_state == "submit": res[data.id] = "confirm" elif action_state == "confirm": res[data.id] = "confirm2" elif action_state == "confirm2": res[data.id] = "purchase" elif action_state == "draft": res[data.id] = "draft" return res def _get_cek_state_detail_pb(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('detail.pb').browse(cr, uid, ids, context=context): result[line.detail_pb_id.id] = True return result.keys() def _get_cek_state_delivery_line(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('order.requisition.delivery.line').browse( cr, uid, ids, context=context): result[line.purchase_requisition_line_id.detail_pb_id.id] = True return result.keys() _name = 'pembelian.barang' _columns = { 'name': fields.char('No.PB', required=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'spk_no': fields.char('SPK No / PO No', readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }, track_visibility='onchange'), 'tanggal': fields.date('Date', required=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'duedate': fields.date('Due Date', required=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'employee_id': fields.many2one('hr.employee', "Employee", required=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'department_id': fields.many2one('hr.department', 'Department', readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'customer_id': fields.many2one('res.partner', 'Customer', domain=[('customer', '=', True)], readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'detail_pb_ids': fields.one2many('detail.pb', 'detail_pb_id', 'Detail PB', readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }, track_visibility='onchange'), 'ref_pb': fields.char('Ref No', required=True, select=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }, track_visibility='onchange'), 'notes': fields.text('Terms and Conditions', readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'cancel_reason': fields.text('Cancel Reason'), 'product_id': fields.related('detail_pb_ids', 'name', type='many2one', relation='product.product', string='Product'), 'source_location_request_id': fields.many2one('stock.location', "Source Location", readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'destination_location_request_id': fields.many2one('stock.location', "Destination Location", required=True, readonly=True, states={ 'draft': [('readonly', False)], 'edit': [('readonly', False)] }), 'state': fields.function(_getParentState, method=True, string="State", type="selection", selection=STATES, store={ 'pembelian.barang': (lambda self, cr, uid, ids, c={}: ids, ['state'], 20), 'detail.pb': (_get_cek_state_detail_pb, ['state'], 20), 'order.requisition.delivery.line': (_get_cek_state_delivery_line, ['state'], 20), }), } _inherit = ['mail.thread'] _track = { 'state': { 'sbm_purchase.pb_confirmed': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'confirm', 'sbm_purchase.pb_checked': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'confirm2', 'sbm_purchase.pb_canceled': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'cancel', 'sbm_purchase.pb_draft': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'draft', }, } def _employee_get(obj, cr, uid, context=None): if context is None: context = {} cek = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)]) hasil = obj.pool.get('hr.employee').browse(cr, uid, cek) if hasil: ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context) if ids: return ids[0] else: return uid _defaults = { 'name': '/', 'tanggal': time.strftime('%Y-%m-%d'), 'employee_id': _employee_get, 'state': 'draft', 'source_location_request_id': 12, } _order = 'id DESC' def action_cancel_item(self, cr, uid, ids, context=None): if context is None: context = {} dummy, view_id = self.pool.get('ir.model.data').get_object_reference( cr, uid, 'sbm_purchase', 'wizard_pr_cancel_form') context.update({ 'active_model': self._name, 'active_ids': ids, 'active_id': len(ids) and ids[0] or False }) return { 'view_mode': 'form', 'view_id': view_id, 'view_type': 'form', 'view_name': 'wizard_pr_cancel_form', 'res_model': 'pembelian.barang', 'type': 'ir.actions.act_window', 'target': 'new', 'context': context, 'nodestroy': True, } def setDeuDate(self, cr, uid, ids, tanggal): setDueDateValue = datetime.strptime(tanggal, "%Y-%m-%d") + timedelta(days=4) return {'value': {'duedate': setDueDateValue.strftime('%Y-%m-%d')}} def setTanggal(self, cr, uid, ids, tanggal, duedate): setDueDateValue = datetime.strptime(tanggal, "%Y-%m-%d") + timedelta(days=4) cektanggal = setDueDateValue.strftime("%Y-%m-%d") if duedate < cektanggal: return {'value': {'duedate': cektanggal}} else: return {'value': {'duedate': duedate}} def create(self, cr, uid, vals, context={}): # vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'pembelian.barang') context.update(action_state='confirm') return super(Pembelian_Barang, self).create(cr, uid, vals, context=context) def setDept(self, cr, uid, ids, pid): employee_id = self.pool.get('hr.employee').browse(cr, uid, pid) dept_id = employee_id.department_id.id return {'value': {'department_id': dept_id}} def submit(self, cr, uid, ids, context={}): context.update(action_state='submit') val = self.browse(cr, uid, ids)[0] code = val.destination_location_request_id.code no = self.pool.get('ir.sequence').get( cr, uid, 'pembelian.barang') + 'PB/SBM/' + code + '/' + time.strftime( '%y') + '/' + time.strftime('%m') return self.write(cr, uid, ids, { 'state': 'confirm', 'name': no }, context=context) def edit(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'edit'}) def setdraft(self, cr, uid, ids, context={}): context.update(action_state='draft') # print '============',data return self.write(cr, uid, ids, {'state': 'draft'}, context=context) def confirm3(self, cr, uid, ids, context={}): val = self.browse(cr, uid, ids)[0] obj_detail_pb = self.pool.get('detail.pb') for detail in val.detail_pb_ids: if detail.state == 'draft': cr.execute('Update detail_pb Set state=%s Where id=%s', ('onproses', detail.id)) return self.write(cr, uid, ids, {'state': 'purchase'}) def confirm(self, cr, uid, ids, context={}): # val = self.browse(cr, uid, ids)[0] # usermencet = self.pool.get('res.user') # if val.employee_id.parent_id.id != uid : # raise osv.except_osv(('Perhatian..!!'), ('Harus Atasannya langsung ..')) context.update(action_state='confirm') return self.write(cr, uid, ids, {'state': 'confirm2'}, context=context) def confirm2(self, cr, uid, ids, context={}): # val = self.browse(cr, uid, ids)[0] # usermencet = self.pool.get('res.user') # if val.employee_id.parent_id.id != uid : # raise osv.except_osv(('Perhatian..!!'), ('Harus Atasannya langsung ..')) context.update(action_state='confirm2') cr.execute('Update detail_pb Set state=%s Where detail_pb_id=%s', ('onproses', ids[0])) return self.write(cr, uid, ids, {'state': 'purchase'}, context=context) def purchase(self, cr, uid, ids, context={}): return self.write(cr, uid, ids, {'state': 'done'}) def reportpb(self, cr, uid, ids, context=None): if context is None: context = {} datas = {'ids': context.get('active_ids', [])} datas['model'] = 'pembelian.barang' datas['form'] = self.read(cr, uid, ids)[0] return { 'type': 'ir.actions.report.xml', 'report_name': 'print.pb', 'report_type': 'webkit', 'datas': datas, }
class maintenance_maintenance(osv.osv): _name = "maintenance.maintenance" _description = "maintenance contract" def _contract_date(self, cr, uid, ids): for contract in self.browse(cr, uid, ids): cr.execute(""" SELECT count(1) FROM maintenance_maintenance WHERE ( (%(date_from)s BETWEEN date_from AND date_to) OR (%(date_to)s BETWEEN date_from AND date_to) OR (%(date_from)s < date_from AND %(date_to)s > date_to) ) AND partner_id = %(partner)s AND id <> %(id)s AND state = %(state)s """, { "date_from": contract.date_from, "date_to": contract.date_to, "partner": contract.partner_id.id, "id": contract.id, "state": "open" }) if cr.fetchone()[0]: return False return True _columns = { 'name' : fields.char('Contract ID', size=64, required=True), 'partner_id' : fields.many2one('res.partner','Partner', required=True), 'partner_invoice_id' : fields.many2one('res.partner.address','Address'), 'date_from' : fields.date('Date From', required=True), 'date_to' : fields.date('Date To', required=True), 'password' : fields.char('Password', size=64, invisible=True, required=True), 'module_ids' : fields.many2many('maintenance.maintenance.module','maintenance_module_rel','maintenance_id','module_id',string='Modules'), 'state' : fields.selection([('draft','Draft'), ('open','Open'), ('cancel','Cancel'), ('done','Done')], 'State', readonly=True), 'note': fields.text('Note'), 'type_id': fields.many2one('maintenance.contract.type', 'Contract Type', required=True), } _defaults = { 'date_from':lambda *a: time.strftime('%Y-%m-%d'), 'password' : lambda *a : str(uuid.uuid4()).split('-')[-1], 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'maintenance.maintenance'), 'state': lambda *a: 'draft', } _sql_constraints = [ ("check_dates", "CHECK (date_from < date_to)", 'The "from" date must not be after the "to" date.'), ] _constraints = [ (_contract_date, 'You can not have 2 contracts (for the same partner) that overlaps !', ['partner_id', 'date_from','date_to']), ] def check_contract(self, cr, uid, modules, contract): external_modules = [] contract_module_list = [] date_from = date_to = False maintenance_ids=self.search(cr,uid, [('name','=',contract['name']), ('password','=',contract['password']), ('date_from','<=',mx.DateTime.today()), ('date_to','>=',mx.DateTime.today()) ],limit=1) if maintenance_ids: maintenance_obj = self.browse(cr,uid,maintenance_ids)[0] date_from = maintenance_obj.date_from date_to = maintenance_obj.date_to contract_module_list = map(lambda x:(x['name'], x['version']), maintenance_obj.module_ids) for module in modules: if (module['name'], module['installed_version']) not in contract_module_list: external_modules.append(module['name']) return { 'id': (maintenance_ids and maintenance_ids[0] or 0), 'status': (maintenance_ids and ('full', 'partial')[bool(external_modules)] or 'none'), 'external_modules': external_modules, 'modules_with_contract' : contract_module_list, 'message': '', 'date_from': date_from, 'date_to': date_to, } def onchange_partner_id(self, cr, uid, ids, part): if not part: return {'value':{'partner_address_id': False}} addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['default']) return {'value':{'partner_invoice_id': addr['default']}} def onchange_date_from(self, cr, uid, ids, date_from): if not date_from: return {'value:':{'date_to':False}} return { 'value': { 'date_to' : (mx.DateTime.strptime(date_from, '%Y-%m-%d') + mx.DateTime.RelativeDate(years=1)).strftime("%Y-%m-%d") } } def __for_each_module(self, cr, uid, ids, modules, callback): res = {} toload = ids if isinstance(ids, (int, long)): toload = [ids] for c in self.browse(cr, uid, toload): res[str(c.id)] = {} for m in c.module_ids: if (m.name not in modules) or parse_version(modules[m.name]) < parse_version(m.version): res[str(c.id)][m.name] = callback(m) if isinstance(ids, (int, long)): return res[str(ids)] return res def get_available_updates(self, cr, uid, ids, modules): return self.__for_each_module(cr, uid, ids, modules, lambda m: m.version) def retrieve_updates(self, cr, uid, ids, modules): return self.__for_each_module(cr, uid, ids, modules, lambda m: addons.get_module_as_zip_from_module_directory(m.path, b64enc=True)) def submit(self, cr, uid, id, tb, explanations, remarks=None, origin=None): contract = self.browse(cr, uid, id) origin_to_channelname = { 'client': 'Client Bug Reporting Form', 'openerp.com': 'OpenERP.com Web Form', } channelname = origin_to_channelname.get(origin) if channelname: channelobj = self.pool.get('res.partner.canal') channelid = channelobj.search(cr, uid, [('name', '=', channelname)]) channelid = channelid and channelid[0] or None if not channelid: channelid = channelobj.create(cr, uid, {'name': channelname}) else: channelid = False # no Channel for the CRM Case crmcase = self.pool.get('crm.case') desc = "%s\n\n-----\n%s" % (explanations, tb) if remarks: desc = "%s\n\n----\n%s" % (desc, remarks) caseid = crmcase.create(cr, uid, { 'name': 'Maintenance report from %s' % (contract.name), 'section_id': contract.type_id.crm_case_section_id.id, 'categ_id': contract.type_id.crm_case_categ_id.id, 'partner_id': contract.partner_id.id, 'description': desc, 'canal_id': channelid, }) crmcase.case_log(cr, uid, [caseid]) return caseid
class res_partner_job(osv.osv): def name_get(self, cr, uid, ids, context=None): """ @param self: The object pointer @param cr: the current row, from the database cursor, @param user: the current user, @param ids: List of partner address’s IDs @param context: A standard dictionary for contextual values """ if context is None: context = {} if not ids: return [] res = [] jobs = self.browse(cr, uid, ids, context=context) contact_ids = [rec.contact_id.id for rec in jobs] contact_names = dict(self.pool.get('res.partner.contact').name_get(cr, uid, contact_ids, context=context)) for r in jobs: function_name = r.function funct = function_name and (", " + function_name) or "" res.append((r.id, contact_names.get(r.contact_id.id, '') + funct)) return res _name = 'res.partner.job' _description ='Contact Partner Function' _order = 'sequence_contact' _columns = { 'name': fields.related('address_id', 'partner_id', type='many2one',\ relation='res.partner', string='Partner', help="You may\ enter Address first,Partner will be linked automatically if any."), 'address_id': fields.many2one('res.partner.address', 'Address', \ help='Address which is linked to the Partner'), # TO Correct: domain=[('partner_id', '=', name)] 'contact_id': fields.many2one('res.partner.contact','Contact', required=True, ondelete='cascade'), 'function': fields.char('Partner Function', size=64, help="Function of this contact with this partner"), 'sequence_contact': fields.integer('Contact Seq.',help='Order of\ importance of this address in the list of addresses of the linked contact'), 'sequence_partner': fields.integer('Partner Seq.',help='Order of importance\ of this job title in the list of job title of the linked partner'), 'email': fields.char('E-Mail', size=240, help="Job E-Mail"), 'phone': fields.char('Phone', size=64, help="Job Phone no."), 'fax': fields.char('Fax', size=64, help="Job FAX no."), 'extension': fields.char('Extension', size=64, help='Internal/External extension phone number'), 'other': fields.char('Other', size=64, help='Additional phone field'), 'date_start': fields.date('Date Start',help="Start date of job(Joining Date)"), 'date_stop': fields.date('Date Stop', help="Last date of job"), 'state': fields.selection([('past', 'Past'),('current', 'Current')], \ 'State', required=True, help="Status of Address"), } _defaults = { 'sequence_contact' : lambda *a: 0, 'state': lambda *a: 'current', } def onchange_name(self, cr, uid, ids, partner_id='', address_id='', context=None): address_id = False if partner_id: partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context) addresses = [a.id for a in partner.address if a.type == 'contact'] or [a.id for a in partner.address] address_id = addresses and addresses[0] or False domain = partner_id and [('partner_id', '=', partner_id)] or [] return {'value': {'address_id': address_id}, 'domain': {'address_id': domain}} def onchange_address(self, cr, uid, _, name, address_id, context=None): """ @@param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user, @param _: List of IDs, @address_id : ID of the Address selected, @param context: A standard dictionary for contextual values """ partner_id = False if address_id: address = self.pool.get('res.partner.address').browse(cr, uid, address_id, context=context) partner_id = address.partner_id.id domain = name and [('partner_id', '=', name)] or [] return {'value': {'name': partner_id}, 'domain': {'address_id': domain}}
class jmdencuestas(osv.Model): _name = "ea.encuesta" _inherit = "mail.thread" #Workflow functions #new state def action_new(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'new'}) # ... perform other tasks return True def action_aprobado(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'aprobado', 'usr_1': uid}) # ... perform other tasks return True def action_segunda(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'segunda', 'usr_2': uid}) # ... perform other tasks return True def action_tercera(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'tercera', 'usr_3': uid}) # ... perform other tasks return True def action_cliente(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'cliente', 'usr_4': uid}) # ... perform other tasks return True def action_cancelado(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'cancelado'}) # ... perform other tasks return True def action_ec(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'ec'}) # ... perform other tasks return True def reiniciar(self, cr, uid, ids, context="None"): self.write(cr, uid, ids, {'state': 'new'}) return True def on_change_odt(self, cr, uid, ids, odt_id, context=None): ret = {} values = {} odt_object = self.pool.get("ea.project_wizard") for i in odt_object.browse(cr, uid, [odt_id], context): values['name'] = i.name ret['value'] = values return ret _columns = { 'name': fields.char(string="Nombre", size=40), 'state': fields.selection([('new', 'Nuevo'), ('aprobado', 'Kick Off'), ('segunda', 'Campo'), ('tercera', 'Procesamiento'), ('ec', 'Ejecutivo de Cuenta'), ('cliente', 'Ok Cliente'), ('cancelado', 'Cancelado')], "Estado", readonly=True), 'ejecutivo': fields.many2one("hr.employee", string="Ejecutivo"), 'encuesta': fields.binary("Cuestionario aprobado"), 'fieldname': fields.char("Nombre del Archivo"), 'proyecto': fields.many2one("project.project", "Clave"), 'nombre_corto': fields.related('proyecto', 'nombre_corto', string="Nombre Corto", type="char"), 'aprobadopor': fields.char(string="Aprobación del cliente", size=40, translate=True), 'aprobacion': fields.date(string="Fecha de aprobación"), 'medio': fields.selection([("telefono", "LLamada telefónica"), ("mail", "Correo electrónico"), ("visita", "Presencial")], string="Medio de Confirmación"), 'salario_ids': fields.one2many("ea.encuesta_salario", "encuesta", string="Salarios"), 'odt_id': fields.many2one("ea.project_wizard", "Orden de Trabajo"), 'adicionales': fields.boolean("Desbloquear el Cuestionario"), 'ad_txt': fields.text("Cambios"), 'ad_pers': fields.char("Quien autoriza cambios"), 'bloquear': fields.boolean("Bloquear Cuestionario"), 'criterio_ids': fields.one2many("ea.salario.concepto", "encuesta_id", string="Criterios Habilitados"), 'usr_1': fields.many2one("res.users", string="Aprobó"), 'usr_2': fields.many2one("res.users", string="Segundo Aprobador"), 'usr_3': fields.many2one("res.users", string="Tercer Aprobador"), 'usr_4': fields.many2one("res.users", string="Capturó Ok Cliente"), }
class lot_range_int_move(osv.osv_memory): _name = 'lot.range.int.move' _description = '' ##------------------------------------------------------------------------- ##------------------------------------------------------- _internal methods ##--------------------------------------------------------- function fields _columns = { 'type': fields.selection( [('range', 'Range'), ('location', 'Location'), ('bundle', 'Bundle')], string='Type', required=True), 'location_id': fields.many2one( 'stock.location', 'Location', ondelete='restrict'), 'prod_lot_id': fields.many2one( 'stock.production.lot', 'First lot', required=False), 'bundle_id': fields.many2one( 'tcv.bundle', 'Bundle', required=False, domain=[('reserved', '=', False)]), 'product_id': fields.related( 'prod_lot_id', 'product_id', type='many2one', relation='product.product', string='Product', store=False, readonly=True), 'item_qty': fields.integer( 'Lot\'s qty', required=True), 'date': fields.date( 'Date'), 'location_dest_id': fields.many2one( 'stock.location', 'Destination Location', readonly=False, ondelete='restrict', required=True, help="Location where the system will stock the finished " + "products."), } _defaults = { 'item_qty': 10, 'type': lambda *a: 'location', } _sql_constraints = [ ('item_qty_range', 'CHECK(item_qty between 1 and 99)', 'The Lot\'s qty must be in 1-99 range!'), ] ##------------------------------------------------------------------------- ##---------------------------------------------------------- public methods def create_lines_by_range(self, cr, uid, ids, lot_rng, context=None): lines = [] obj_lot = self.pool.get('stock.production.lot') obj_wiz = self.pool.get('tcv.internal.move.wiz.lines') lot_int = int(lot_rng.prod_lot_id.name) lot_names = map(lambda x: str(x), range(lot_int, lot_int + lot_rng.item_qty)) for lot_name in lot_names: lot_ids = obj_lot.search( cr, uid, [('name', 'ilike', lot_name)]) for lot in obj_lot.browse(cr, uid, lot_ids, context={}): data = obj_wiz.get_lot_data( cr, uid, ids, lot.id, context=None) data.update( {'location_dest_id': lot_rng.location_dest_id.id, }) lines.append((0, 0, data)) return lines def create_lines_by_location(self, cr, uid, ids, lot_rng, context=None): lines = [] obj_loc = self.pool.get('tcv.stock.by.location.report') obj_wiz = self.pool.get('tcv.internal.move.wiz.lines') loc_data_id = obj_loc.create( cr, uid, {'location_id': lot_rng.location_id.id, 'date': lot_rng.date, }, context) obj_loc.button_load_inventory(cr, uid, loc_data_id, context=context) loc_brw = obj_loc.browse(cr, uid, loc_data_id, context=context) for line in loc_brw.line_ids: data = obj_wiz.get_lot_data( cr, uid, ids, line.prod_lot_id.id, context=None) data.update( {'location_dest_id': lot_rng.location_dest_id.id, }) lines.append((0, 0, data)) return lines def create_lines_by_bundle(self, cr, uid, ids, lot_rng, context=None): lines = [] obj_wiz = self.pool.get('tcv.internal.move.wiz.lines') for line in lot_rng.bundle_id.line_ids: data = obj_wiz.get_lot_data( cr, uid, ids, line.prod_lot_id.id, context=None) data.update( {'location_dest_id': lot_rng.location_dest_id.id, }) lines.append((0, 0, data)) return lines def create_wizard_lines(self, cr, uid, ids, lot_rng, context=None): lines = [] if lot_rng.type == 'range' and lot_rng.prod_lot_id.name.isdigit() \ and lot_rng.item_qty: lines = self.create_lines_by_range( cr, uid, ids, lot_rng, context=context) elif lot_rng.type == 'location': lines = self.create_lines_by_location( cr, uid, ids, lot_rng, context=context) elif lot_rng.type == 'bundle': lines = self.create_lines_by_bundle( cr, uid, ids, lot_rng, context=context) return lines ##-------------------------------------------------------- buttons (object) def button_done(self, cr, uid, ids, context=None): context = context or {} ids = isinstance(ids, (int, long)) and [ids] or ids if context.get('active_model') == 'tcv.internal.move.wiz' and \ context.get('active_ids'): lot_rng = self.browse(cr, uid, ids, context={})[0] obj_wiz = self.pool.get('tcv.internal.move.wiz') #~ obj_brw = obj_wiz.browse(cr, uid, ids[0], context=context) lines = self.create_wizard_lines( cr, uid, ids, lot_rng, context=context) if lines: obj_wiz.write(cr, uid, context.get('active_ids'), {'line_ids': lines}, context) return {'type': 'ir.actions.act_window_close'} ##------------------------------------------------------------ on_change... def on_change_prod_lot_id(self, cr, uid, ids, prod_lot_id): res = {} if not prod_lot_id: return res obj_lot = self.pool.get('stock.production.lot') lot = obj_lot.browse(cr, uid, prod_lot_id, context=None) res.update({'product_id': lot.product_id.id}) res = {'value': res} return res def on_change_bundle_id(self, cr, uid, ids, bundle_id): res = {} if bundle_id: obj_bun = self.pool.get('tcv.bundle') bun = obj_bun.browse(cr, uid, bundle_id, context=None) if bun.location_id: res.update({'location_dest_id': bun.location_id.id}) return {'value': res}
class inherits(osv.osv): _name = 'product.product' _description = 'product.product' _inherit = "product.product" _columns = { 'gii_cc': fields.char('Course Code', size=64, required=False, readonly=False), 'gii_ver': fields.char('Version', size=64, required=False, readonly=False), 'gii_effect': fields.date('Effective Date', size=64, required=False, readonly=False), 'gii_with': fields.date('Withdrawn Date', size=64, required=False, readonly=False), 'gii_with': fields.date('Withdrawn Date', size=64, required=False, readonly=False), 'gii_language': fields.many2one('gii.language', 'Language', ondelete='set null'), 'gii_reccomended_study': fields.integer('Recommended Study Hours', size=64, required=False, readonly=False), 'gii_minimum_attendance': fields.integer('Min Attendance Rate Required', size=64, required=False, readonly=False), 'gii_glh': fields.integer('GLH', size=64, required=False, readonly=False), 'gii_qf_id': fields.many2one('gii.qflevel', 'QF Level', ondelete='set null'), 'gii_name': fields.text('Reccomended for', size=64, required=False, readonly=False), 'gii_lo': fields.text('Learning Objectives', size=64, required=False, readonly=False), 'gii_credit_id': fields.one2many('gii.accreditations', 'product_id', 'Accreditations'), 'gii_grading_id': fields.one2many('gii.grading', 'product_id', 'Grading'), 'gii_events_id': fields.one2many('event.event', 'productid_event', 'Events'), 'gii_fees_id': fields.one2many('gii.fee', 'product_id', 'Fees'), 'gii_resources_id': fields.one2many('gii.resources', 'product_id', 'Resources'), 'gii_coursetutors_id': fields.one2many('gii.coursetutors', 'product_id', 'Course Tutors'), 'gii_assmnt_id': fields.many2one('gii.assessment', 'Assesment Type', ondelete='set null'), 'gii_target_id': fields.many2one('gii.target', 'Target Audience', ondelete='set null'), 'gii_awardingbody_id': fields.many2one('test', 'Awarding Body', required=True, ondelete='set null'), 'gii_qualification_id': fields.many2one('gii.qualification', 'Qualification', required=True, ondelete='set null') }
class shipping_general_payment(osv.osv): def _amount_paid(self, cr, uid, ids, name, args, context=None): vals = {} paid_cash = 0.0 for advanced in self.browse(cr, uid, ids): for cash in advanced.cash_line_ids: paid_cash += cash.amount paid_total = paid_cash vals[advanced.id] = { "paid_cash": paid_cash, "paid_total": paid_total, } return vals def _remaining(self, cr, uid, ids, name, args, context=None): vals = {} for pay_receive in self.browse(cr, uid, ids, context=context): tot_adv = pay_receive.cash_total return vals _name = "shipping.general.payment" _description = "Shipping General Payment Received" _columns = { 'name': fields.char('Name', size=16), 'origin': fields.char('Original', size=50), 'invoice': fields.char('Invoice', size=50), 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'journal_id': fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'cash_line_ids': fields.one2many('payment.move.line', 'general_payment_id', 'Payment Lines', readonly=True, states={'draft': [('readonly', False)]}), 'journal_entry_id': fields.many2one('account.move', 'Journal Entry', readonly=True), 'doc_date': fields.date('Doc Date', required=True, select=True, help="Effective date for accounting entries", readonly=True, states={'draft': [('readonly', False)]}), 'auto_posted': fields.boolean( 'Auto Posted', readonly=True, states={'draft': [('readonly', False)]}, help= "Check this box if you want to post the Journal Entry automatically." ), 'paid_cash': fields.function(_amount_paid, method=True, string='Paid Cash', type='float', multi="amount_paid"), 'paid_total': fields.function(_amount_paid, method=True, string='Paid Total', type='float', multi="amount_paid"), 'amount_total': fields.float('Amount Total'), 'amount_currency': fields.float( 'Amount Currency', help="The amount expressed in an optional other currency."), 'currency_id': fields.many2one('res.currency', 'Currency'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'debit_account_id': fields.many2one('account.account', 'Debit'), 'credit_account_id': fields.many2one('account.account', 'Credit'), 'state': fields.selection([('draft', 'Draft'), ('paid', 'Paid'), ('cancel', 'Cancel')], 'State', readonly=True, size=32), 'ref': fields.char('Reference', size=16), 'resource': fields.char('Resource', size=50), 'notes': fields.char( 'Notes', size=300, ), 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted': [('readonly', True)]}), } _defaults = { 'name': '/', 'state': 'draft', 'period_id': _get_period, 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse( cr, uid, uid, c).company_id.id, } def create(self, cr, uid, vals, context=None): if vals.get('name', '/') == '/': vals['name'] = self.pool.get('ir.sequence').get( cr, uid, 'shipping.general.payment') or '/' return super(shipping_general_payment, self).create(cr, uid, vals, context=context) def button_validate_payment(self, cr, uid, ids, context=None): if context is None: context = {} self.create_payment_move_lines(cr, uid, ids, context=context) if self.test_paid(cr, uid, ids, context=context): self.write(cr, uid, ids, {'state': 'paid'}, context=context) return True def create_payment_move_lines(self, cr, uid, ids, context=None): move_pool = self.pool.get('account.move') period_pool = self.pool.get('account.period') account_journal_pool = self.pool.get('account.journal.mapping') journal_pool = self.pool.get('account.journal') account_pool = self.pool.get('account.account') cur_obj = self.pool.get('res.currency') timenow = time.strftime('%Y-%m-%d') for payment in self.browse(cr, uid, ids, context=context): journal_obj = payment.journal_id line_ids = [] period_id = payment.period_id.id journal_id = payment.journal_id.id name = payment.name move = { 'narration': payment.notes, 'date': payment.doc_date, 'ref': payment.ref, 'journal_id': journal_obj.id, 'period_id': period_id, } company = self.pool.get('res.users').browse(cr, uid, uid).company_id debit_account_id = payment.debit_account_id.id credit_account_id = payment.credit_account_id.id amount_total = 0 amount_currency = 0 amount_currency_total = 0 for line in payment.cash_line_ids: if line.currency_id.id != company.currency_id.id: amount_currency = line.amount amt = cur_obj.compute( cr, uid, journal_obj.default_debit_account_id.currency_id.id, journal_obj.default_debit_account_id.company_id. currency_id.id, amount_currency, context=context) else: amt = line.amount amount_currency_total += amount_currency amount_total += amt if debit_account_id: debit_line = (0, 0, { 'name': payment.name, 'date': payment.doc_date or timenow, 'partner_id': False, 'account_id': debit_account_id, 'journal_id': journal_id, 'period_id': period_id, 'debit': amt > 0.0 and amt or 0.0, 'credit': amt < 0.0 and -amt or 0.0, 'amount_currency': amount_currency, }) line_ids.append(debit_line) if credit_account_id: credit_line = (0, 0, { 'name': payment.name, 'date': payment.doc_date or timenow, 'account_id': credit_account_id, 'journal_id': journal_id, 'period_id': period_id, 'amount_currency': amount_currency_total, 'debit': amount_total < 0.0 and -amount_total or 0.0, 'credit': amount_total > 0.0 and amount_total or 0.0, }) line_ids.append(credit_line) move.update({'line_id': line_ids}) move_id = move_pool.create(cr, uid, move, context=context) return True def button_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'cancel'}, context=context) return True def test_paid(self, cr, uid, ids, context=None): """Payment is paid when the sum of amount total equal to paid amount @return: True """ for payment in self.browse(cr, uid, ids, context=context): if payment.cash_line_ids and not payment.amount_total: return True if payment.cash_line_ids and ( abs(payment.amount_total - payment.paid_total) > 0.00001): return False return True def action_view_payment(self, cr, uid, payment_ids, context=None): ''' This function returns an action that display existing invoices of given sales order ids. It can either be a in a list or in a form view, if there is only one invoice to show. ''' mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') result = mod_obj.get_object_reference( cr, uid, 'container_management', 'action_shipping_general_payment') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] #choose the view_mode accordingly if len(payment_ids) > 1: result['domain'] = "[('id','in',[" + ','.join(map( str, payment_ids)) + "])]" else: res = mod_obj.get_object_reference( cr, uid, 'container_management', 'view_shipping_general_payment_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = payment_ids and payment_ids[0] or False return result def print_report(self, cr, uid, ids, context=None): company = self.pool.get('res.users').browse(cr, uid, uid).company_id comm_obj = self.browse(cr, uid, ids[0], context=context) report_param = { 'company_name': company and company.name or '', 'address': company.partner_id.complete_address, 'tel_fax': company and "Tel/Fax: %s , %s " % (company.phone and company.phone or '', company.fax and company.fax or ''), 'invoice_id': ids[0], } return { 'type': 'ir.actions.report.xml', 'report_name': 'general.receipt.invoice', 'datas': { 'parameters': report_param }, }
class sale_shop(osv.osv): _inherit = "sale.shop" _columns = { 'instance_id': fields.many2one('sales.channel.instance', 'Instance', readonly=True), 'last_update_order_date': fields.date('Last Update order Date'), 'prefix': fields.char('Prefix', size=64), 'suffix': fields.char('suffix', size=64), 'last_update_order_status_date': fields.datetime('Start Update Status Date'), 'last_export_stock_date': fields.datetime('Last Exported Stock Date'), 'last_export_price_date': fields.datetime('Last Exported Price Date'), 'last_import_order_date': fields.datetime('Last Imported Order Date'), 'sale_channel_shop': fields.boolean('Sales channel shop'), 'tax_include': fields.boolean('Cost Price Include Taxes'), 'picking_policy': fields.selection( [('direct', 'Deliver each product when available'), ('one', 'Deliver all products at once')], 'Shipping Policy', help= """Pick 'Deliver each product when available' if you allow partial delivery.""" ), 'order_policy': fields.selection([ ('manual', 'On Demand'), ('picking', 'On Delivery Order'), ('prepaid', 'Before Delivery'), ], 'Create Invoice'), 'shop_address': fields.many2one('res.partner', 'Shop Address'), 'alloc_type': fields.selection([('fixed', 'Fixed'), ('per', 'Percentage')], 'Type'), 'alloc_value': fields.float('Value') } #***************Update Order Status******************** def update_order_status(self, cr, uid, ids, context={}): log_obj = self.pool.get('ecommerce.logs') log_vals = {} try: shop_obj = self.browse(cr, uid, ids[0]) if shop_obj.instance_id.module_id == 'oeoo_amazon': self.update_amazon_order_status(cr, uid, ids, context=context) if shop_obj.instance_id.module_id == 'ebay_teckzilla': self.update_ebay_order_status(cr, uid, ids, context=context) if shop_obj.instance_id.module_id == 'magento_teckzilla': self.update_magento_order_status(cr, uid, ids, context=context) self.write( cr, uid, shop_obj.id, {'last_update_order_status_date': datetime.datetime.now()}) log_vals = { 'activity': 'update_order_status', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'SucessFull' } except Exception as e: log_vals = { 'activity': 'update_order_status', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Failed ' + str(e) } log_obj.create(cr, uid, log_vals) return True #***************Export price******************** def export_price(self, cr, uid, ids, context={}): print "======innnnnn export price========>" log_obj = self.pool.get('ecommerce.logs') log_vals = {} try: shop_obj = self.browse(cr, uid, ids[0]) if shop_obj.amazon_shop: self.export_amazon_price(cr, uid, ids, context) if shop_obj.ebay_shop: self.export_stock_and_price(cr, uid, ids, context=context) if shop_obj.magento_shop: self.export_stock_and_price(cr, uid, ids, context=context) self.write(cr, uid, shop_obj.id, {'last_export_price_date': datetime.datetime.now()}) log_vals = { 'activity': 'export_price', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Successful' } except Exception as e: log_vals = { 'activity': 'import_orders', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Failed ' + str(e) } log_obj.create(cr, uid, log_vals) return True #**************Stock Function*********************** #***************Export Stock******************** def export_stock(self, cr, uid, ids, context={}): print "======innnnnn export stock========>" log_obj = self.pool.get('ecommerce.logs') log_vals = {} try: shop_obj = self.browse(cr, uid, ids[0]) print "=======shop_obj.instance_id.module_id==========", shop_obj.instance_id.module_id if shop_obj.instance_id.module_id == 'oeoo_amazon': self.export_amazon_stock(cr, uid, ids, context) if shop_obj.instance_id.module_id == 'ebay_teckzilla': self.export_stock_and_price(cr, uid, ids, context=context) if shop_obj.instance_id.module_id == 'magento_teckzilla': self.export_magento_stock(cr, uid, ids, context=context) self.write(cr, uid, shop_obj.id, {'last_export_stock_date': datetime.datetime.now()}) log_vals = { 'activity': 'export_stock', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Successful' } except Exception as e: log_vals = { 'activity': 'import_orders', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Failed ' + str(e) } log_obj.create(cr, uid, log_vals) return True #**************Orders Function*********************** #***************Import Orders******************** def import_orders(self, cr, uid, ids, context={}): print "======innnnnn main import Orders========>" log_obj = self.pool.get('ecommerce.logs') log_vals = {} # try: shop_obj = self.browse(cr, uid, ids[0]) if shop_obj.instance_id.module_id == 'oeoo_amazon': self.import_amazon_orders(cr, uid, ids, context=context) print "============shop_obj.instance_id.module_id==========>", shop_obj.instance_id.module_id if shop_obj.instance_id.module_id == 'ebay_teckzilla': self.import_ebay_orders(cr, uid, ids, context=context) if shop_obj.instance_id.module_id == 'magento_teckzilla': self.import_magento_orders(cr, uid, ids, context=context) self.write( cr, uid, shop_obj.id, { 'last_import_order_date': time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) }) log_vals = { 'activity': 'import_orders', 'start_datetime': context.get('from_date', False), 'end_datetime': datetime.datetime.now(), 'shop_id': ids[0], 'message': 'Successful' } # except Exception as e: # log_vals = { # 'activity': 'import_orders', # 'start_datetime': context.get('from_date',False), # 'end_datetime': datetime.datetime.now(), # 'shop_id': ids[0], # 'message':'Failed ' + str(e) # } log_obj.create(cr, uid, log_vals) return True def manageCountryCode(self, cr, uid, id, country_code, context): cr.execute( "SELECT id from res_country WHERE lower(name) = %s or lower(code) in %s", (country_code.lower(), (country_code.lower(), country_code[:2].lower()))) res = cr.fetchall() print "country res: ", res if not res: country_id = self.pool.get('res.country').create( cr, uid, { 'code': country_code[:2].upper(), 'name': country_code.title() }, context) else: country_id = res[0][0] return country_id def manageStateCode(self, cr, uid, id, state_code, country_id, context): state_name = re.sub('[^a-zA-Z ]*', '', state_code.upper()) print "state_name: ", state_name cr.execute( "SELECT id from res_country_state WHERE lower(name) = %s or lower(code) in %s AND country_id=%s", (state_name.lower(), (state_name.lower(), state_name[:3].lower()), country_id)) res = cr.fetchall() print "state res: ", res if not res: state_id = self.pool.get('res.country.state').create( cr, uid, { 'country_id': country_id, 'name': state_name.title(), 'code': state_name[:3].upper() }, context) else: state_id = res[0][0] return state_id def updatePartnerInvoiceAddress(self, cr, uid, id, resultvals, context={}): partneradd_obj = self.pool.get('res.partner') if resultvals.get('BillingCountryCode', False): country_id = self.manageCountryCode( cr, uid, id, resultvals['BillingCountryCode'], context) else: return False if resultvals.get('BillingStateOrRegion', False): state_id = self.manageStateCode(cr, uid, id, resultvals['BillingStateOrRegion'], country_id, context) else: state_id = False addressvals = { 'name': resultvals['BillingName'], 'street': resultvals.get('BillingAddressLine1', False), 'street2': resultvals.get('BillingAddressLine2', False), 'city': resultvals.get('BillingCity', False), 'country_id': country_id, 'state_id': state_id, 'phone': resultvals.get('BillingPhone', False), 'zip': resultvals.get('BillingPostalCode', False), 'email': resultvals.get('BillingEmail', False), 'type': 'invoice', } if context.get('shoppartnerinvoiceaddrvals', False): addressvals.update(context['shoppartnerinvoiceaddrvals']) print "addressvals: ", addressvals partnerinvoice_ids = partneradd_obj.search( cr, uid, [('name', '=', resultvals['BillingName']), ('street', '=', resultvals.get('BillingAddressLine1') and resultvals['BillingAddressLine1'] or ''), ('zip', '=', resultvals.get('BillingPostalCode') and resultvals['BillingPostalCode'] or '')]) if partnerinvoice_ids: partnerinvoice_id = partnerinvoice_ids[0] partneradd_obj.write(cr, uid, partnerinvoice_id, addressvals) else: partnerinvoice_id = partneradd_obj.create(cr, uid, addressvals) return partnerinvoice_id def updatePartnerShippingAddress(self, cr, uid, id, resultvals, context={}): partneradd_obj = self.pool.get('res.partner') if resultvals.get('ShippingCountryCode', False): country_id = self.manageCountryCode( cr, uid, id, resultvals['ShippingCountryCode'], context) else: return False if resultvals.get('ShippingStateOrRegion', False): state_id = self.manageStateCode( cr, uid, id, resultvals['ShippingStateOrRegion'], country_id, context) else: state_id = 0 addressvals = { 'name': resultvals['ShippingName'], 'street': resultvals.get('ShippingAddressLine1', False), 'street2': resultvals.get('ShippingAddressLine2', False), 'city': resultvals.get('ShippingCity', False), 'country_id': country_id, 'state_id': state_id, 'phone': resultvals.get('ShippingPhone', False), 'zip': resultvals.get('ShippingPostalCode', False), 'email': resultvals.get('ShippingEmail', False), 'type': 'delivery', } if context.get('shoppartnershippingaddrvals', False): addressvals.update(context['shoppartnershippingaddrvals']) print "addressvals: ", addressvals partnershippingadd_ids = partneradd_obj.search( cr, uid, [('name', '=', resultvals['ShippingName']), ('street', '=', resultvals.get('ShippingAddressLine1') and resultvals['ShippingAddressLine1'] or ''), ('zip', '=', resultvals.get('ShippingPostalCode') and resultvals['ShippingPostalCode'] or '')]) if partnershippingadd_ids: partnershippingadd_id = partnershippingadd_ids[0] partneradd_obj.write(cr, uid, partnershippingadd_id, addressvals) else: partnershippingadd_id = partneradd_obj.create(cr, uid, addressvals) return partnershippingadd_id def import_listing(self, cr, uid, ids, shop_id, product_id, resultvals, context={}): return True def createAccountTax(self, cr, uid, ids, value, context={}): accounttax_obj = self.pool.get('account.tax') accounttax_id = accounttax_obj.create( cr, uid, { 'name': 'Sales Tax(' + str(value) + '%)', 'amount': float(value) / 100, 'type_tax_use': 'sale' }) print 'createAccountTax id: ', accounttax_id return accounttax_id def computeTax(self, cr, uid, id, resultval, context): tax_id = [] if float(resultval.get('ItemTax', 0.0)) > 0.0: if resultval.get('ItemTaxPercentage', False): ship_tax_vat = float(resultval['ItemTaxPercentage']) / 100.00 ship_tax_percent = float(resultval['ItemTaxPercentage']) else: ship_tax_vat = float(resultval['ItemTax']) / float( resultval['ItemPrice']) ship_tax_percent = float(resultval['ItemTax']) / float( resultval['ItemPrice']) * 100.00 acctax_id = self.pool.get('account.tax').search( cr, uid, [('type_tax_use', '=', 'sale'), ('amount', '>=', ship_tax_vat - 0.001), ('amount', '<=', ship_tax_vat + 0.001)]) print "acctax_id: ", acctax_id if not acctax_id: acctax_id = self.createAccountTax(cr, uid, id, ship_tax_percent, context) tax_id = [(6, 0, [acctax_id])] else: tax_id = [(6, 0, [acctax_id[0]])] return tax_id def createProduct(self, cr, uid, id, shop_id, product_details, context={}): ## Logic for creating products in OpenERP ###Getting Product Category prodtemp_obj = self.pool.get('product.template') prod_obj = self.pool.get('product.product') template_vals = { 'list_price': product_details.get('ItemPrice', 0.00), 'purchase_ok': 'TRUE', 'sale_ok': 'TRUE', 'name': product_details['Title'], 'type': 'consu', 'procure_method': 'make_to_stock', 'cost_method': 'average', 'standard_price': 0.00, 'categ_id': context['default_product_category'], 'weight_net': product_details.get('ItemWeight', 0.00), } print "template_vals: ", template_vals template_id = prodtemp_obj.create(cr, uid, template_vals, context) product_vals = { 'product_tmpl_id': template_id, 'default_code': product_details.get('SellerSKU', '').strip() } print "=======product_vals===========>", product_vals if context.get('shopproductsvals', False): ordervals.update(context['shopproductsvals']) print "product_vals: ", product_vals prod_id = prod_obj.create(cr, uid, product_vals, context) return prod_id def oe_status(self, cr, uid, ids, resultval): saleorder_obj = self.pool.get('sale.order') order = saleorder_obj.browse(cr, uid, ids) wf_service = netsvc.LocalService('workflow') print ")))))))))))))))))))))))))))", resultval.get( 'confirm'), resultval.get('paid', False) if resultval.get('confirm', False): print wf_service.trg_validate(uid, 'sale.order', ids, 'order_confirm', cr) invoice_ids = self.pool.get('account.invoice').search( cr, uid, [('origin', '=', order.name)]) print "==========invoice_ids==========>", invoice_ids if len(invoice_ids): print wf_service.trg_validate(uid, 'account.invoice', invoice_ids[0], 'invoice_open', cr) if resultval.get('paid', False): print self.pool.get( 'account.invoice').invoice_pay_customer( cr, uid, [invoice_ids[0]], context={}) return True def manageSaleOrderLine(self, cr, uid, id, shop_id, saleorderid, resultval, context): saleorder_obj = self.pool.get('sale.order') saleorderline_obj = self.pool.get('sale.order.line') product_obj = self.pool.get('product.product') saleorderlineid = False # cr.execute("SELECT * FROM product_product WHERE substring(trim(product_sku),1,9) = %s and active=True",(resultval['SellerSKU'][:9],)) # product_ids = filter(None, map(lambda x: x[0], cr.fetchall())) # print "base_ecommerce/sale.py > manageSaleOrderLine() product_ids: ",product_ids product_ids = product_obj.search( cr, uid, [('default_code', '=', resultval['SellerSKU'])]) if not product_ids: product_id = self.createProduct(cr, uid, id, shop_id, resultval, context) else: product_id = product_ids[0] ### Account Tax - Needs to be tested if not context.get('create_tax_product_line', False): tax_id = self.computeTax( cr, uid, id, resultval, context) if float(resultval['ItemTax']) > 0.00 else False else: tax_id = False product = product_obj.browse(cr, uid, product_id) orderlinevals = { 'order_id': saleorderid, 'product_uom_qty': resultval['QuantityOrdered'], 'product_uom': product.product_tmpl_id.uom_id.id, 'name': product.product_tmpl_id.name, 'price_unit': float(resultval['ItemPrice']), # 'delay' : product.product_tmpl_id.sale_delay, 'invoiced': False, 'state': 'confirmed', 'product_id': product_id, 'tax_id': tax_id, 'type': 'make_to_stock', 'unique_sales_line_rec_no': resultval['unique_sales_line_rec_no'] } if context.get('shoporderlinevals', False): orderlinevals.update(context['shoporderlinevals']) print "orderlinevals: ", orderlinevals if resultval.get('listing_id', False): self.import_listing(cr, uid, id, shop_id, product_id, resultval, context={}) '''### Check if there is no line is_line_order = len(saleorder_obj.browse(cr,uid,saleorderid).order_line) ### Check if order_id was created in same import only if order has >= 1 lines if is_line_order: cr.execute("SELECT id from sale_order WHERE id=%s AND import_unique_id =%s",(saleorderid, context.get('import_unique_id','')),) saleorderids = filter(None, map(lambda x: x[0], cr.fetchall())) if not len(saleorderids): print"manageSaleOrderLine import_unique_id different" return True ### Check if line with same unique_sales_line_rec_no/product_id already exist if context.get('orderline_search_clause',False): context['orderline_search_clause'].append(('order_id','=',saleorderid),) saleorderlineids = saleorderline_obj.search(cr,uid,context['orderline_search_clause']) or [] # cr.execute("SELECT l.id from sale_order s, sale_order_line l WHERE l.order_id=s.id AND s.id=%s AND l.unique_sales_line_rec_no=%s", (saleorderid,context['orderline_search_clause'],)) else: cr.execute("SELECT l.id from sale_order s, sale_order_line l WHERE l.order_id=s.id AND s.id=%s AND l.product_id=%s", (saleorderid,product_id,)) saleorderlineids = filter(None, map(lambda x: x[0], cr.fetchall())) if len(saleorderlineids): print"manageSaleOrderLine line already exist" return saleorderlineids[0] else: ### If no line, then update import_unique_id to current one saleorder_obj.write(cr,uid,saleorderid,{'import_unique_id':resultval['import_unique_id']})''' saleorderlineid = saleorderline_obj.create(cr, uid, orderlinevals, context) cr.commit() return saleorderlineid def createShippingProduct(self, cr, uid, id, context={}): prod_obj = self.pool.get('product.product') prodcateg_obj = self.pool.get('product.category') categ_id = prodcateg_obj.search(cr, uid, [('name', '=', 'Service')]) if not categ_id: categ_id = prodcateg_obj.create(cr, uid, { 'name': 'Service', 'type': 'normal' }, context) else: categ_id = categ_id[0] prod_id = prod_obj.create( cr, uid, { 'type': 'service', 'name': 'Shipping and Handling', 'default_code': context['shipping_product_default_code'], 'categ_id': categ_id }, context) # print "createEbayShippingProduct id: ",prod_id return prod_id def manageSaleOrderLineShipping(self, cr, uid, id, shop_id, saleorderid, resultval, context): saleorderline_obj = self.pool.get('sale.order.line') product_obj = self.pool.get('product.product') ## Shipping Service prod_shipping_id = product_obj.search( cr, uid, [('default_code', '=', context['shipping_product_default_code'])]) if not prod_shipping_id: prod_shipping_id = self.createShippingProduct(cr, uid, id, context) else: prod_shipping_id = prod_shipping_id[0] print "prod_shipping_id: ", prod_shipping_id shipping_price = resultval.get('ShippingPrice', 0.00) shiplineids = saleorderline_obj.search( cr, uid, [('order_id', '=', saleorderid), ('product_id', '=', prod_shipping_id)]) print 'shipping_price Before', shipping_price if shiplineids: shipping_price = float(shipping_price) + float( saleorderline_obj.browse(cr, uid, shiplineids[0]).price_unit) print 'shipping_price After', shipping_price saleorderline_obj.write(cr, uid, shiplineids[0], {'price_unit': shipping_price}) return shiplineids[0] product = product_obj.browse(cr, uid, prod_shipping_id) shiporderlinevals = { 'order_id': saleorderid, 'product_uom_qty': 1, 'product_uom': product.product_tmpl_id.uom_id.id, 'name': product.product_tmpl_id.name, 'price_unit': shipping_price, # 'delay' : product.product_tmpl_id.sale_delay, 'invoiced': False, 'state': 'confirmed', 'product_id': prod_shipping_id, 'type': 'make_to_stock', } print "shiporderlinevals: ", shiporderlinevals shiplineid = saleorderline_obj.create(cr, uid, shiporderlinevals, context) cr.commit() return shiplineid def manageSaleOrder(self, cr, uid, id, shop_id, resultval, context): saleorder_obj = self.pool.get('sale.order') shop_obj = self.pool.get('sale.shop') partner_obj = self.pool.get('res.partner') payment_method_obj = self.pool.get('payment.method') payment_id = False if isinstance(shop_id, (int, long)): shop = shop_obj.browse(cr, uid, shop_id) else: shop = shop_id print "=====shop_id==$$$$$$$$=====>", shop print "**********resultval**************", resultval print "(((((((((((((", resultval[ 'OrderId'], shop.prefix, shop.suffix, shop.name if context.get('order_search_clause', False): saleorderids = saleorder_obj.search(cr, uid, context['order_search_clause']) else: saleorderids = saleorder_obj.search( cr, uid, [('name', '=', shop.prefix + resultval['OrderId'] + shop.suffix), ('shop_id', '=', shop.id)]) print "base_ecommerce/sale => manageSaleOrder() saleorderids: ", saleorderids if saleorderids: saleorder = saleorder_obj.browse(cr, uid, saleorderids[0]) if saleorder.invoiced: return False else: return saleorderids[0] partnerinvoiceaddress_id = self.updatePartnerInvoiceAddress( cr, uid, id, resultval) or False partner_id = partnerinvoiceaddress_id partnershippingaddress_id = self.updatePartnerShippingAddress( cr, uid, id, resultval) or False if not partner_id or not (partnershippingaddress_id or partnerinvoiceaddress_id): print "Invalid Partner Information!!!!!!!!!" ## Skip it since the address info is wrong return False pricelist_id = partner_obj.browse( cr, uid, partner_id)['property_product_pricelist'].id # carrier_ids = resultval.get('Carrier') and self.pool.get('delivery.carrier').search(cr,uid,[(context['shipping_code_key'],'=',resultval['Carrier'])]) # if not carrier_ids: # carrier_ids = resultval.get('Carrier') and self.pool.get('delivery.carrier').search(cr,uid,[('name','=',resultval['Carrier'])]) # carrier_id = carrier_ids[0] if carrier_ids else False carrier_id = False if context.get('date_format', False): date_order = time.strptime(resultval['PurchaseDate'], context['date_format']) date_order = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", date_order) else: date_order = resultval['PurchaseDate'] if resultval.get('PaymentMethod', False) and resultval['PaymentMethod'] != 'None': payment_ids = payment_method_obj.search( cr, uid, [('name', '=', resultval['PaymentMethod'])]) if payment_ids: payment_id = payment_ids[0] else: payment_id = payment_method_obj.create( cr, uid, { 'name': resultval['PaymentMethod'], 'code': resultval['PaymentMethod'] }) # print "resultval['PaymentMethod']: ",resultval['PaymentMethod'] ordervals = { 'name': resultval['OrderId'], 'picking_policy': shop.picking_policy or 'direct', 'order_policy': shop.order_policy or 'picking', 'partner_order_id': partnerinvoiceaddress_id, 'partner_invoice_id': partnerinvoiceaddress_id, 'date_order': date_order, 'shop_id': shop.id, 'partner_id': partner_id, 'user_id': uid, 'partner_shipping_id': partnershippingaddress_id, 'shipped': False, 'state': 'draft', # 'invoice_quantity' : shop.invoice_quantity, 'pricelist_id': pricelist_id, 'payment_method_id': payment_id, 'carrier_id': carrier_id or False, 'unique_sales_rec_no': resultval.get('unique_sales_rec_no', False), 'is_waiting_for_shipment': context.get('waiting_for_shipment', False), } if context.get('shopordervals', False): ordervals.update(context['shopordervals']) saleorderid = saleorder_obj.create(cr, uid, ordervals, context) message = _('SaleOrder %s created successfully' % ((shop.prefix or '') + resultval['OrderId'] + (shop.suffix or ''))) self.log(cr, uid, shop_id, message) cr.commit() return saleorderid def createOrderIndividual(self, cr, uid, id, shop_id, resultval, context={}): print "========shop_id=====>", shop_id saleorder_obj = self.pool.get('sale.order') saleorderid = self.manageSaleOrder(cr, uid, id, shop_id, resultval, context) print "createOrderIndividual saleorderid: ", saleorderid if not saleorderid: return False if saleorder_obj.browse(cr, uid, saleorderid).state == 'draft': ### Order has been reversed bcoz in Sales order it comes in right order if resultval.get( 'ShippingPrice', False) and float(resultval['ShippingPrice']) > 0.00: self.manageSaleOrderLineShipping(cr, uid, id, shop_id, saleorderid, resultval, context) if resultval.get('ItemTax', False) and float( resultval['ItemTax']) > 0.00 and context.get( 'create_tax_product_line', False): self.manageSaleOrderLineTax(cr, uid, id, shop_id, saleorderid, resultval, context) saleorderlineid = self.manageSaleOrderLine(cr, uid, id, shop_id, saleorderid, resultval, context) print "createOrderIndividual saleorderlineid: ", saleorderlineid cr.commit() return saleorderid def handleMissingOrders(self, cr, uid, shop_id, missed_resultvals, context={}): shop_obj = self.pool.get('sale.shop') company_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.id defaults = {'company_id': company_id} count = 0 while (missed_resultvals): count = count + 1 ### count is to make sure loop doesn't go into endless iteraiton if count > 3: break resultvals = missed_resultvals[:] prev_order_id = False prev_order_paid = False for resultval in resultvals: resultval = self.get_payment_method(cr, uid, shop_id, resultval) if not resultval.get('SellerSKU', False): continue # try: saleorderid = self.createOrderIndividual( cr, uid, id, shop_id, resultval, context) print "saleorderid: ", saleorderid if not saleorderid: continue prev_order_id = saleorderid prev_order_paid = resultval['paid'] missed_resultvals.remove(resultval) # except Exception, e: # print "handleMissingOrders Exception: ",e # if str(e).find('concurrent update') != -1: # cr.rollback() # message = _("ImportLog Exception handleMissingOrders '%s': %s") % (str(e),resultval['OrderId'],) # shop_obj.log(cr, uid, shop_id, message) # cr.commit() # continue self.oe_status(cr, uid, saleorderid, resultval) cr.commit() return True def get_payment_method(self, cr, uid, shop, resultval): print "=====resultval============>", resultval pay_obj = self.pool.get('ecommerce.payment.method') pay_ids = pay_obj.search(cr, uid, [('shop_id', '=', shop.id)]) resultval.update({'confirm': False}) resultval.update({'order_policy': shop.order_policy}) print "=====resultval============>", resultval for pay in pay_obj.browse(cr, uid, pay_ids): methods = (pay.name).split(',') payment_method = resultval.get( 'PaymentMethod', False) and resultval['PaymentMethod'] or '' if payment_method in methods: resultval.update({'paid': pay.pay_invoice}) resultval.update({'confirm': pay.val_order}) resultval.update({'order_policy': pay.order_policy}) break print "*****************************************************************" print "======payment_method============>", payment_method print "=======resultval['paid']========>", resultval['paid'] print "======= resultval['confirm']========>", resultval['confirm'] print "======= resultval['order_policy']=======>", resultval[ 'order_policy'] print "*****************************************************************" return resultval # def createOrder(self, cr, uid, shop, resultvals, context={}): # sale_order_obj = self.pool.get('sale.order') # saleorderid = False # company_id = self.pool.get('res.users').browse(cr,uid,uid).company_id.id # defaults = {'company_id':company_id} # ## self.create_order_info(cr,uid,shop_id,context) # prev_order_id = False # prev_order_paid = False # missed_resultvals = [] # missed_order_ids = [] # # for resultval in resultvals: # resultval = self.get_payment_method(cr, uid, shop, resultval) # context['import_type'] = 'api' # print "=====resultval=^^^^^^^^^^^^^^^^^^^**********************======>",resultval # if not resultval.get('SellerSKU',False): # continue # context['waiting_for_shipment'] = False ## try: # saleorderid = self.createOrderIndividual(cr,uid,id,shop.id,resultval,context) # # if not saleorderid: # continue # self.oe_status(cr, uid, saleorderid, resultval) # cr.commit() # # ## except Exception, e: ## print "base_ecommerce/sale.py createOrderDirect Exception: ",e ## if str(e).find('concurrent update') != -1: ## missed_resultvals.append(resultval) ## missed_order_ids.append(resultval['OrderId']) ## cr.rollback() ## continue ## cr.rollback() ## message = _("ImportLog Exception createOrderDirect for '%s': %s") % (str(e),resultval['OrderId'],) ### shop_obj.log(cr, uid, shop_id, message) ## cr.commit() # # # print "createOrderDirect missed_resultvals: ",missed_resultvals # # self.handleMissingOrders(cr,uid,shop.id,missed_resultvals,context) # # return True def createOrder(self, cr, uid, id, shop_id, resultvals, context={}): print "inside shoperp_instance createOrder" saleorderid = False order_data = [] context['import_type'] = 'api' missed_resultvals = [] missed_order_ids = [] for resultval in resultvals: if isinstance(shop_id, (int, long)): shop_id = self.browse(cr, uid, shop_id) resultval = self.get_payment_method(cr, uid, shop_id, resultval) if not resultval.get('SellerSKU', False): continue saleorderid = self.createOrderIndividual(cr, uid, id, shop_id, resultval, context) print "saleorderid: ", saleorderid if not saleorderid: continue order_data.append({'id': saleorderid, 'resultval': resultval}) cr.commit() # except Exception, e: # print "base_ecommerce_connector/shoperp_instance.py createOrder Exception: ",e # if str(e).find('concurrent update') != -1: # missed_resultvals.append(resultval) # missed_order_ids.append(resultval['OrderId']) # cr.rollback() # continue # message = _("ImportLog Exception createOrder for '%s': %s") % (str(e),resultval['OrderId'],) # shop_obj.log(cr, uid, shop_id, message) order_ids = [] for saleorderid in order_data: try: self.oe_status(cr, uid, saleorderid['id'], saleorderid['resultval']) order_ids.append(saleorderid['id']) cr.commit() except Exception, e: print "base_ecomerce_connector/shooperp_instance.py createOrder oe_status Exception: ", e cr.rollback() message = _( "ImportLog Exception createOrder oe_status for '%s': %s" ) % ( str(e), resultval['OrderId'], ) # shop_obj.log(cr, uid, shop_id, message) cr.commit() continue print "createOrderDirect missed_resultvals: ", missed_resultvals self.handleMissingOrders(cr, uid, shop_id, missed_resultvals, context) return order_ids
class account_loan_bank_cheque(osv.osv): _name = 'account.loan.bank.cheque' _description = 'Bank Account Cheque' _rec_name = 'code' _columns = { 'loan_id': fields.many2one('account.loan', 'Loan', required=False), 'code': fields.char('Code', size=32, required=True), 'name': fields.char('Name', size=32, required=True), 'partner_id': fields.many2one('res.partner', 'Customer', required=True), 'loan_bank_id': fields.many2one('res.partner.bank', 'Bank', required=True), 'loan': fields.float('Loan Amount', size=32), 'interest': fields.float('Interest Amount', size=32), 'cheque_amount': fields.float('Cheque Amount', size=32, required=True), 'account_id': fields.many2one('account.account', 'General Account', required=True, select=True), 'state': fields.selection([('draft', 'Draft'), ('posted', 'Posted'), ('clear', 'Clear'), ('return', 'Return'), ('cancel', 'Cancel'), ('done', 'Done')], 'State', readonly=True, select=True), 'date': fields.date('Date', required=True), 'clear_date': fields.date('Cheque Clearing Date', required=False, readonly=True), 'return_date': fields.date('Cheque Return Date', required=False, readonly=True), 'note': fields.text('Notes'), 'cheque_id': fields.one2many('account.loan.installment', 'cheque_id', 'Installments'), 'voucher_id': fields.many2one('account.voucher', 'Voucher', readonly=True), } _defaults = { 'state': lambda *a: 'draft', 'date': lambda *a: time.strftime('%Y-%m-%d'), } def onchange_bank_id(self, cr, uid, ids, part): val = {'loan_bank_id': False, 'account_id': False, 'loan_id': False} if not part: return {'value': val} else: bank_ids = self.pool.get('res.partner.bank').search( cr, uid, [('partner_id', '=', part)]) loan_ids = self.pool.get('account.loan').search( cr, uid, [('partner_id', '=', part)]) obj = self.pool.get('account.loan').browse(cr, uid, part) bank_acc = obj.bank_acc.id if loan_ids.__len__() > 0: val['loan_id'] = loan_ids[0] if bank_ids.__len__() > 0: acc_ids = self.pool.get('account.account').search( cr, uid, [('id', '=', bank_acc)]) if acc_ids: val['loan_bank_id'] = bank_ids[0] val['account_id'] = acc_ids[0] return {'value': val} else: val['loan_bank_id'] = bank_ids[0] return {'value': val} else: return {'value': val} def post_bank(self, cr, uid, ids, context={}): res = False invoices = {} invoice_ids = [] def make_voucher(loan): b = loan.partner_id.property_account_payable.id ln_id = loan.loan_id int_acc = ln_id.int_acc.id cus_acc = ln_id.cus_pay_acc.id create_ids = [] inv_id = self.pool.get('account.voucher.line').create( cr, uid, { 'partner_id': loan.partner_id.id, 'name': loan.name, 'amount': loan.loan, 'account_id': cus_acc, 'type': 'cr' }) inv_id1 = self.pool.get('account.voucher.line').create( cr, uid, { 'partner_id': loan.partner_id.id, 'name': loan.name, 'amount': loan.interest, 'account_id': int_acc, 'type': 'cr' }) create_ids.append(inv_id1) create_ids.append(inv_id) inv = { 'name': loan.loan_id.loan_id, 'type': 'bank_rec_voucher', 'account_id': loan.account_id.id, 'narration': loan.name, 'payment_ids': [(6, 0, create_ids)], 'date': loan.date } inv_obj = self.pool.get('account.voucher') inv_id = inv_obj.create(cr, uid, inv) for o in self.pool.get('account.loan').browse(cr, uid, ids): self.write(cr, uid, [o.id], {'voucher_id': inv_id}) return inv_id for o in self.pool.get('account.loan.bank.cheque').browse( cr, uid, ids): res = make_voucher(o) voucher_dict = { 'draft': ['open_voucher', 'proforma_voucher'], 'proforma': ['proforma_voucher'] } voucher_pool = self.pool.get('account.voucher') for this_obj in self.browse(cr, uid, ids): voucher_obj = this_obj.voucher_id and this_obj.voucher_id or False voucher_state = voucher_obj and voucher_obj.state or False if voucher_state and voucher_state in voucher_dict: for voucher_method in voucher_dict[voucher_state]: getattr(voucher_pool, voucher_method)(cr, uid, [this_obj.voucher_id.id], context=context) move_ids = voucher_obj and [x.id for x in voucher_obj.move_ids] or [] if move_ids: self.pool.get('account.move.line').write( cr, uid, move_ids, {'acc_loan_id': this_obj.loan_id.id}) return res def cheque_return(self, cr, uid, ids, context={}): for o in self.pool.get('account.loan.bank.cheque').browse( cr, uid, ids): self.write(cr, uid, [o.id], {'return_date': time.strftime('%Y-%m-%d')}) res = False invoices = {} invoice_ids = [] def make_voucher(loan): b = loan.partner_id.property_account_payable.id ln_id = loan.loan_id int_acc = ln_id.int_acc.id cus_acc = ln_id.cus_pay_acc.id create_ids = [] inv_id = self.pool.get('account.voucher.line').create( cr, uid, { 'partner_id': loan.partner_id.id, 'name': loan.name, 'amount': loan.loan, 'account_id': cus_acc, 'type': 'dr' }) inv_id1 = self.pool.get('account.voucher.line').create( cr, uid, { 'partner_id': loan.partner_id.id, 'name': loan.name, 'amount': loan.interest, 'account_id': int_acc, 'type': 'dr' }) create_ids.append(inv_id1) create_ids.append(inv_id) inv = { 'name': loan.loan_id.loan_id, 'type': 'bank_pay_voucher', 'account_id': loan.account_id.id, 'narration': loan.name, 'payment_ids': [(6, 0, create_ids)], 'date': loan.date } inv_obj = self.pool.get('account.voucher') inv_id = inv_obj.create(cr, uid, inv) for o in self.pool.get('account.loan').browse(cr, uid, ids): self.write(cr, uid, [o.id], {'voucher_id': inv_id}) return inv_id for o in self.pool.get('account.loan.bank.cheque').browse( cr, uid, ids): res = make_voucher(o) voucher_dict = { 'draft': ['open_voucher', 'proforma_voucher'], 'proforma': ['proforma_voucher'] } voucher_pool = self.pool.get('account.voucher') for this_obj in self.browse(cr, uid, ids): voucher_obj = this_obj.voucher_id and this_obj.voucher_id or False voucher_state = voucher_obj and voucher_obj.state or False if voucher_state and voucher_state in voucher_dict: for voucher_method in voucher_dict[voucher_state]: getattr(voucher_pool, voucher_method)(cr, uid, [this_obj.voucher_id.id], context=context) move_ids = voucher_obj and [x.id for x in voucher_obj.move_ids] or [] if move_ids: self.pool.get('account.move.line').write( cr, uid, move_ids, {'acc_loan_id': this_obj.loan_id.id}) return res def cheque_clear(self, cr, uid, ids, context={}): res = False for o in self.pool.get('account.loan.bank.cheque').browse( cr, uid, ids): self.write(cr, uid, [o.id], {'clear_date': time.strftime('%Y-%m-%d')})
except: if not crm_case_id: # TODO schedule a retry (ir.cron) return False return True def _valid_get(self, cr, uid, ids, field_name, arg, context=None): res = {} for contract in self.browse(cr, uid, ids, context=context): res[contract.id] = ("unvalid", "valid")[contract.date_stop >= time.strftime('%Y-%m-%d')] return res _columns = { 'name' : fields.char('Contract ID', size=256, required=True, readonly=True), 'password' : fields.char('Password', size=64, invisible=True, required=True, readonly=True), 'date_start' : fields.date('Starting Date', readonly=True), 'date_stop' : fields.date('Ending Date', readonly=True), 'module_ids' : fields.many2many('maintenance.contract.module', 'maintenance_contract_module_rel', 'contract_id', 'module_id', 'Covered Modules', readonly=True), 'state' : fields.function(_valid_get, method=True, string="State", type="selection", selection=[('valid', 'Valid'),('unvalid', 'Unvalid')], readonly=True), 'kind' : fields.selection([('full', 'Full'),('partial', 'Partial')], 'Kind', required=True, readonly=True), } _defaults = { 'password' : lambda obj,cr,uid,context={} : '', } _sql_constraints = [ ('uniq_name', 'unique(name)', "Your maintenance contract is already subscribed in the system !") ] maintenance_contract()
class res_partner_contact(osv.osv): """ Partner Contact """ _name = "res.partner.contact" _description = "Contact" def _main_job(self, cr, uid, ids, fields, arg, context=None): """ @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of partner contact’s IDs @fields: Get Fields @param context: A standard dictionary for contextual values @param arg: list of tuples of form [(‘name_of_the_field’, ‘operator’, value), ...]. """ res = dict.fromkeys(ids, False) res_partner_job_obj = self.pool.get('res.partner.job') all_job_ids = res_partner_job_obj.search(cr, uid, []) all_job_names = dict(zip(all_job_ids, res_partner_job_obj.name_get(cr, uid, all_job_ids, context=context))) for contact in self.browse(cr, uid, ids, context=context): if contact.job_ids: res[contact.id] = all_job_names.get(contact.job_ids[0].id, False) return res _columns = { 'name': fields.char('Last Name', size=64, required=True), 'first_name': fields.char('First Name', size=64), 'mobile': fields.char('Mobile', size=64), 'title': fields.many2one('res.partner.title','Title'), 'website': fields.char('Website', size=120), 'lang_id': fields.many2one('res.lang', 'Language'), 'job_ids': fields.one2many('res.partner.job', 'contact_id', 'Functions and Addresses'), 'country_id': fields.many2one('res.country','Nationality'), 'birthdate': fields.date('Birth Date'), 'active': fields.boolean('Active', help="If the active field is set to False,\ it will allow you to hide the partner contact without removing it."), 'partner_id': fields.related('job_ids', 'address_id', 'partner_id', type='many2one',\ relation='res.partner', string='Main Employer'), 'function': fields.related('job_ids', 'function', type='char', \ string='Main Function'), 'job_id': fields.function(_main_job, method=True, type='many2one',\ relation='res.partner.job', string='Main Job'), 'email': fields.char('E-Mail', size=240), 'comment': fields.text('Notes', translate=True), 'photo': fields.binary('Image'), } _defaults = { 'active' : lambda *a: True, } _order = "name,first_name" def name_get(self, cr, user, ids, context=None): """ will return name and first_name....... @param self: The object pointer @param cr: the current row, from the database cursor, @param user: the current user’s ID for security checks, @param ids: List of create menu’s IDs @return: name and first_name @param context: A standard dictionary for contextual values """ if not len(ids): return [] res = [] for contact in self.browse(cr, user, ids, context=context): _contact = "" if contact.title: _contact += "%s "%(contact.title.name) _contact += contact.name or "" if contact.name and contact.first_name: _contact += " " _contact += contact.first_name or "" res.append((contact.id, _contact)) return res def name_search(self, cr, uid, name='', args=None, operator='ilike', context=None, limit=None): if not args: args = [] if context is None: context = {} if name: ids = self.search(cr, uid, ['|',('name', operator, name),('first_name', operator, name)] + args, limit=limit, context=context) else: ids = self.search(cr, uid, args, limit=limit, context=context) return self.name_get(cr, uid, ids, context=context)
class aging_report_wizard(osv.osv_memory): _name = "aging.report.wizard" _columns = { "account_type": fields.selection([('receivable', 'Account Receivable'), ('payable', 'Account Payable')], "Account Type", required=True), "as_on_date": fields.date('As On Date', required=True), "journal_ids": fields.many2many("account.journal", "aging_report_wizard_rel_journal", "ageing_id", "journal_id", "Filter Journals"), "account_ids": fields.many2many("account.account", "aging_report_wizard_rel_account", "ageing_id", "account_id", "Filter Accounts"), "show_outstanding_advance": fields.boolean('Show Outstanding Advance?'), "adv_account_id": fields.many2one("account.account", "Advance Account", domain=[('type', '=', 'receivable')]), "period_length": fields.integer("Period Length (days)", required=True), "partner_ids": fields.many2many( "res.partner", "aging_report_wizard_rel_partner", "wizard_id", "partner_id", "Filter Partners", ), } _defaults = { "account_type": lambda self, cr, uid, context: context.get('account_type', 'receivable' ), "as_on_date": lambda *a: time.strftime("%Y-%m-%d"), "period_length": lambda *n: 10, } def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False): if context is None: context = {} res = super(aging_report_wizard, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) for field in res['fields']: if field == 'journal_ids': if context.get('account_type', False) and context.get( 'account_type', False) == 'receivable': res['fields'][field]['domain'] = [ ('type', 'in', ['sale', 'sale_refund', 'situation']) ] if context.get('account_type', False) and context.get( 'account_type', False) == 'payable': res['fields'][field]['domain'] = [('type', 'in', [ 'purchase', 'purchase_refund', 'situation', 'general' ])] return res def print_report(self, cr, uid, ids, context={}): datas = { 'ids': context.get('active_ids', []), 'model': 'aging.report.wizard', 'form': self.read(cr, uid, ids)[0], } return { 'type': 'ir.actions.report.xml', 'report_name': 'aging.report', 'report_type': 'webkit', 'datas': datas, }
class oehealth_borderaux(osv.Model): _name = 'oehealth.borderaux' _description = "Borderaux" def _compute_create_uid(self, cr, uid, ids, field_name, arg, context={}): result = {} for r in self.browse(cr, uid, ids, context=context): perms = self.perm_read(cr, uid, ids) create_uid = perms[0].get('create_uid', 'n/a') result[r.id] = create_uid return result def _compute_create_date(self, cr, uid, ids, field_name, arg, context={}): result = {} for r in self.browse(cr, uid, ids, context=context): perms = self.perm_read(cr, uid, ids) create_date = perms[0].get('create_date', 'n/a') result[r.id] = create_date return result def _compute_write_uid(self, cr, uid, ids, field_name, arg, context={}): result = {} for r in self.browse(cr, uid, ids, context=context): perms = self.perm_read(cr, uid, ids) write_uid = perms[0].get('write_uid', 'n/a') result[r.id] = write_uid return result def _compute_write_date(self, cr, uid, ids, field_name, arg, context={}): result = {} for r in self.browse(cr, uid, ids, context=context): perms = self.perm_read(cr, uid, ids) write_date = perms[0].get('write_date', 'n/a') result[r.id] = write_date return result _columns = { 'name': fields.char(string='Borderaux', size=64, required=True), 'pharmacy': fields.char('Pharmacy Name', size=254), 'pharmacy_id': fields.many2one('oehealth.pharmacy', 'Pharmacy'), 'authorizations': fields.integer('Authorizations'), 'refund_value': fields.float('Refund Value'), 'refund_data': fields.date('Refund Data'), 'borderaux_total': fields.float('Borderaux Total'), 'category_ids': fields.many2many('oehealth.borderaux.category', 'oehealth_borderaux_category_rel', 'borderaux_id', 'category_id', 'Categories'), 'tag_ids': fields.many2many('oehealth.tag', 'oehealth_borderaux_tag_rel', 'borderaux_id', 'tag_id', 'Tags'), 'borderaux_info': fields.text(string='Info'), 'annotation_ids': fields.one2many('oehealth.annotation', 'borderaux_id', 'Annotations'), 'state': fields.selection([('new', 'New'), ('revised', 'Revised'), ('waiting', 'Waiting'), ('okay', 'Okay')], 'Stage', readonly=True), 'active': fields.boolean( 'Active', help= "The active field allows you to hide the borderaux without removing it." ), 'create_uid': fields.function( _compute_create_uid, method=True, type='char', string='Create User', ), 'create_date': fields.function( _compute_create_date, method=True, type='datetime', string='Create Date', ), 'write_uid': fields.function( _compute_write_uid, method=True, type='char', string='Write User', ), 'write_date': fields.function( _compute_write_date, method=True, type='datetime', string='Write Date', ), } _order = 'name' _sql_constraints = [('name_uniq', 'unique(name)', u'Duplicated Borderaux!') ] _defaults = { 'active': 1, 'state': 'new', } def oehealth_borderaux_new(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'new'}) return True def oehealth_borderaux_revised(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'revised'}) return True def oehealth_borderaux_waiting(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'waiting'}) return True def oehealth_borderaux_okay(self, cr, uid, ids): self.write(cr, uid, ids, {'state': 'okay'}) return True
class kg_esi_pdf(osv.osv_memory): _name = 'kg.esi.pdf' _columns = { 'filter': fields.selection([('filter_date', 'Date')], "Filter by", required=True), 'date_from': fields.date("Start Date"), 'date_to': fields.date("End Date"), 'pay_sch': fields.selection([('5th', '5th Pay Day'), ('7th', '7th Pay Day')], 'PaySchedule Selection', required=True), 'company_id': fields.many2one('res.company', 'Company') } def _get_last_month_first(self, cr, uid, context=None): today = lastdate.date.today() first = lastdate.date(day=1, month=today.month, year=today.year) mon = today.month - 1 if mon == 0: mon = 12 else: mon = mon tot_days = calendar.monthrange(today.year, mon)[1] test = first - lastdate.timedelta(days=tot_days) res = test.strftime('%Y-%m-%d') return res def _get_last_month_end(self, cr, uid, context=None): today = lastdate.date.today() first = lastdate.date(day=1, month=today.month, year=today.year) last = first - lastdate.timedelta(days=1) res = last.strftime('%Y-%m-%d') return res _defaults = { 'filter': 'filter_date', 'date_from': _get_last_month_first, 'date_to': _get_last_month_end, 'pay_sch': '7th', 'company_id': lambda self, cr, uid, c: self.pool.get('res.company'). _company_default_get(cr, uid, 'kg.esi.pdf', context=c), } def _date_validation_check(self, cr, uid, ids, context=None): for val_date in self.browse(cr, uid, ids, context=context): if val_date.date_from <= val_date.date_to: return True return False _constraints = [ (_date_validation_check, 'You must select an correct Start Date and End Date !!', ['Valid_date']), ] def _build_contexts(self, cr, uid, ids, data, context=None): if context is None: context = {} result = {} result['date_from'] = 'date_from' in data['form'] and data['form'][ 'date_from'] or False result['date_to'] = 'date_to' in data['form'] and data['form'][ 'date_to'] or False if data['form']['filter'] == 'filter_date': result['date_from'] = data['form']['date_from'] result['date_to'] = data['form']['date_to'] return result def date_indian_format(self, date_pyformat): date_contents = date_pyformat.split("-") date_indian = date_contents[2] + "/" + date_contents[ 1] + "/" + date_contents[0] return date_indian def check_report(self, cr, uid, ids, context=None): if context is None: context = {} data = {} data['ids'] = context.get('active_ids', []) data['model'] = context.get('active_model', 'ir.ui.menu') data['form'] = self.read(cr, uid, ids, [])[0] used_context = self._build_contexts(cr, uid, ids, data, context=context) data['form']['used_context'] = used_context return self._print_report(cr, uid, ids, data, context=context) def pre_print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data['form'].update(self.read(cr, uid, ids, [], context=context)[0]) return data def _print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = self.pre_print_report(cr, uid, ids, data, context=context) data['form'].update(self.read(cr, uid, ids)[0]) if data['form']: date_from = data['form']['date_from'] date_from = (datetime.datetime.strptime(date_from, '%Y-%m-%d')) data['form']['month'] = date_from.strftime('%B-%Y') company_id = data['form']['company_id'][0] com_rec = self.pool.get('res.company').browse(cr, uid, company_id) data['form']['company'] = com_rec.name if data['form']['pay_sch'] == '5th': data['form']['pay'] = '5th Pay Day' else: data['form']['pay'] = '7th Pay Day' return { 'type': 'ir.actions.report.xml', 'report_name': 'kg.esi.pdf.report', 'datas': data }
class sale_order(osv.osv): _inherit="sale.order" def _amount_in_words(self, cr, uid, ids, name, arg, context=None): res = {} for order in self.browse(cr, uid, ids, context=context): a='' b='' if order.currency_id.name == 'INR': a = 'Rupees' b = '' res[order.id] = amount_to_text(order.roundoff_grand_total, 'en', a).replace('and Zero Cent', b).replace('and Zero Cent', b) return res def _total_shipped_quantity(self, cr, uid, ids, field_name, arg, context=None): res = {} for order in self.browse(cr, uid, ids, context=context): val = val1 = 0.0 for line in order.order_line: val1 += line.product_uom_qty res[order.id] = val1 return res def _total_billed_quantity(self, cr, uid, ids, field_name, arg, context=None): res = {} for order in self.browse(cr, uid, ids, context=context): val = 0.0 for line in order.order_line: val += line.product_billed_qty res[order.id] = val return res SELECTION_LIST = [ ('Financial Year(2016-2017)','Financial Year(2016-2017)'), ('Financial Year(2017-2018)','Financial Year(2017-2018)'), ('Financial Year(2018-2019)','Financial Year(2018-2019)'), ('Financial Year(2019-2020)','Financial Year(2019-2020)'), ] def _get_financial_year(self, cr, uid, ids, field_name, arg, context=None): res= {} for x in self.browse(cr, uid, ids): option='' etd_date = x.date_order option1='Financial Year(2016-2017)' option2='Financial Year(2017-2018)' option3='Financial Year(2018-2019)' option4='Financial Year(2019-2020)' if etd_date>='2016-04-01' and etd_date<='2017-03-31': option=option1 if etd_date>='2017-04-01' and etd_date<='2018-03-31': option=option2 if etd_date>='2018-04-01' and etd_date<='2019-03-31': option=option3 if etd_date>='2019-04-01' and etd_date<='2020-03-31': option=option4 res[x.id] = option return res _columns={ 'po_date': fields.date("Buyer's PO Date"), 'due_date': fields.date('Payment Due Date',help="Payment Due Date calculation done on the following condition :-\nIf the Customer is Interstate and agreed C-Form then Due Date=Order Date+Payment Term Days+5.\nIf the Customer is Interstate and Disagreed the C-Form or Within the State then Due Date=Order Date+Payment Term Days."), #'destination': fields.many2one('res.city','Destination'), 'destination': fields.char('Destination', size=128), 'client_order_ref': fields.char("Buyer's PO Number", size=128), 'dispatch_source': fields.many2one('dispatch.through','Dispatch Through'), ##############Shipping Address fields 'shipping_street': fields.char('Shipping Street',size=128), 'shipping_street2': fields.char('Shipping Street2',size=128), 'shipping_city': fields.many2one('res.city','Shipping Cities'), 'shipping_state_id': fields.many2one('res.country.state',' Shipping State'), 'shipping_zip': fields.char('Shipping Zip',size=24), 'shipping_country_id': fields.many2one('res.country','Shipping Country'), 'shipping_destination': fields.char('Shipping Destination', size=128), 'shipping_contact_person': fields.many2one('res.partner', 'Contact Person'), 'shipping_contact_mobile_no': fields.char('Mobile Number',size=68), 'shipping_contact_landline_no': fields.char('Landline Number',size=68), 'shipping_email_id': fields.char('Email ID',size=68), ##################Billing Address fields 'billing_street': fields.char('Billing Street',size=128), 'billing_street2': fields.char('Billing Street2',size=128), 'billing_city': fields.many2one('res.city','Billing Cities'), 'billing_state_id': fields.many2one('res.country.state','Billing State'), 'billing_zip': fields.char('Billing Zip',size=24), 'billing_country_id': fields.many2one('res.country','Billing Country'), 'billing_destination': fields.char('Billing Destination',size=128), 'billing_contact_person': fields.many2one('res.partner', 'Contact Person'), 'billing_contact_mobile_no': fields.char('Mobile Number',size=68), 'billing_contact_landline_no': fields.char('Landline Number',size=68), 'billing_email_id': fields.char('Email ID',size=68), #####################Display total amount_totalt in words 'amount_total_in_words': fields.function(_amount_in_words, string='Total amount in word', type='char', size=128), 'total_shipped_quantity': fields.function(_total_shipped_quantity, string='Total Shipped Quantity', type='integer',digits_compute= dp.get_precision('Product UoS')), 'total_billed_quantity': fields.function(_total_billed_quantity, string='Total Billed Quantity', type='integer',digits_compute= dp.get_precision('Product UoS')), #####################Display the Financial Year 'financial_year': fields.function(_get_financial_year, type='selection',method=True,selection=SELECTION_LIST, string="Financial Year"), 'order_policy': fields.selection([ ('manual', 'On Demand'), ('picking', 'On Delivery Order'), ('prepaid', 'Before Delivery'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""On demand: A draft invoice can be created from the sales order when needed. \nOn delivery order: A draft invoice can be created from the delivery order when the products have been delivered. \nBefore delivery: A draft invoice is created from the sales order and must be paid before the products can be delivered."""), 'created_delivery_order': fields.boolean('Created Delivery Order'), 'po_attachment': fields.binary('Attach PO', required=True) } def onchange_billing_contact_person(self,cr,uid,ids,billing_contact_person): v={} res_partner_obj=self.pool.get('res.partner') if billing_contact_person: res_partner_browse = res_partner_obj.browse(cr,uid,billing_contact_person) v['billing_contact_mobile_no'] = res_partner_browse.mobile v['billing_contact_landline_no'] = res_partner_browse.phone v['billing_email_id'] = res_partner_browse.email return {'value':v} def onchange_shipping_contact_person(self,cr,uid,ids,shipping_contact_person): v={} res_partner_obj=self.pool.get('res.partner') if shipping_contact_person: res_partner_browse = res_partner_obj.browse(cr,uid,shipping_contact_person) v['shipping_contact_mobile_no'] = res_partner_browse.mobile v['shipping_contact_landline_no'] = res_partner_browse.phone v['shipping_email_id'] = res_partner_browse.email return {'value':v} def onchange_partner_id(self, cr, uid, ids, part, context=None): if not part: return {'value': {'partner_invoice_id': False, 'partner_shipping_id': False, 'payment_term': False, 'fiscal_position': False}} added_values_date = '' todays_date =datetime.now().date() date_order = str(todays_date) account_payment_term_line = self.pool.get('account.payment.term.line') part = self.pool.get('res.partner').browse(cr, uid, part, context=context) addr = self.pool.get('res.partner').address_get(cr, uid, [part.id], ['delivery', 'invoice', 'contact']) pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False payment_term = part.property_payment_term and part.property_payment_term.id or False fiscal_position = part.property_account_position and part.property_account_position.id or False dedicated_salesman = part.user_id and part.user_id.id or uid #####################Shipping address############### shipping_street = part.shipping_street shipping_street2 = part.shipping_street2 shipping_city = part.shipping_city2.id shipping_state_id = part.shipping_state_id.id shipping_zip = part.shipping_zip shipping_country_id = part.shipping_country_id.id shipping_destination = part.shipping_destination #####################Billing address################# billing_street = part.street billing_street2 = part.street2 billing_city = part.billing_city.id billing_state_id = part.state_id.id billing_zip = part.zip billing_country_id = part.country_id.id billing_destination = part.billing_destination type_of_sales = part.type_of_sales cform_criteria = part.cform_criteria payment_term = part.property_payment_term.id primary_contact = part.primary_contact billing_contact_person = False shipping_contact_person = False if part.child_ids: for line in part.child_ids: primary_contact = line.primary_contact if primary_contact: billing_contact_person = line.id shipping_contact_person = line.id start_date_day = datetime.strptime(date_order,'%Y-%m-%d') search_account_payment_line = account_payment_term_line.search(cr,uid,[('payment_id','=',payment_term)]) browse_account_payment_line = account_payment_term_line.browse(cr,uid,search_account_payment_line[0]) days = browse_account_payment_line.days grace_days = 5 if type_of_sales == 'interstate' and cform_criteria == 'agreed': if days != 0: new_days = days + grace_days added_value_days = start_date_day+timedelta(days=new_days) added_values_date =str(added_value_days) else: added_values_date = '' elif type_of_sales == 'within_state' or (type_of_sales == 'interstate' and cform_criteria == 'disagreed'): if days != 0: added_value_days = start_date_day+timedelta(days=days) added_values_date =str(added_value_days) else: added_values_date = False val = { 'partner_invoice_id': addr['invoice'], 'partner_shipping_id': addr['delivery'], 'payment_term': payment_term, 'fiscal_position': fiscal_position, 'user_id': dedicated_salesman, 'shipping_contact_person': shipping_contact_person, 'shipping_street': shipping_street, 'shipping_street2': shipping_street2, 'shipping_city': shipping_city, 'shipping_destination': shipping_destination, 'destination': shipping_destination, 'shipping_state_id': shipping_state_id, 'shipping_zip': shipping_zip, 'shipping_country_id': shipping_country_id, 'billing_contact_person': billing_contact_person, 'billing_street': billing_street, 'billing_street2': billing_street2, 'billing_city': billing_city, 'billing_state_id': billing_state_id, 'billing_zip': billing_zip, 'billing_country_id': billing_country_id, 'billing_destination': billing_destination, 'due_date': added_values_date, 'order_policy': 'picking', 'section_id':1, } if pricelist: val['pricelist_id'] = pricelist return {'value': val} def action_wait(self, cr, uid, ids, context=None): context = context or {} for o in self.browse(cr, uid, ids): if not o.order_line: raise osv.except_osv(_('Error!'),_('You cannot confirm a sales order which has no line.')) noprod = self.test_no_product(cr, uid, o, context) if (o.order_policy == 'manual') or noprod: self.write(cr, uid, [o.id], {'state': 'manual', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) else: self.write(cr, uid, [o.id], {'state': 'progress', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) sale_order_number = o.name subscribe_ids = [] zeeva_ind_management = ['nitin','arun'] subscribe_ids += self.pool.get('res.users').search(cr, SUPERUSER_ID, [('login','in',zeeva_ind_management)]) self.message_subscribe_users(cr, SUPERUSER_ID, [o.id], user_ids=subscribe_ids, context=context) # message1 = _("<b>Status: Draft --> Sales Order</b>") # self.message_post(cr, uid, ids, body = message1, type='comment', subtype='mt_comment', context = context) message = _("<b>Status: Draft --> Sales Order</b>,<br/><br/><b>Dear Sir,<br/><br/> The Sale Order %s has been confirmed.</b>") % (sale_order_number) self.message_post(cr, uid, ids, body = message, type='comment', subtype='mt_comment', context = context) self.pool.get('sale.order.line').button_confirm(cr, uid, [x.id for x in o.order_line]) return True def onchange_date_order(self,cr,uid,ids,date_order,payment_term,partner_id): v={} res_partner_obj = self.pool.get('res.partner') search_partner_id =res_partner_obj.search(cr,uid,[('id','=',partner_id)]) browse_partner_line_id = res_partner_obj.browse(cr,uid,search_partner_id) for browse_partner_id in browse_partner_line_id: type_of_sales = browse_partner_id.type_of_sales cform_criteria = browse_partner_id.cform_criteria account_payment_term_line = self.pool.get('account.payment.term.line') if date_order and payment_term: start_date_day = datetime.strptime(date_order,'%Y-%m-%d') search_account_payment_line = account_payment_term_line.search(cr,uid,[('payment_id','=',payment_term)]) browse_account_payment_line = account_payment_term_line.browse(cr,uid,search_account_payment_line[0]) days = browse_account_payment_line.days grace_days = 5 if type_of_sales == 'interstate' and cform_criteria == 'agreed': if days != 0: new_days = days + grace_days added_value_days = start_date_day+timedelta(days=new_days) added_values_date =str(added_value_days) v['due_date'] = added_values_date else: added_values_date = '' v['due_date'] = added_values_date elif type_of_sales == 'within_state' or (type_of_sales == 'interstate' and cform_criteria == 'disagreed'): if days != 0: added_value_days = start_date_day+timedelta(days=days) added_values_date =str(added_value_days) v['due_date'] = added_values_date else: added_values_date = '' v['due_date'] = added_values_date elif not date_order or payment_term: v['due_date'] = '' return {'value':v} def create_delivery_order(self,cr,uid,ids,context=None): result = [] line_order =[] tax_line =[] pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out') stock_obj = self.pool.get('stock.picking.out') stock_move = self.pool.get('stock.move') tax_line = self.pool.get('delivery.tax.summary.report') product_product_obj = self.pool.get('product.product') todays_date = datetime.now() for order in self.browse(cr,uid,ids): partner_id = order.partner_id.id main_form_id = order.id stock_values = { 'name': str(pick_name), 'origin': order.name, 'date': todays_date, 'type': 'out', 'state': 'draft', 'partner_id': order.partner_id.id, 'note': order.note, 'company_id': order.company_id.id, 'po_date': order.po_date, 'due_date': order.due_date, 'delivery_order_ref': order.client_order_ref, 'dispatch_source': order.dispatch_source.id, 'user_id': order.user_id.id, 'payment_term': order.payment_term.id, #############Shipping Address fields 'shipping_street': order.shipping_street, 'shipping_street2': order.shipping_street2, 'shipping_city': order.shipping_city.id, 'shipping_state_id':order.shipping_state_id.id, 'shipping_zip':order.shipping_zip, 'shipping_country_id': order.shipping_country_id.id, 'shipping_destination': order.shipping_destination, 'shipping_contact_person': order.shipping_contact_person.id, 'shipping_contact_mobile_no': order.shipping_contact_mobile_no, 'shipping_contact_landline_no': order.shipping_contact_landline_no, 'shipping_email_id': order.shipping_email_id, 'destination': order.shipping_destination, ##################Billing Address fields 'billing_street': order.billing_street, 'billing_street2': order.billing_street2, 'billing_city': order.billing_city.id, 'billing_state_id': order.billing_state_id.id, 'billing_zip': order.billing_zip, 'billing_country_id': order.billing_country_id.id, 'billing_destination': order.billing_destination, 'billing_contact_person': order.billing_contact_person.id, 'billing_contact_mobile_no': order.billing_contact_mobile_no, 'billing_contact_landline_no': order.billing_contact_landline_no, 'billing_email_id':order.billing_email_id, 'apply_discount': order.apply_discount, 'discount_value': order.discount_value, 'discounted_amount': order.discounted_amount, 'pricelist_id': order.pricelist_id.id, 'stock_journal_id':1, 'so_date':order.date_order, 'po_attachment':order.po_attachment, 'invoice_state': '2binvoiced', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S') } ir_model_data = self.pool.get('ir.model.data') form_res = ir_model_data.get_object_reference(cr, uid, 'stock', 'view_picking_form') form_id = form_res and form_res[1] or False tree_res = ir_model_data.get_object_reference(cr, uid, 'stock', 'view_picking_out_tree') tree_id = tree_res and tree_res[1] or False stock_id =stock_obj.create(cr,uid,stock_values) for line1 in order.tax_lines: tax_line_values = { 'tax_id':line1.tax_id, 'tx_name':line1.tx_name, 'total_amount':line1.total_amount, 'tax_rate':line1.tax_rate, 'stock_taxes_id':stock_id } tax_line_values_create = tax_line.create(cr,uid,tax_line_values) for line in order.order_line: location_id = line.sale_warehouse_id.lot_stock_id.id output_id = line.sale_warehouse_id.lot_output_id.id product_id = line.product_id.id product_product_browse = product_product_obj.browse(cr,uid,product_id).virtual_available # if product_product_browse < 0.00: # raise osv.except_osv(('Warning!!'),('The stock is not available.')) stock_line_values={ 'name': line.name, 'product_id': line.product_id.id, 'product_qty': line.product_uom_qty, 'product_billed_qty': line.product_billed_qty, 'product_uom': line.product_uom.id, 'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty, 'product_uos': (line.product_uos and line.product_uos.id)\ or line.product_uom.id, 'partner_id': line.order_partner_id.id, 'location_id': location_id, 'location_dest_id': output_id, 'tracking_id': False, 'state': 'confirmed', 'company_id': order.company_id.id, 'price_unit': line.price_unit or 0.0, 'delivery_warehouse_id':line.sale_warehouse_id.id, 'sale_price':line.sale_price.id, 'tax_applied_id':line.tax_applied_id.id, 'product_category_id':line.product_category_id.id, 'picking_id':stock_id, 'product_code':line.product_code, } stock_line_values_create = stock_move.create(cr,uid,stock_line_values) self.write(cr,uid,main_form_id,{'created_delivery_order':True}) order.refresh() return { 'name': _('Delivery Order'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'stock.picking.out', 'res_id': stock_id, 'view_id': False, 'views': [(form_id, 'form'), (tree_id, 'tree')], 'context': "{'type': 'out'}", 'type': 'ir.actions.act_window', }
class kg_category_count_wizard(osv.osv_memory): _name = 'kg.category.count.wizard' _columns = { 'product_id': fields.many2many('product.product', 'kg_po_stm_pro', 'order_id', 'product_id', 'Product Name'), 'supplier': fields.many2many('res.partner', 'kg_po_stm_sup', 'order_id', 'supplier_id', 'Supplier'), 'filter': fields.selection([('filter_no', 'No Filters'), ('filter_date', 'Date')], "Filter by", required=True), 'date_from': fields.date("Start Date"), 'date_to': fields.date("End Date"), 'print_date': fields.datetime('Creation Date', readonly=True), 'printed_by': fields.many2one('res.users', 'Printed By', readonly=True), 'user_name': fields.many2one('res.users', 'User'), 'status': fields.selection([('approved', 'Approved'), ('cancelled', 'Cancelled')], "Status", invisible=False), 'company_id': fields.many2one('res.company', 'Company Name'), } _defaults = { 'filter': 'filter_date', 'date_from': time.strftime('%Y-%m-%d'), 'date_to': time.strftime('%Y-%m-%d'), 'print_date': fields.datetime.now, 'printed_by': lambda obj, cr, uid, context: uid, 'company_id': lambda self, cr, uid, c: self.pool.get('res.company'). _company_default_get(cr, uid, 'kg.pi.detail.wizard', context=c), } def _date_validation_check(self, cr, uid, ids, context=None): for val_date in self.browse(cr, uid, ids, context=context): if val_date.date_from <= val_date.date_to: return True return False _constraints = [ (_date_validation_check, 'You must select an correct Start Date and End Date !!', ['Valid_date']), ] def _build_contexts(self, cr, uid, ids, data, context=None): if context is None: context = {} result = {} result['date_from'] = 'date_from' in data['form'] and data['form'][ 'date_from'] or False result['date_to'] = 'date_to' in data['form'] and data['form'][ 'date_to'] or False if data['form']['filter'] == 'filter_date': result['date_from'] = data['form']['date_from'] result['date_to'] = data['form']['date_to'] return result def date_indian_format(self, date_pyformat): date_contents = date_pyformat.split("-") date_indian = date_contents[2] + "/" + date_contents[ 1] + "/" + date_contents[0] return date_indian def check_report(self, cr, uid, ids, context=None): if context is None: context = {} data = {} data['ids'] = context.get('active_ids', []) data['model'] = context.get('active_model', 'ir.ui.menu') data['form'] = self.read(cr, uid, ids, [])[0] used_context = self._build_contexts(cr, uid, ids, data, context=context) data['form']['used_context'] = used_context return self._print_report(cr, uid, ids, data, context=context) def pre_print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data['form'].update(self.read(cr, uid, ids, [], context=context)[0]) return data def _print_report(self, cr, uid, ids, data, context=None): rec = self.browse(cr, uid, ids[0]) if context is None: context = {} data = self.pre_print_report(cr, uid, ids, data, context=context) data['form'].update(self.read(cr, uid, ids[0])) if data['form']: date_from = str(data['form']['date_from']) date_to = str(data['form']['date_to']) data['form']['date_from_ind'] = self.date_indian_format(date_from) data['form']['date_to_ind'] = self.date_indian_format(date_to) company_id = data['form']['company_id'][0] com_rec = self.pool.get('res.company').browse(cr, uid, company_id) data['form']['company'] = com_rec.name data['form']['printed_by'] = rec.printed_by.name if data['form']['status'] == 'approved': data['form']['status_name'] = 'Approved' elif data['form']['status'] == 'cancelled': data['form']['status_name'] = 'Cancelled' else: data['form']['status_name'] = '' if data['form']['user_name']: data['form']['user_name'] = rec.user_name.login else: data['form']['user_name'] = 'Others' cr_date = datetime.strptime(rec.print_date, '%Y-%m-%d %H:%M:%S') date = cr_date.strftime('%d/%m/%Y %H:%M:%S') data['form']['print_date'] = date return { 'type': 'ir.actions.report.xml', 'report_name': 'kg.category.count.report', 'datas': data, 'name': 'Category Count Report' }
class AccountAssetDepreciationLine(orm.Model): _name = 'account.asset.depreciation.line' _description = 'Asset depreciation line' _rec_name = 'depreciation_date' _order = 'asset_id, depreciation_type, depreciation_date' def __init__(self, pool, cr): super(AccountAssetDepreciationLine, self).__init__(pool, cr) cr.execute( "SELECT * FROM pg_proc WHERE proname = 'last' AND proisagg;") if not cr.fetchall(): cr.execute( """-- Create a function that always returns the last non-NULL item CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement ) RETURNS anyelement LANGUAGE sql IMMUTABLE STRICT AS $$ SELECT $2; $$; -- And then wrap an aggregate around it CREATE AGGREGATE public.last ( sfunc = public.last_agg, basetype = anyelement, stype = anyelement );""") def _get_asset_info(self, cr, uid, ids, name, args, context=None): res = {} category_obj = self.pool.get('account.asset.category') company_obj = self.pool.get('res.company') category_by_asset_id = {} fiscalyear_start_day_by_company_id = {} for line in self.browse(cr, uid, ids, context): asset = line.asset_id year = line.depreciation_date[:4] if asset.company_id.id not in fiscalyear_start_day_by_company_id: fiscalyear_start_day_by_company_id[ asset.company_id. id] = company_obj.get_fiscalyear_start_day( cr, uid, asset.company_id.id, context) if line.depreciation_date[5:] < fiscalyear_start_day_by_company_id[ asset.company_id.id]: year = str(int(line.depreciation_date[:4]) + 1) if asset.id not in category_by_asset_id: category_by_asset_id[asset.id] = category_obj.browse( cr, uid, asset.category_id.id, {'force_company': asset.company_id.id}) category = category_by_asset_id[asset.id] if line.depreciation_type == 'accounting': account_id = category.accounting_depreciation_account_id.id if line.depreciation_type == 'fiscal': account_id = asset.company_id.fiscal_depreciation_account_id.id if line.depreciation_type == 'exceptional': account_id = category.exceptional_depreciation_account_id.id res[line.id] = { 'purchase_value': asset.purchase_value, 'salvage_value': asset.salvage_value, 'category_id': asset.category_id.id, 'currency_id': asset.currency_id.id, 'company_id': asset.company_id.id, 'state': asset.state, 'asset_type': asset.asset_type, 'benefit_accelerated_depreciation': asset.benefit_accelerated_depreciation, 'account_id': account_id, 'year': year, 'is_posted': bool(line.move_id), } return res def _get_fiscal_depreciation_info(self, cr, uid, ids, name, args, context=None): res = {} fields_to_read = [ 'depreciation_date', 'asset_id', 'depreciation_value', 'depreciation_type' ] lines = sorted(self.read(cr, uid, ids, fields_to_read, context, '_classic_write'), key=lambda d: d['depreciation_date']) line_ids = [line['id'] for line in lines] fiscal_lines = [ line for line in lines if line['depreciation_type'] == 'fiscal' ] if fiscal_lines: depr_line_ids = self.search( cr, uid, [('asset_id', 'in', [line['asset_id'] for line in fiscal_lines]), ('depreciation_type', '!=', 'exceptional')], context=context) depr_lines = self.read(cr, uid, depr_line_ids, fields_to_read, context, '_classic_write') accounting_lines_by_asset_and_date = {} max_depr_date_by_asset = {} accelerated_amount_by_asset = {} for line in depr_lines: if line['depreciation_type'] == 'accounting': accounting_lines_by_asset_and_date.setdefault( line['asset_id'], {} )[line['depreciation_date']] = line['depreciation_value'] else: if line['id'] not in line_ids: accelerated_amount_by_asset.setdefault( line['asset_id'], 0.0) accelerated_amount_by_asset[ line['asset_id']] += line['depreciation_value'] if line['depreciation_date'] > max_depr_date_by_asset.get( line['asset_id'], ''): max_depr_date_by_asset[ line['asset_id']] = line['depreciation_date'] for line in lines: accounting_value = accelerated_value = 0.0 if line['depreciation_type'] == 'fiscal': accounting_value = accounting_lines_by_asset_and_date.get( line['asset_id'], {}).get(line['depreciation_date'], 0.0) accelerated_value = line[ 'depreciation_value'] - accounting_value if line['depreciation_date'] == max_depr_date_by_asset[ line['asset_id']]: accelerated_value = -accelerated_amount_by_asset.get( line['asset_id'], 0.0) else: accelerated_amount_by_asset.setdefault( line['asset_id'], 0.0) accelerated_amount_by_asset[ line['asset_id']] += accelerated_value res[line['id']] = { 'accounting_value': accounting_value, 'accelerated_value': accelerated_value, } return res def _get_line_ids_from_depreciation_lines(self, cr, uid, ids, context=None): res = [] for line in self.browse(cr, uid, ids, context): if line.depreciation_type != 'exceptional': res.extend([ l.id for l in line.asset_id.depreciation_line_ids if l.depreciation_type == 'fiscal' and not l.is_posted ]) return list(set(res)) def _get_line_ids_from_assets(self, cr, uid, ids, context=None): return sum([ asset['depreciation_line_ids'] for asset in self.read( cr, uid, ids, ['depreciation_line_ids'], context) ], []) def _get_line_ids_from_asset_categories(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] cr.execute( 'SELECT id FROM account_asset_depreciation_line WHERE category_id IN %s', (tuple(ids), )) return [line[0] for line in cr.fetchall()] def _get_line_ids_from_assets_for_account(self, cr, uid, ids, context=None): return self.pool.get('account.asset.depreciation.line').search( cr, uid, [('asset_id', 'in', ids)], context=context) def _get_line_ids_from_asset_categories_for_account( self, cr, uid, ids, context=None): return self.pool.get('account.asset.depreciation.line').search( cr, uid, [('category_id', 'in', ids)], context=context) def _get_line_ids_from_companies_for_account(self, cr, uid, ids, context=None): return self.pool.get('account.asset.depreciation.line').search( cr, uid, [('company_id', 'in', ids)], context=context) def _is_manual(self, cr, uid, ids, name, arg, context=None): # WARNING: method copied in AccountAssetAsset._update_or_create_depreciation_lines res = {} if isinstance(ids, (int, long)): ids = [ids] for line in self.browse(cr, uid, ids, context): res[line.id] = getattr(line.asset_id, '%s_method' % line.depreciation_type) == 'manual' return res def _set_is_posted(self, cr, uid, ids, name, value, arg, context=None): cr.execute( "UDPATE account_asset_depreciation_line SET is_posted = %s WHERE id IN %s", (value, tuple(ids))) return True _columns = { 'asset_id': fields.many2one('account.asset.asset', 'Asset', required=True, ondelete='cascade'), 'depreciation_type': fields.selection([('accounting', 'Accounting'), ('fiscal', 'Fiscal'), ('exceptional', 'Exceptional')], 'Type', required=True, select=True), 'depreciation_date': fields.date('Date', required=True), 'base_value': fields.float('Base Amount', digits_compute=dp.get_precision('Account'), readonly=True), 'previous_years_accumulated_value': fields.float('Previous Years Accumulated Depreciation', digits_compute=dp.get_precision('Account'), readonly=True, group_operator="last"), 'current_year_accumulated_value': fields.float('Current Year Accumulated Depreciation', digits_compute=dp.get_precision('Account'), readonly=True, group_operator="last"), 'depreciation_value': fields.float('Depreciation', digits_compute=dp.get_precision('Account')), 'accumulated_value': fields.float('Accumulated Depreciation', digits_compute=dp.get_precision('Account'), readonly=True), 'exceptional_value': fields.float('Exceptional Depreciation', digits_compute=dp.get_precision('Account'), readonly=True), 'book_value': fields.float('Book value', digits_compute=dp.get_precision('Account'), readonly=True), 'book_value_wo_exceptional': fields.float('Book value at end without exceptional', digits_compute=dp.get_precision('Account'), readonly=True), 'move_id': fields.many2one('account.move', 'Depreciation Entry', ondelete='restrict'), 'accounting_value': fields.function(_get_fiscal_depreciation_info, method=True, type='float', digits_compute=dp.get_precision('Account'), store={ 'account.asset.depreciation.line': (_get_line_ids_from_depreciation_lines, None, 5), }, string='Accounting Depreciation', multi='fiscal_depreciation'), 'accelerated_value': fields.function(_get_fiscal_depreciation_info, method=True, type='float', digits_compute=dp.get_precision('Account'), store={ 'account.asset.depreciation.line': (_get_line_ids_from_depreciation_lines, None, 5), }, string='Accelerated Depreciation', multi='fiscal_depreciation'), 'purchase_value': fields.function(_get_asset_info, method=True, type='float', digits_compute=dp.get_precision('Account'), store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['purchase_value'], 5), }, string="Gross Value", multi="asset_info"), 'salvage_value': fields.function(_get_asset_info, method=True, type='float', digits_compute=dp.get_precision('Account'), store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['salvage_value'], 5), }, string="Salvage Value", multi="asset_info"), 'category_id': fields.function(_get_asset_info, method=True, type='many2one', relation='account.asset.category', store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['category_id'], 5), }, string="Asset Category", ondelete='restrict', multi="asset_info"), 'company_id': fields.function(_get_asset_info, method=True, type='many2one', relation='res.company', string="Company", store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['category_id'], 5), }, ondelete='restrict', multi="asset_info"), 'currency_id': fields.function(_get_asset_info, method=True, type="many2one", relation="res.currency", string="Currency", store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['company_id'], 5), }, ondelete='restrict', multi="asset_info"), 'state': fields.function(_get_asset_info, method=True, type='selection', selection=ASSET_STATES, string="State", store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['state'], 5), }, multi="asset_info"), 'asset_type': fields.function(_get_asset_info, method=True, type='selection', selection=ASSET_TYPES, string="Type", store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, ['asset_type'], 5), }, ondelete='restrict', multi="asset_info"), 'benefit_accelerated_depreciation': fields.function(_get_asset_info, method=True, type='boolean', store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets, [ 'purchase_value', 'salvage_value', 'accounting_method', 'accounting_annuities', 'accounting_rate', 'fiscal_method', 'fiscal_annuities', 'fiscal_rate' ], 5), }, string="Benefit accelerated depreciation", multi="asset_info"), 'year': fields.function(_get_asset_info, method=True, type='char', size=4, string='Year', store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['depreciation_date'], 5), }, multi="asset_info"), 'account_id': fields.function(_get_asset_info, method=True, type='many2one', relation="account.account", store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['asset_id'], 5), 'account.asset.asset': (_get_line_ids_from_assets_for_account, ['category_id'], 5), 'account.asset.category': (_get_line_ids_from_asset_categories_for_account, [ 'accounting_depreciation_account_id', 'exceptional_depreciation_account_id' ], 5), 'res.company': (_get_line_ids_from_companies_for_account, ['fiscal_depreciation_account_id'], 5), }, string="Account", multi="asset_info"), 'is_posted': fields.function(_get_asset_info, fnct_inv=_set_is_posted, method=True, type='boolean', string='Posted Depreciation', store={ 'account.asset.depreciation.line': (lambda self, cr, uid, ids, context=None: ids, ['move_id'], 5), }, multi="asset_info", readonly=True), 'is_manual': fields.function(_is_manual, method=True, type='boolean', string='Manual Depreciation'), } _defaults = { 'depreciation_date': lambda *a: time.strftime('%Y-%m-%d'), 'depreciation_type': 'exceptional', } def check_constraints(self, cr, uid, ids, context=None): # _constraints are too slow if isinstance(ids, (int, long)): ids = [ids] for line in self.browse(cr, uid, ids, context): if line.depreciation_date < line.asset_id.purchase_date: raise orm.except_orm( _('Error'), _('Depreciation date must be after purchase date!')) if line.depreciation_type == 'exceptional': cr.execute( "SELECT id FROM account_period WHERE state='draft' AND date_start <= %s AND date_stop >= %s AND company_id = %s", (line.depreciation_date, line.depreciation_date, line.company_id.id)) res = cr.fetchall() if not res: raise orm.except_orm( _('Error'), _('Depreciation date must be in current fiscal year!')) if line.depreciation_value > line.asset_id.purchase_value: raise orm.except_orm( _('Error'), _('Depreciation value cannot be bigger than gross value!')) if line.book_value > line.book_value_wo_exceptional: raise orm.except_orm( _('Error'), _('Book value with exceptional depreciations cannot be superior to book value ' 'without exceptional depreciations, nor inferior to salvage value!' )) return True def create(self, cr, uid, vals, context=None): context_copy = context and context.copy() or {} context_copy['no_validate'] = True res_id = super(AccountAssetDepreciationLine, self).create(cr, uid, vals, context_copy) self._validate(cr, uid, [res_id], context) return res_id def _validate(self, cr, uid, ids, context=None): context = context or {} if context.get('no_validate'): return super(AccountAssetDepreciationLine, self)._validate(cr, uid, ids, context) self.check_constraints(cr, uid, ids, context) def validate_exceptional_depreciation(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] asset_ids = [ line.asset_id.id for line in self.browse(cr, uid, ids, context) ] return self.pool.get('account.asset.asset').compute_depreciation_board( cr, uid, asset_ids, context) def button_validate_exceptional_depreciation(self, cr, uid, ids, context=None): self.validate_exceptional_depreciation(cr, uid, ids, context) return {'type': 'ir.actions.act_window_close'} def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): context = context or {} if context.get('search_in_current_month'): date_start = datetime.today().strftime('%Y-%m-01') date_stop = (datetime.strptime(date_start, '%Y-%m-%d') + relativedelta(months=1)).strftime('%Y-%m-%d') domain = [ '&', ('depreciation_date', '>=', date_start), ('depreciation_date', '<', date_stop) ] args = args and (['&'] + domain + args) or domain return super(AccountAssetDepreciationLine, self)._search(cr, uid, args, offset, limit, order, context, count, access_rights_uid)
class hr_employee(osv.osv): _name = "hr.employee" _inherit = "hr.employee" _columns = { 'evaluation_plan_id': fields.many2one('hr_evaluation.plan', 'Appraisal Plan'), 'evaluation_date': fields.date( 'Next Appraisal Date', help= "The date of the next appraisal is computed by the appraisal plan's dates (first appraisal + periodicity)." ), } def run_employee_evaluation(self, cr, uid, automatic=False, use_new_cursor=False, context=None): obj_evaluation = self.pool.get('hr_evaluation.evaluation') for id in self.browse(cr, uid, self.search(cr, uid, [], context=context), context=context): if id.evaluation_plan_id and id.evaluation_date: if (parser.parse(id.evaluation_date) + relativedelta( months=int(id.evaluation_plan_id.month_next)) ).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"): self.write( cr, uid, id.id, { 'evaluation_date': (parser.parse(id.evaluation_date) + relativedelta( months=+int(id.evaluation_plan_id.month_next)) ).strftime('%Y-%m-%d') }, context=context) obj_evaluation.create(cr, uid, { 'employee_id': id.id, 'plan_id': id.evaluation_plan_id }, context=context) return True def onchange_evaluation_plan_id(self, cr, uid, ids, evaluation_plan_id, evaluation_date, context=None): if evaluation_plan_id: evaluation_plan_obj = self.pool.get('hr_evaluation.plan') obj_evaluation = self.pool.get('hr_evaluation.evaluation') flag = False evaluation_plan = evaluation_plan_obj.browse(cr, uid, [evaluation_plan_id], context=context)[0] if not evaluation_date: evaluation_date = ( parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months=+evaluation_plan.month_first) ).strftime('%Y-%m-%d') flag = True else: if (parser.parse(evaluation_date) + relativedelta(months=int(evaluation_plan.month_next)) ).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"): evaluation_date = ( parser.parse(evaluation_date) + relativedelta(months=+evaluation_plan.month_next) ).strftime('%Y-%m-%d') flag = True if ids and flag: obj_evaluation.create(cr, uid, { 'employee_id': ids[0], 'plan_id': evaluation_plan_id }, context=context) return {'value': {'evaluation_date': evaluation_date}} def create(self, cr, uid, vals, context=None): id = super(hr_employee, self).create(cr, uid, vals, context=context) if vals.get('evaluation_plan_id', False): self.pool.get('hr_evaluation.evaluation').create( cr, uid, { 'employee_id': id, 'plan_id': vals['evaluation_plan_id'] }, context=context) return id
class hr_anticipo(osv.osv): _name = 'hr.anticipo' _description = 'Anticipos de Nominas' _columns = { 'name': fields.char('Anticipo', size=30), 'employee_id': fields.many2one('hr.employee', 'Empleado', required=True, select="1", readonly=True), 'fecha_anticipo': fields.date('Fecha de Anticipo', select="1", readonly=True), 'cantidad': fields.float('Cantidad Anticipo', digits=(16, 2), readonly=True), 'state': fields.selection( (('borrador', 'Borrador'), ('confirmado', 'Confirmado'), ('pagado', 'Pagado'), ('cancelado', 'Cancelado')), 'Estado de anticipo', readonly=True, select="1"), 'asiento_anticipo': fields.many2one('account.move', 'Asiento Anticipo', readonly=True), } _defaults = { 'state': lambda *a: 'borrador', } def confirmar_anticipo(self, cr, uid, ids, *args): ################################################################## # OBJETOS ################################################################## account_journal_obj = self.pool.get('account.journal') account_period_obj = self.pool.get('account.period') account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') ################################################################## cuentas = get_configuration(cr, uid, ids) for anticipo in self.browse(cr, uid, ids): if anticipo.state != 'borrador': continue journal_id = cuentas['diario_destino'] journal = account_journal_obj.browse(cr, uid, journal_id) fecha_anticipo = anticipo.fecha_anticipo #PERIODO period_ids = account_period_obj.search( cr, uid, [('date_start', '<=', fecha_anticipo or time.strftime('%Y-%m-%d')), ('date_stop', '>=', fecha_anticipo or time.strftime('%Y-%m-%d'))]) if len(period_ids): periodo_id = period_ids[0] referencia = 'Anticipo: ' + anticipo.employee_id.name + ' - ' + fecha_anticipo move_val = { 'ref': referencia, 'journal_id': journal_id, 'date': fecha_anticipo, 'period_id': periodo_id } move_id = account_move_obj.create(cr, uid, move_val) cuenta_anticipos_val = { 'account_id': cuentas['cuenta_anticipos'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Anticipo', 'debit': anticipo.cantidad, 'ref': referencia, } account_move_line_obj.create(cr, uid, cuenta_anticipos_val) cuenta_bancos_val = { 'account_id': cuentas['cuenta_bancos'], 'move_id': move_id, 'journal_id': journal_id, 'period_id': periodo_id, 'name': 'Bancos', 'credit': anticipo.cantidad, 'ref': referencia, } account_move_line_obj.create(cr, uid, cuenta_bancos_val) self.write(cr, uid, ids, { 'state': 'confirmado', 'asiento_anticipo': move_id }) account_move_obj.write(cr, uid, [move_id], {'date': fecha_anticipo}) return True def pagar_anticipo(self, cr, uid, ids, *args): for ant in self.browse(cr, uid, ids): if ant.state != 'confirmado': continue acc_obj = self.pool.get('account.move') acc_obj.post(cr, uid, [ant.asiento_anticipo.id]) self.write(cr, uid, ids, {'state': 'pagado'}) return True def cancelar_anticipo(self, cr, uid, ids, *args): for ant in self.browse(cr, uid, ids): acc_obj = self.pool.get('account.move') if ant.state == 'confirmado': self.write(cr, uid, ids, {'state': 'cancelado'}) return True
class hr_evaluation(osv.osv): _name = "hr_evaluation.evaluation" _description = "Employee Appraisal" _rec_name = 'employee_id' _columns = { 'date': fields.date("Appraisal Deadline", required=True, select=True), 'employee_id': fields.many2one('hr.employee', "Employee", required=True), 'note_summary': fields.text('Appraisal Summary'), 'note_action': fields.text( 'Action Plan', help= "If the evaluation does not meet the expectations, you can propose" + "an action plan"), 'rating': fields.selection( [ ('0', 'Significantly bellow expectations'), ('1', 'Did not meet expectations'), ('2', 'Meet expectations'), ('3', 'Exceeds expectations'), ('4', 'Significantly exceeds expectations'), ], "Appreciation", help="This is the appreciation on that summarize the evaluation"), 'survey_request_ids': fields.one2many('hr.evaluation.interview', 'evaluation_id', 'Appraisal Forms'), 'plan_id': fields.many2one('hr_evaluation.plan', 'Plan', required=True), 'state': fields.selection([ ('draft', 'New'), ('wait', 'Plan In Progress'), ('progress', 'Waiting Appreciation'), ('done', 'Done'), ('cancel', 'Cancelled'), ], 'State', required=True, readonly=True), 'date_close': fields.date('Ending Date', select=True), 'progress': fields.float("Progress"), } _defaults = { 'date': lambda *a: (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months=+1)).strftime('%Y-%m-%d'), 'state': lambda *a: 'draft', } def name_get(self, cr, uid, ids, context=None): if not ids: return [] reads = self.browse(cr, uid, ids, context=context) res = [] for record in reads: name = record.plan_id.name res.append((record['id'], name)) return res def onchange_employee_id(self, cr, uid, ids, employee_id, context=None): evaluation_plan_id = False if employee_id: employee_obj = self.pool.get('hr.employee') for employee in employee_obj.browse(cr, uid, [employee_id], context=context): if employee and employee.evaluation_plan_id and employee.evaluation_plan_id.id: evaluation_plan_id = employee.evaluation_plan_id.id return {'value': {'plan_id': evaluation_plan_id}} def button_plan_in_progress(self, cr, uid, ids, context=None): mail_message = self.pool.get('mail.message') hr_eval_inter_obj = self.pool.get('hr.evaluation.interview') if context is None: context = {} for evaluation in self.browse(cr, uid, ids, context=context): wait = False for phase in evaluation.plan_id.phase_ids: children = [] if phase.action == "bottom-up": children = evaluation.employee_id.child_ids elif phase.action in ("top-down", "final"): if evaluation.employee_id.parent_id: children = [evaluation.employee_id.parent_id] elif phase.action == "self": children = [evaluation.employee_id] for child in children: # if not child.user_id: # continue int_id = hr_eval_inter_obj.create( cr, uid, { 'evaluation_id': evaluation.id, 'survey_id': phase.survey_id.id, 'date_deadline': (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months=+1)).strftime('%Y-%m-%d'), 'user_id': child.user_id.id, 'user_to_review_id': evaluation.employee_id.id }, context=context) if phase.wait: wait = True if not wait: hr_eval_inter_obj.survey_req_waiting_answer( cr, uid, [int_id], context=context) if (not wait) and phase.mail_feature: body = phase.mail_body % { 'employee_name': child.name, 'user_signature': child.user_id.signature, 'eval_name': phase.survey_id.title, 'date': time.strftime('%Y-%m-%d'), 'time': time } sub = phase.email_subject dest = [child.work_email] if dest: mail_message.schedule_with_attach( cr, uid, evaluation.employee_id.work_email, dest, sub, body, context=context) self.write(cr, uid, ids, {'state': 'wait'}, context=context) return True def button_final_validation(self, cr, uid, ids, context=None): request_obj = self.pool.get('hr.evaluation.interview') self.write(cr, uid, ids, {'state': 'progress'}, context=context) for id in self.browse(cr, uid, ids, context=context): if len(id.survey_request_ids) != len( request_obj.search(cr, uid, [('evaluation_id', '=', id.id), ('state', 'in', ['done', 'cancel'])], context=context)): raise osv.except_osv( _('Warning !'), _("You cannot change state, because some appraisal in waiting answer or draft state" )) return True def button_done(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'progress': 1 * 100}, context=context) self.write(cr, uid, ids, { 'state': 'done', 'date_close': time.strftime('%Y-%m-%d') }, context=context) return True def button_cancel(self, cr, uid, ids, context=None): interview_obj = self.pool.get('hr.evaluation.interview') evaluation = self.browse(cr, uid, ids[0], context) interview_obj.survey_req_cancel( cr, uid, [r.id for r in evaluation.survey_request_ids]) self.write(cr, uid, ids, {'state': 'cancel'}, context=context) return True def button_draft(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'draft'}, context=context) return True def write(self, cr, uid, ids, vals, context=None): if 'date' in vals: new_vals = {'date_deadline': vals.get('date')} obj_hr_eval_iterview = self.pool.get('hr.evaluation.interview') for evalutation in self.browse(cr, uid, ids, context=context): for survey_req in evalutation.survey_request_ids: obj_hr_eval_iterview.write(cr, uid, [survey_req.id], new_vals, context=context) return super(hr_evaluation, self).write(cr, uid, ids, vals, context=context)
class accounting_report(osv.osv_memory): _name = "accounting.report" _inherit = "account.common.report" _description = "Accounting Report" _columns = { 'enable_filter': fields.boolean('Enable Comparison'), 'account_report_id': fields.many2one('account.financial.report', 'Account Reports', required=True), 'label_filter': fields.char('Column Label', size=32, help="This label will be displayed on report to show the balance computed for the given comparison filter."), 'fiscalyear_id_cmp': fields.many2one('account.fiscalyear', 'Fiscal Year', help='Keep empty for all open fiscal year'), 'filter_cmp': fields.selection([('filter_no', 'No Filters'), ('filter_date', 'Date'), ('filter_period', 'Periods')], "Filter by", required=True), 'period_from_cmp': fields.many2one('account.period', 'Start Period'), 'period_to_cmp': fields.many2one('account.period', 'End Period'), 'date_from_cmp': fields.date("Start Date"), 'date_to_cmp': fields.date("End Date"), 'debit_credit': fields.boolean('Display Debit/Credit Columns', help="This option allows you to get more details about the way your balances are computed. Because it is space consuming, we do not allow to use it while doing a comparison."), } def _get_account_report(self, cr, uid, context=None): # TODO deprecate this it doesnt work in web menu_obj = self.pool.get('ir.ui.menu') report_obj = self.pool.get('account.financial.report') report_ids = [] if context.get('active_id'): menu = menu_obj.browse(cr, uid, context.get('active_id')).name report_ids = report_obj.search(cr, uid, [('name','ilike',menu)]) return report_ids and report_ids[0] or False _defaults = { 'filter_cmp': 'filter_no', 'target_move': 'posted', 'account_report_id': _get_account_report, } def _build_comparison_context(self, cr, uid, ids, data, context=None): if context is None: context = {} result = {} result['fiscalyear'] = 'fiscalyear_id_cmp' in data['form'] and data['form']['fiscalyear_id_cmp'] or False result['journal_ids'] = 'journal_ids' in data['form'] and data['form']['journal_ids'] or False result['chart_account_id'] = 'chart_account_id' in data['form'] and data['form']['chart_account_id'] or False if data['form']['filter_cmp'] == 'filter_date': result['date_from'] = data['form']['date_from_cmp'] result['date_to'] = data['form']['date_to_cmp'] elif data['form']['filter_cmp'] == 'filter_period': if not data['form']['period_from_cmp'] or not data['form']['period_to_cmp']: raise osv.except_osv(_('Error'),_('Select a starting and an ending period')) result['period_from'] = data['form']['period_from_cmp'] result['period_to'] = data['form']['period_to_cmp'] return result def check_report(self, cr, uid, ids, context=None): if context is None: context = {} res = super(accounting_report, self).check_report(cr, uid, ids, context=context) data = {} data['form'] = self.read(cr, uid, ids, ['account_report_id', 'date_from_cmp', 'date_to_cmp', 'fiscalyear_id_cmp', 'journal_ids', 'period_from_cmp', 'period_to_cmp', 'filter_cmp', 'chart_account_id', 'target_move'], context=context)[0] for field in ['fiscalyear_id_cmp', 'chart_account_id', 'period_from_cmp', 'period_to_cmp', 'account_report_id']: if isinstance(data['form'][field], tuple): data['form'][field] = data['form'][field][0] comparison_context = self._build_comparison_context(cr, uid, ids, data, context=context) res['datas']['form']['comparison_context'] = comparison_context return res def _print_report(self, cr, uid, ids, data, context=None): data['form'].update(self.read(cr, uid, ids, ['date_from_cmp', 'debit_credit', 'date_to_cmp', 'fiscalyear_id_cmp', 'period_from_cmp', 'period_to_cmp', 'filter_cmp', 'account_report_id', 'enable_filter', 'label_filter'], context=context)[0]) return { 'type': 'ir.actions.report.xml', 'report_name': 'account.financial.report', 'datas': data, }
class fleet_order(osv.osv): _name="fleet.order" _description="Fleet Orders" def ord_seq_get(self, cr, uid): pool_seq=self.pool.get('ir.sequence') cr.execute("select id,number_next,number_increment,prefix,suffix,padding from ir_sequence where code='fleet.order' and active=True") res = cr.dictfetchone() if res: if res['number_next']: return pool_seq._process(res['prefix']) + '%%0%sd' % res['padding'] % res['number_next'] + pool_seq._process(res['suffix']) else: return pool_seq._process(res['prefix']) + pool_seq._process(res['suffix']) return False def create(self, cr, user, vals, context=None): name=self.pool.get('ir.sequence').get(cr, user, 'fleet.order') return super(fleet_workorder,self).create(cr, user, vals, context) _rec_name="orderno" _columns={ 'orderno':fields.char('Order No',size=20,required=True), 'orddate':fields.date('Order Date',required=True), 'reqdate':fields.date('Book Date',required=True), 'client_order_ref': fields.char('Customer Order Ref',size=64), 'partner_id':fields.many2one('res.partner', 'Customer', readonly=True, states={'draft':[('readonly',False)]}, change_default=True, select=True), 'partner_invoice_id':fields.many2one('res.partner.address', 'Invoice Address', readonly=True, required=True, states={'draft':[('readonly',False)]}), 'partner_order_id':fields.many2one('res.partner.address', 'Ordering Contact', readonly=True, required=True, states={'draft':[('readonly',False)]}, help="The name and address of the contact that requested the order or quotation."), 'partner_shipping_origin_id':fields.many2one('res.partner.address', 'Origin Address', readonly=True, required=True, states={'draft':[('readonly',False)]}), 'partner_shipping_dest_id':fields.many2one('res.partner.address', 'Destination Address', readonly=True, required=True, states={'draft':[('readonly',False)]}), 'state': fields.selection([ ('draft','Enquired'), ('waiting_allotment','Waiting Allotment'), ('allotted','Vehicle Allotted'), ('progress','In Progress'), ('vehicle_except','Vehicle Exception'), ('invoice_except','Invoice Exception'), ('done','Done'), ('cancel','Cancel'), ('invoiced','Invoiced') ], 'Order State', readonly=True, help="Gives the state of the quotation or sale order. The exception state is automatically set when a cancel operation occurs in the invoice validation (Invoice Exception) or in the packing list process (Shipping Exception). The 'Waiting Schedule' state is set when the invoice is confirmed but waiting for the scheduler to run on the date 'Date Ordered'.", select=True), 'pricelist_id':fields.many2one('product.pricelist', 'Pricelist', required=True, readonly=True, states={'draft':[('readonly',False)]}), 'payment_term' : fields.many2one('account.payment.term', 'Payment Term'), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position'), 'vehicle':fields.many2one('fleet.vehicle','Vehicle Allotted',required=True, states={'draft':[('readonly',False)],'waiting_allotment':[('readonly',False)]}), } _defaults={ 'orderno':lambda obj,cr,uid,context: obj.pool.get('fleet.order').wt_seq_get(cr,uid), 'partner_invoice_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['invoice'])['invoice'], 'partner_order_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['contact'])['contact'], 'partner_shipping_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['delivery'])['delivery'], 'partner_origin_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['origin'])['origin'], 'partner_dest_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['destination'])['destination'], 'pricelist_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').browse(cr, uid, context['partner_id']).property_product_pricelist.id, } def onchange_partner_id(self, cr, uid, ids, part): if not part: return {'value':{'partner_invoice_id': False, 'partner_shipping_id':False, 'partner_order_id':False, 'payment_term' : False, 'fiscal_position': False}} addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['delivery','invoice','contact','origin','destination']) part = self.pool.get('res.partner').browse(cr, uid, part) pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False payment_term = part.property_payment_term and part.property_payment_term.id or False fiscal_position = part.property_account_position and part.property_account_position.id or False return {'value':{'partner_invoice_id': addr['invoice'], 'partner_order_id':addr['contact'],'partner_shipping_origin_id':addr['origin'],'partner_shipping_dest_id':addr['destination'], 'partner_shipping_id':addr['delivery'], 'pricelist_id': pricelist, 'payment_term' : payment_term, 'fiscal_position': fiscal_position}}
class vehicle_prev_op(osv.osv): _name = "vehicle.prev.op" _description = "Preventive operations of a vehicle." _columns = { 'name': fields.char('REF', size=80, required=True), 'opdescription': fields.text('Description'), 'vehicle': fields.many2one('fleet.vehicles', 'Vehicle', required=True, readonly=True), 'frequency': fields.integer('Frequency', help="Estimated time for the next operation."), 'measUnit': fields.selection( [('day', 'Days'), ('week', 'Weeks'), ('mon', 'Months'), ('year', 'Years')], 'Meas.', ), 'mileage': fields.integer( 'Op. Mileage Increment', help= "Mileage increment for the next operation. Measured in kilometers." ), 'lastdate': fields.date('Date', help="Last date on which the operation was done."), 'lastkm': fields.integer( 'Mileage', help= "Mileage of the vehicle in the last operation. Measured in kilometers." ), 'lasttime': fields.time('Time', help="Time it takes to make the operation. hh:mm:ss"), 'nextkm': fields.integer( 'Mileage', help= "Mileage of the vehicle for the next operation. Measured in kilometers." ), 'nextdate': fields.date('Date', help="Expected date for the next operation."), 'nexttime': fields.time( 'Time', size=10, help="Expected time for the execution of the operation. hh:mm:ss"), 'alert': fields.boolean('1st alert', readonly=True), 'extra_alert': fields.boolean('2nd alert', readonly=True), 'check_al1': fields.boolean( '1st alert check', help= "If checked the alarm will be test at the specified parameters."), 'check_al2': fields.boolean( '2nd alert check', help= "If checked the alarm will be test at the specified parameters."), 'margin_km1': fields.integer('Km. Margin', size=20), 'margin_km2': fields.integer('Km. Margin', size=20), 'margin_fre1': fields.integer('Frequency Margin'), 'measUnit1': fields.selection([('day', 'Days'), ('week', 'Weeks'), ('mon', 'Months'), ('year', 'Years')], 'Meas.'), 'margin_fre2': fields.integer('Frequency Margin'), 'measUnit2': fields.selection([('day', 'Days'), ('week', 'Weeks'), ('mon', 'Months'), ('year', 'Years')], 'Meas.'), 'acdometer': fields.related('vehicle', 'actodometer', type='integer', relation="fleet.vehicles", string="Actual Odometer"), } _defaults = { # 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'vehicle.prev.op'), } def default_get(self, cr, uid, fields, context=None): if context is None: context = {} res = super(vehicle_prev_op, self).default_get(cr, uid, fields, context) if 'name' in context: if context['name']: opt = self.pool.get('fleet.vehicles').search( cr, uid, [('name', '=', context['name'])])[0] res.update({'vehicle': opt}) return res
class bom_history_line(osv.osv): _name = "bom.history.line" _columns = { 'name': fields.char('Name', size=64), 'code': fields.char('Reference', size=16), 'position': fields.char('Internal Reference', size=64, help="Reference to a position in an external plan."), 'date_start': fields.date( 'Valid From', help= "Validity of this BoM or component. Keep empty if it's always valid." ), 'date_stop': fields.date( 'Valid Until', help= "Validity of this BoM or component. Keep empty if it's always valid." ), 'sequence': fields.integer( 'Sequence', help= "Gives the sequence order when displaying a list of bills of material." ), 'product_uos_qty': fields.float('Product UOS Qty'), 'product_qty': fields.float( 'Product Quantity', required=True, digits_compute=dp.get_precision('Product Unit of Measure')), 'history_id': fields.many2one('bom.history', 'History ID', ondelete='cascade'), 'product_id': fields.many2one('product.product', 'Product', required=True), 'product_uos': fields.many2one( 'product.uom', 'Product UOS', help= "Product UOS (Unit of Sale) is the unit of measurement for the invoicing and promotion of stock." ), 'product_uom': fields.many2one( 'product.uom', 'Product Unit of Measure', required=True, help= "Unit of Measure (Unit of Measure) is the unit of measurement for the inventory control" ), 'bom_id': fields.many2one('mrp.bom', 'Parent BoM', ondelete='cascade', select=True), 'routing_id': fields.many2one( 'mrp.routing', 'Routing', help= "The list of operations (list of work centers) to produce the finished product. The routing is mainly used to compute work center costs during operations and to plan future loads on work centers based on production planning." ), 'company_id': fields.many2one('res.company', 'Company', required=True), 'property_ids': fields.many2many('mrp.property', 'mrp_bom_property_rel', 'bom_id', 'property_id', 'Properties'), } _defaults = { 'product_qty': lambda *a: 1.0, 'company_id': lambda self, cr, uid, c: self.pool.get('res.company'). _company_default_get(cr, uid, 'mrp.bom', context=c), }
args.insert(0, self.pool.get(act.model.model).search(cr, uid, [])) act.args=str(args) self._callback(cr, uid, act.model.model, act.name, act.args) ################################### warning = self.make_warning_message() res_text = '\n' for i in sorted(self.imported_records): res_text+=i+': '+str(len(self.imported_records[i]))+'\n' self.imported_records.clear() self.warning_text = [] self.write(cr, uid, self_id, {'log':warning+res_text,'state':'done'}) return _columns = { 'name':fields.char('Name', size=64), 'date': fields.date('Date', required=True), 'import_model_ids':fields.many2many('migration.import_models', 'schedule_models_rel', 'schedule_id', 'import_model_id', 'Import Models'), 'actions_ids': fields.many2many('migration.model_actions', 'schedule_actions_rel', 'schedule_id', 'action_id', 'Actions'), 'state':fields.selection([('ready','Ready'),('running','Running'),('error','Error'),('done','Done'),('stop','Stopped')], 'State'), 'log': fields.text('Log'), 'print_log':fields.boolean('Print Log to Console'), 'cron_id':fields.many2one('ir.cron', 'Scheduler', readonly=True), } _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'state': lambda *a: 'ready', } def set_start(self, cr, uid, ids, context={}): self.write(cr, uid, ids, {'state':'ready'})
class wizard_report(osv.osv_memory): _name = "wizard.report" _columns = { 'afr_id': fields.many2one('afr', 'Custom Report', help='If you have already set a Custom Report, Select it Here.'), 'company_id': fields.many2one('res.company', 'Company', required=True), 'currency_id': fields.many2one('res.currency', 'Currency', help="Currency at which this report will be expressed. If not selected will be used the one set in the company"), 'inf_type': fields.selection([('BS', 'Balance Sheet'), ('IS', 'Income Statement')], 'Type', required=True), 'columns': fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'), ('four', 'Initial | Debit | Credit | YTD'), ('five', 'Initial | Debit | Credit | Period | YTD'), ('qtr', "4 QTR's | YTD"), ('thirteen', '12 Months | YTD')], 'Columns', required=True), 'display_account': fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'), ('mov', 'With movements'), ('bal_mov', 'With Balance / Movements')], 'Display accounts'), 'display_account_level': fields.integer('Up to level', help='Display accounts up to this level (0 to show all)'), 'account_list': fields.many2many('account.account', 'rel_wizard_account', 'account_list', 'account_id', 'Root accounts', required=True), 'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year', help='Fiscal Year for this report', required=True), 'periods': fields.many2many('account.period', 'rel_wizard_period', 'wizard_id', 'period_id', 'Periods', help='All periods in the fiscal year if empty'), 'analytic_ledger': fields.boolean('Analytic Ledger', help="Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"), 'journal_ledger': fields.boolean('Journal Ledger', help="Allows to Generate an Journal Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"), 'partner_balance': fields.boolean('Partner Balance', help="Allows to " "Generate a Partner Balance for accounts with moves. Available when " "Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"), 'tot_check': fields.boolean('Summarize?', help='Checking will add a new line at the end of the Report which will Summarize Columns in Report'), 'lab_str': fields.char('Description', help='Description for the Summary', size=128), 'target_move': fields.selection([('posted', 'All Posted Entries'), ('all', 'All Entries'), ], 'Entries to Include', required=True, help='Print All Accounting Entries or just Posted Accounting Entries'), 'narration': fields.text('Notes', readonly=True), #~ Deprecated fields 'filter': fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')], 'Date/Period Filter'), 'date_to': fields.date('End date'), 'date_from': fields.date('Start date'), } _defaults = { 'date_from': lambda *a: time.strftime('%Y-%m-%d'), 'date_to': lambda *a: time.strftime('%Y-%m-%d'), 'filter': lambda *a: 'byperiod', 'display_account_level': lambda *a: 0, 'inf_type': lambda *a: 'BS', 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c), 'fiscalyear': lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(cr, uid), 'display_account': lambda *a: 'bal_mov', 'columns': lambda *a: 'five', 'target_move': 'posted', } def onchange_inf_type(self, cr, uid, ids, inf_type, context=None): if context is None: context = {} res = {'value': {}} if inf_type != 'BS': res['value'].update({'analytic_ledger': False}) return res def onchange_columns(self, cr, uid, ids, columns, fiscalyear, periods, context=None): if context is None: context = {} res = {'value': {}} p_obj = self.pool.get("account.period") all_periods = p_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear), ( 'special', '=', False)], context=context) s = set(periods[0][2]) t = set(all_periods) go = periods[0][2] and s.issubset(t) or False if columns != 'four': res['value'].update({'analytic_ledger': False}) if columns in ('qtr', 'thirteen'): res['value'].update({'periods': all_periods}) else: if go: res['value'].update({'periods': periods}) else: res['value'].update({'periods': []}) return res def onchange_analytic_ledger(self, cr, uid, ids, company_id, analytic_ledger, context=None): if context is None: context = {} context['company_id'] = company_id res = {'value': {}} cur_id = self.pool.get('res.company').browse( cr, uid, company_id, context=context).currency_id.id res['value'].update({'currency_id': cur_id}) return res def onchange_company_id(self, cr, uid, ids, company_id, context=None): if context is None: context = {} context['company_id'] = company_id res = {'value': {}} if not company_id: return res cur_id = self.pool.get('res.company').browse( cr, uid, company_id, context=context).currency_id.id fy_id = self.pool.get('account.fiscalyear').find( cr, uid, context=context) res['value'].update({'fiscalyear': fy_id}) res['value'].update({'currency_id': cur_id}) res['value'].update({'account_list': []}) res['value'].update({'periods': []}) res['value'].update({'afr_id': None}) return res def onchange_afr_id(self, cr, uid, ids, afr_id, context=None): if context is None: context = {} res = {'value': {}} if not afr_id: return res afr_brw = self.pool.get('afr').browse(cr, uid, afr_id, context=context) res['value'].update({ 'currency_id': afr_brw.currency_id and afr_brw.currency_id.id or afr_brw.company_id.currency_id.id}) res['value'].update({'inf_type': afr_brw.inf_type or 'BS'}) res['value'].update({'columns': afr_brw.columns or 'five'}) res['value'].update({ 'display_account': afr_brw.display_account or 'bal_mov'}) res['value'].update({ 'display_account_level': afr_brw.display_account_level or 0}) res['value'].update({ 'fiscalyear': afr_brw.fiscalyear_id and afr_brw.fiscalyear_id.id}) res['value'].update({'account_list': [ acc.id for acc in afr_brw.account_ids]}) res['value'].update({'periods': [p.id for p in afr_brw.period_ids]}) res['value'].update({ 'analytic_ledger': afr_brw.analytic_ledger or False}) res['value'].update({'tot_check': afr_brw.tot_check or False}) res['value'].update({'narration': afr_brw.narration or ''}) res['value'].update({'lab_str': afr_brw.lab_str or _( 'Write a Description for your Summary Total')}) return res def _get_defaults(self, cr, uid, data, context=None): if context is None: context = {} user = pooler.get_pool(cr.dbname).get( 'res.users').browse(cr, uid, uid, context=context) if user.company_id: company_id = user.company_id.id else: company_id = pooler.get_pool(cr.dbname).get( 'res.company').search(cr, uid, [('parent_id', '=', False)])[0] data['form']['company_id'] = company_id fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) data['form']['context'] = context return data['form'] def _check_state(self, cr, uid, data, context=None): if context is None: context = {} if data['form']['filter'] == 'bydate': self._check_date(cr, uid, data, context) return data['form'] def _check_date(self, cr, uid, data, context=None): if context is None: context = {} if data['form']['date_from'] > data['form']['date_to']: raise osv.except_osv(_('Error !'), ( 'La fecha final debe ser mayor a la inicial')) sql = """SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f WHERE '%s' = f.id """ % (data['form']['fiscalyear']) cr.execute(sql) res = cr.dictfetchall() if res: if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_from'] < res[0]['date_start']): raise osv.except_osv(_('UserError'), 'Las fechas deben estar entre %s y %s' % ( res[0]['date_start'], res[0]['date_stop'])) else: return 'report' else: raise osv.except_osv(_('UserError'), 'No existe periodo fiscal') def period_span(self, cr, uid, ids, fy_id, context=None): if context is None: context = {} ap_obj = self.pool.get('account.period') fy_id = fy_id and type(fy_id) in (list, tuple) and fy_id[0] or fy_id if not ids: #~ No hay periodos return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False)], order='date_start asc') ap_brws = ap_obj.browse(cr, uid, ids, context=context) date_start = min([period.date_start for period in ap_brws]) date_stop = max([period.date_stop for period in ap_brws]) return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False), ('date_start', '>=', date_start), ('date_stop', '<=', date_stop)], order='date_start asc') def print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = {} data['ids'] = context.get('active_ids', []) data['model'] = context.get('active_model', 'ir.ui.menu') data['form'] = self.read(cr, uid, ids[0]) if data['form']['filter'] == 'byperiod': del data['form']['date_from'] del data['form']['date_to'] data['form']['periods'] = self.period_span(cr, uid, data[ 'form']['periods'], data['form']['fiscalyear']) elif data['form']['filter'] == 'bydate': self._check_date(cr, uid, data) del data['form']['periods'] elif data['form']['filter'] == 'none': del data['form']['date_from'] del data['form']['date_to'] del data['form']['periods'] else: self._check_date(cr, uid, data) lis2 = str(data['form']['periods']).replace( "[", "(").replace("]", ")") sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin from account_period p where p.id in %s""" % lis2 cr.execute(sqlmm) minmax = cr.dictfetchall() if minmax: if (data['form']['date_to'] < minmax[0]['inicio']) or (data['form']['date_from'] > minmax[0]['fin']): raise osv.except_osv(_('Error !'), _( 'La interseccion entre el periodo y fecha es vacio')) if data['form']['columns'] == 'one': name = 'afr.1cols' if data['form']['columns'] == 'two': name = 'afr.2cols' if data['form']['columns'] == 'four': if data['form']['analytic_ledger'] and data['form']['inf_type'] == 'BS': name = 'afr.analytic.ledger' elif data['form']['journal_ledger'] and data['form']['inf_type'] == 'BS': name = 'afr.journal.ledger' elif data['form']['partner_balance'] and data['form']['inf_type'] == 'BS': name = 'afr.partner.balance' else: name = 'afr.4cols' if data['form']['columns'] == 'five': name = 'afr.5cols' if data['form']['columns'] == 'qtr': name = 'afr.qtrcols' if data['form']['columns'] == 'thirteen': name = 'afr.13cols' return {'type': 'ir.actions.report.xml', 'report_name': name, 'datas': data}
'base_discount': valid_discount, 'price_buffer':total_price, # 'balance':balance, } } def _estado_defecto(self, cr, uid, context=None): estado = self.pool.get('bag.state').search(cr, uid, [('name', '=', 'Recibido')]) return estado _name = 'bag.service' _description = 'Service Order' _columns = { 'name': fields.char('Numero Orden', size=24), 'type': fields.selection([('particular', 'Particular'), ('airline', 'Aerolinea')], 'Type', required=True), 'date': fields.date('Fecha', required=True), 'date_promised': fields.date('Fecha Prometida', required=True), 'partner_id' : fields.many2one('res.partner', 'Cliente'), 'address_str': fields.related('partner_id', 'street', type='char', size='128'), 'address_num_str': fields.related('partner_id', 'street_num', type='char'), 'piso_dpto_str': fields.related('partner_id', 'piso_dpto', type='char', size='128'), 'phone_str': fields.related('partner_id', 'phone_str', type='char', size='128'), 'zone_str': fields.related('partner_id', 'street', type='char'), 'type_id': fields.many2one('bag.type', 'Tipo'), 'format_id': fields.many2one('bag.format', 'Formato'), 'color_id': fields.many2one('bag.color', 'Color'), 'material_id': fields.many2one('bag.material', 'Material'), 'size_id': fields.many2one('bag.size', 'Tamano'), 'description': fields.char('Descripcion', size=64), 'brand': fields.char('Marca', size=64), 'model': fields.char('Modelo', size=64),
class asset_pact_order(osv.osv): """ Asset Pact record including basic information of the Pact.""" def create(self, cr, user, vals, context=None): """ """ if ('name' not in vals) or (vals.get('name') == '/'): seq = self.pool.get('ir.sequence').get(cr, user, 'asset.pact.order') vals['name'] = seq and seq or '/' if not seq: raise osv.except_osv(_('Warning'), _('No sequence defined!\nPleas contact administartor to configue sequence with code \'asset.pact.order\'') ) new_id = super(asset_pact_order, self).create(cr, user, vals, context) return new_id def copy(self, cr, uid, id, default=None, context=None): """ Override copy function to edit default value. @param default : default vals dict @return: id of the newly created record """ if default is None: default = {} if context is None: context = {} default.update({ 'name': self.pool.get('ir.sequence').get(cr, uid, 'asset.pact.order'), 'categories_ids':[], 'pact_line_ids':[], }) return super(asset_pact_order, self).copy(cr, uid, id, default, context) def action_create_custody_order(self ,cr ,uid ,ids ,order={},context=None): """This Function For Create Custody Order @para order : is a dictionary holds order data, @return order_id""" order_id = self.create( cr , uid , order ,context=context) return order_id def unlink(self, cr, uid, ids, context=None): """ """ pact_orders = self.read(cr, uid, ids, ['state'], context=context) unlink_ids = [] for pact_order in pact_orders: if pact_order['state'] in ['draft', 'cancel']: unlink_ids.append(pact_order['id']) else: raise osv.except_osv(_('Invalid action !'), _('In order to delete a Pact Order(s), it must be cancelled first!')) wf_service = netsvc.LocalService("workflow") for id in unlink_ids: wf_service.trg_validate(uid, 'asset.pact.order', id, 'cancel', cr) return super(asset_pact_order, self).unlink(cr, uid, unlink_ids, context=context) _name = 'asset.pact.order' _description = 'Custody Request' _inherit = ['mail.thread'] _track = { 'state': { 'asset_pact_order.mt_custody_order_state_change': lambda self, cr, uid, obj, ctx=None: True, },} _columns = { 'name' : fields.char('Name' , size=32), 'department_id' : fields.many2one('hr.department','Department', ), 'user': fields.many2one('res.users', 'Responsible', readonly=True,), 'order_date' : fields.date('Date' ,), 'purpose' : fields.char('Purpose',size=64, ), 'source_document' : fields.many2one('stock.picking' , 'Source Document' ,), 'custody_type' : fields.selection([('department','Administrative'),('personal' , 'Personal')], 'Custody Type',), 'period_type' : fields.selection([('temp','Temparory'),('const' , 'Constant')], 'Period Type',), 'expacted_return_date' : fields.date('Expected Date',), 'categories_ids' : fields.one2many('custody.order.items' , 'custody_order_id' , 'Categories') , 'pact_line_ids' : fields.one2many('pact.order.line' , 'pact_order_id' , 'Pact Lines') , 'notes': fields.text('Notes'), 'state' : fields.selection([('draft','Draft'), ('confirmed','Confirmed'), ('approved','Approved from Section Manager'), ('approve_dept','Approved from Department Manager'), ('approve_support','Approved from Techincal Manager'), ('assigned' , 'Assigned'), ('cancel','Cancelled')] , 'State' ), } _defaults = { 'name':'/', 'order_date': lambda *a: time.strftime('%Y-%m-%d'), 'user': lambda self, cr, uid, context: uid, 'state' : 'draft', } _order = "order_date desc,name desc" _sql_constraints = [ ('check_expacted_return_date',"CHECK(expacted_return_date >= order_date)",_("Expacted Return Date must be bigger than Order Date!")) , ] def confirm(self,cr,uid,ids,context=None): """ Workflow function changes order state to confirmed. @return: Boolean True """ for order in self.browse(cr, uid, ids, context=context): if not order.categories_ids: raise osv.except_osv(_('Error !'), _('Please Fill the Categories')) self.write(cr,uid,ids,{'state' : 'confirmed' },context=context) return True def approve(self,cr,uid,ids,context=None): """ Workflow function changes order state to approved. @return: Boolean True """ self.write(cr,uid,ids,{'state' : 'approved' },context=context) return True def approve_dept(self,cr,uid,ids,context=None): """ Workflow function changes order state to approve_dept. @return: Boolean True """ self.write(cr,uid,ids,{'state' : 'approve_dept' },context=context) return True def approve_support(self,cr,uid,ids,context=None): """ Workflow function changes order state to approve_suport. @return: Boolean True """ if not isinstance(ids, list): ids = [ids] pact_line_obj = self.pool.get('pact.order.line') emp_obj = self.pool.get('hr.employee') for order in self.browse(cr, uid, ids, context=context): user_id = order.user.id user_name = order.user.name if not order.categories_ids: raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.')) if order.custody_type == 'personal': emp_id = emp_obj.search(cr ,uid ,[('user_id', '=' , user_id ),('name','=',user_name)] ) if not emp_id: emp_id = [False] else : emp_id = [False] for line in order.categories_ids: for custody in range(line.quantity): custody_id = pact_line_obj.create(cr ,uid , {'category_id' : line.category_id.id, 'custody_type' : order.custody_type, 'employee_id' : emp_id[0], 'pact_order_id' : order.id ,} ,context=context) self.write(cr,uid,ids,{'state' : 'approve_support' },context=context) return True def assign(self,cr,uid,ids,context=None): employee_obj = self.pool.get('hr.employee') user_obj = self.pool.get('res.users') custody_obj = self.pool.get('account.asset.asset') asset_obj = self.pool.get('account.asset.asset') asset_log_obj = self.pool.get('asset.logs') parent_res = { } lines_res = { } for order in self.browse(cr, uid, ids, context=context): if not order.categories_ids: raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.')) if not order.pact_line_ids: raise osv.except_osv(_('Error !'), _('Please Fill the Assets or Assign the Assets to Users.')) #desire_quantity = 0 #for categ in order.categories_ids: # desire_quantity += categ.quantity #if len(order.pact_line_ids) != desire_quantity : # raise osv.except_osv(_('Error !'), _('The Desire Quantities and The Number of Assign Quantities Not Equal .')) for line in order.pact_line_ids: custody_id = custody_obj.search(cr,uid,[('id' , '=' , line.custody_id.id )]) parent_res = { 'state' : 'open', 'custody_type' : order.custody_type , 'current_employee' : line.employee_id.id , 'period_type' : order.period_type, 'expacted_return_date' : order.expacted_return_date or False, 'department_id' : order.department_id.id, 'custody_location_id' : line.custody_location_id.id , 'user_id' : line.employee_id.user_id.id, } lines_res = { 'custody_log_id' : custody_id[0] , 'department_id' : order.department_id.id, 'action_type' : 'recieve' , 'action_date' : order.order_date , 'employee_id' : line.employee_id.id or False, } log_id = asset_log_obj.create(cr,uid,lines_res) custody_obj.write(cr,uid,custody_id, parent_res ,context=context) self.write(cr,uid,ids,{'state' : 'assigned' },context=context) return True def cancel(self,cr,uid,ids,context=None): """ Workflow function changes order state to cancel. @return: Boolean True """ self.write(cr, uid, ids, {'state':'cancel'}, context=context) return True def ir_action_cancel_draft(self, cr, uid, ids, context=None): """ Changes state to Draft and reset the workflow. @return: Boolean True """ if not len(ids): return False self.write(cr, uid, ids, {'state':'draft'}, context=context) wf_service = netsvc.LocalService("workflow") for s_id in ids: # Deleting the existing instance of workflow for Internal requestion wf_service.trg_delete(uid, 'asset.pact.order', s_id, cr) wf_service.trg_create(uid, 'asset.pact.order', s_id, cr) return True
'installed_1st_fa':fields.char("Installed 1st FA", size=10, help="1st Front Axle Weight (with wrecker)"), 'installed_2nd_fa':fields.char("Installed 2nd FA", size=10, help="2nd Front Axle Weight (with wrecker)"), 'installed_1st_ra':fields.char("Installed 1st RA", size=10, help="1st Rear Axle Weight (with wrecker)"), 'installed_2nd_ra':fields.char("Installed 2nd RA", size=10, help="2nd Rear Axle Weight (with wrecker)"), 'installed_3rd_ra':fields.char("Installed 3rd RA", size=10, help="3rd Rear Axle Weight (with wrecker)"), 'installed_height':fields.char("Installed Height", size=10, help="Highest Point on the Installed Wrecker"), 'installed_length':fields.char("Installed Length", size=10, help="Overall Length of the Installed Wrecker"), 'installed_width':fields.char("Installed Width", size=10, help="Overall Width of the Installed Wrecker"), 'chassis_1st_fa_rating':fields.integer("Chassis 1st FA Rating", size=10, help="1st Front Axle Rating"), 'chassis_2nd_fa_rating':fields.integer("Chassis 2nd FA Rating", size=10, help="2nd Front Axle Rating"), 'chassis_1st_ra_rating':fields.integer("Chassis 1st RA Rating", size=10, help="1st Rear Axle Rating"), 'chassis_2nd_ra_rating':fields.integer("Chassis 2nd RA Rating", size=10, help="2nd Rear Axle Rating"), 'chassis_3rd_ra_rating':fields.integer("Chassis 3rd RA Rating", size=10, help="3rd Rear Axle Rating"), #Warranty 'warranty_start_date':fields.date('Start Date', help="The date the warranty commences"), 'warranty_finish_date':fields.date('Finish Date', help="The date the warranty expires"), 'warranty_completion_date':fields.date('Completion Date'), 'warranty_duration':fields.selection([ ('no_warranty', 'No Warranty'), ('30_days','30 Days'), ('60_days','60 Days'), ('90_days','90 Days'), ('180_days','180 Days'), ('1_year','1 Year'), ('2_years','2 Years'), ('3_years','3 Years'), ('4_years','4 Years'), ('5_years','5 Years')], 'Duration', help="Duration of the Warranty"), 'warranty_history':fields.one2many('mttl.warranty.history','serial_id', 'Warranty Claims History'), #+++ HoangTK - 02/18/2016 : Link warranty module to serials
class account_invoice_refund(osv.osv_memory): """Refunds invoice""" _name = "account.invoice.refund" _description = "Invoice Refund" _columns = { 'date': fields.date( 'Operation Date', help= 'This date will be used as the invoice date for credit note and period will be chosen accordingly!' ), 'period': fields.many2one('account.period', 'Force period'), 'journal_id': fields.many2one( 'account.journal', 'Refund Journal', help= 'You can select here the journal to use for the credit note that will be created. If you leave that field empty, it will use the same journal as the current invoice.' ), 'description': fields.char('Description', size=128, required=True), 'filter_refund': fields.selection( [('refund', 'Create a draft refund'), ('cancel', 'Cancel: create credit note and reconcile'), ('modify', 'Modify: create credit note, reconcile and create a new draft invoice' )], "Refund Method", required=True, help= 'Credit note base on this type. You can not Modify and Cancel if the invoice is already reconciled' ), } def _get_journal(self, cr, uid, context=None): obj_journal = self.pool.get('account.journal') user_obj = self.pool.get('res.users') if context is None: context = {} inv_type = context.get('type', 'out_invoice') company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id type = (inv_type == 'out_invoice') and 'sale_refund' or \ (inv_type == 'out_refund') and 'sale' or \ (inv_type == 'in_invoice') and 'purchase_refund' or \ (inv_type == 'in_refund') and 'purchase' journal = obj_journal.search(cr, uid, [('type', '=', type), ('company_id', '=', company_id)], limit=1, context=context) return journal and journal[0] or False _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'journal_id': _get_journal, 'filter_refund': 'refund', } def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False): if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') # remove the entry with key 'form_view_ref', otherwise fields_view_get crashes context.pop('form_view_ref', None) res = super(account_invoice_refund, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) type = context.get('type', 'out_invoice') company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id journal_type = (type == 'out_invoice') and 'sale_refund' or \ (type == 'out_refund') and 'sale' or \ (type == 'in_invoice') and 'purchase_refund' or \ (type == 'in_refund') and 'purchase' for field in res['fields']: if field == 'journal_id': journal_select = journal_obj._name_search( cr, uid, '', [('type', '=', journal_type), ('company_id', 'child_of', [company_id])], context=context) res['fields'][field]['selection'] = journal_select return res def compute_refund(self, cr, uid, ids, mode='refund', context=None): """ @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs """ inv_obj = self.pool.get('account.invoice') reconcile_obj = self.pool.get('account.move.reconcile') account_m_line_obj = self.pool.get('account.move.line') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') wf_service = netsvc.LocalService('workflow') inv_tax_obj = self.pool.get('account.invoice.tax') inv_line_obj = self.pool.get('account.invoice.line') res_users_obj = self.pool.get('res.users') if context is None: context = {} for form in self.browse(cr, uid, ids, context=context): created_inv = [] date = False period = False description = False company = res_users_obj.browse(cr, uid, uid, context=context).company_id journal_id = form.journal_id.id for inv in inv_obj.browse(cr, uid, context.get('active_ids'), context=context): if inv.state in ['draft', 'proforma2', 'cancel']: raise osv.except_osv( _('Error !'), _('Can not %s draft/proforma/cancel invoice.') % (mode)) if inv.reconciled and mode in ('cancel', 'modify'): raise osv.except_osv( _('Error !'), _('Can not %s invoice which is already reconciled, invoice should be unreconciled first. You can only Refund this invoice' ) % (mode)) if form.period.id: period = form.period.id else: period = inv.period_id and inv.period_id.id or False if not journal_id: journal_id = inv.journal_id.id if form.date: date = form.date if not form.period.id: cr.execute("select name from ir_model_fields \ where model = 'account.period' \ and name = 'company_id'") result_query = cr.fetchone() if result_query: cr.execute( """select p.id from account_fiscalyear y, account_period p where y.id=p.fiscalyear_id \ and date(%s) between p.date_start AND p.date_stop and y.company_id = %s limit 1""", ( date, company.id, )) else: cr.execute( """SELECT id from account_period where date(%s) between date_start AND date_stop \ limit 1 """, (date, )) res = cr.fetchone() if res: period = res[0] else: date = inv.date_invoice if form.description: description = form.description else: description = inv.name if not period: raise osv.except_osv(_('Data Insufficient !'), \ _('No Period found on Invoice!')) refund_id = inv_obj.refund(cr, uid, [inv.id], date, period, description, journal_id) refund = inv_obj.browse(cr, uid, refund_id[0], context=context) inv_obj.write(cr, uid, [refund.id], { 'date_due': date, 'check_total': inv.check_total }) inv_obj.button_compute(cr, uid, refund_id) created_inv.append(refund_id[0]) if mode in ('cancel', 'modify'): movelines = inv.move_id.line_id to_reconcile_ids = {} for line in movelines: if line.account_id.id == inv.account_id.id: to_reconcile_ids[line.account_id.id] = [line.id] if type(line.reconcile_id) != osv.orm.browse_null: reconcile_obj.unlink(cr, uid, line.reconcile_id.id) wf_service.trg_validate(uid, 'account.invoice', \ refund.id, 'invoice_open', cr) refund = inv_obj.browse(cr, uid, refund_id[0], context=context) for tmpline in refund.move_id.line_id: if tmpline.account_id.id == inv.account_id.id: to_reconcile_ids[tmpline.account_id.id].append( tmpline.id) for account in to_reconcile_ids: account_m_line_obj.reconcile( cr, uid, to_reconcile_ids[account], writeoff_period_id=period, writeoff_journal_id=inv.journal_id.id, writeoff_acc_id=inv.account_id.id) if mode == 'modify': invoice = inv_obj.read( cr, uid, [inv.id], [ 'name', 'type', 'number', 'reference', 'comment', 'date_due', 'partner_id', 'partner_insite', 'partner_contact', 'partner_ref', 'payment_term', 'account_id', 'currency_id', 'invoice_line', 'tax_line', 'journal_id', 'period_id' ], context=context) invoice = invoice[0] del invoice['id'] invoice_lines = inv_line_obj.read( cr, uid, invoice['invoice_line'], context=context) invoice_lines = inv_obj._refund_cleanup_lines( cr, uid, invoice_lines) tax_lines = inv_tax_obj.read(cr, uid, invoice['tax_line'], context=context) tax_lines = inv_obj._refund_cleanup_lines( cr, uid, tax_lines) invoice.update({ 'type': inv.type, 'date_invoice': date, 'state': 'draft', 'number': False, 'invoice_line': invoice_lines, 'tax_line': tax_lines, 'period_id': period, 'name': description }) for field in ('partner_id', 'account_id', 'currency_id', 'payment_term', 'journal_id'): invoice[ field] = invoice[field] and invoice[field][0] inv_id = inv_obj.create(cr, uid, invoice, {}) if inv.payment_term.id: data = inv_obj.onchange_payment_term_date_invoice( cr, uid, [inv_id], inv.payment_term.id, date) if 'value' in data and data['value']: inv_obj.write(cr, uid, [inv_id], data['value']) created_inv.append(inv_id) xml_id = (inv.type == 'out_refund') and 'action_invoice_tree1' or \ (inv.type == 'in_refund') and 'action_invoice_tree2' or \ (inv.type == 'out_invoice') and 'action_invoice_tree3' or \ (inv.type == 'in_invoice') and 'action_invoice_tree4' result = mod_obj.get_object_reference(cr, uid, 'account', xml_id) id = result and result[1] or False result = act_obj.read(cr, uid, id, context=context) invoice_domain = eval(result['domain']) invoice_domain.append(('id', 'in', created_inv)) result['domain'] = invoice_domain return result def invoice_refund(self, cr, uid, ids, context=None): data_refund = self.read(cr, uid, ids, ['filter_refund'], context=context)[0]['filter_refund'] return self.compute_refund(cr, uid, ids, data_refund, context=context)