class custom_calendar_event(osv.osv): _name = "calendar.event" _inherit = 'calendar.event' @api.depends('x_categ_id','x_partner_id') def _compute_categ_id_char(self): self.x_categ_id_char = self.x_categ_id.name if self.x_categ_id_char and self.x_partner_id.display_name and self.x_partner_id.phone: self.name = self.x_categ_id_char+' : '+self.x_partner_id.display_name+', '+self.x_partner_id.phone elif self.x_categ_id_char and self.x_partner_id.display_name: self.name = self.x_categ_id_char+' : '+self.x_partner_id.display_name elif self.x_partner_id.display_name: self.name = self.x_partner_id.display_name elif self.x_categ_id_char: self.name = self.x_categ_id_char else: _columns = { 'x_domicile': fields.boolean('A domicile'), 'x_partner_id': fields.many2one('res.partner', 'Attendee', default=''), 'x_categ_id': fields.many2one('calendar.event.type', 'Tags'), 'x_categ_id_char': fields.char(compute='_compute_categ_id_char', default=''), 'x_event_is_billed': fields.boolean('is_billed'), 'x_event_is_printed': fields.boolean('is_printed'), # related field res.partner # ------------------------- 'x_event_display_name' : fields.related('x_partner_id', 'display_name', type="char"), 'x_event_name' : fields.related('x_partner_id', 'name', type="char"), 'x_event_phone' : fields.related('x_partner_id', 'phone', type="char", default=''), 'x_event_patient_prenom': fields.related('x_partner_id', 'x_patient_prenom', type="char"), 'x_event_patient_sexe': fields.related('x_partner_id', 'x_patient_sexe', type="selection", selection=SEXE_SELECTION), 'x_event_patient_cafat': fields.related('x_partner_id', 'x_patient_cafat', type="char"), 'x_event_dob': fields.date(related='x_partner_id.dob'), 'x_event_age' : fields.integer(related='x_partner_id.age'), 'x_event_src_avatar' : fields.binary(related='x_partner_id.x_src_avatar'), 'x_event_medecin_traitant': fields.char(related='x_partner_id.x_medecin_traitant'), ########## MEDICAL INFO ??? # 'x_event_groupe_sang': fields.related('x_partner_id', 'x_groupe_sang', type="selection", selection=GRP_SANG_SELECTION), # 'x_event_taille': fields.float(related='x_partner_id.x_taille'), # 'x_event_poids': fields.float(related='x_partner_id.x_poids'), # 'x_event_IMC': fields.float(related='x_partner_id.x_IMC'), ########## # related field calendar_event_type # ------------------------- 'x_event_codeActe': fields.char(related='x_categ_id.x_code_acte', size=8), 'x_event_priceActe': fields.float(related='x_categ_id.x_price_acte', digits=(4,0)), # ------------------------- } _default = { 'x_domicile': False, }
class hr_holidays_status(models.Model): _inherit = 'hr.holidays.status' _columns = { 'paid_leave': fields.boolean( 'Is Paid Leave', help="Whether this leave is paid or not", ), 'activity_ids': fields.one2many( 'hr.activity', 'leave_id', 'Activity', ), } _defaults = { # Creates an leave type automatically 'activity_ids': [{ 'type': 'leave' }] } def name_get(self, cr, uid, ids, context=None): # There is a missing context check in # addons/hr_holidays/hr_holidays.py # This is fixed by a patch in v8. context = context or {} return super(hr_holidays_status, self).name_get(cr, uid, ids, context=context)
class generate_pairkey(models.Model): _name = 'crypto.generate_pairkey' _columns = { 'name': fields.char('Pair key name', size=63), 'key_length': fields.integer('Key lenght'), 'update': fields.boolean('Update key'), } _defaults = { 'key_length': 1024, } def on_generate(self, cr, uid, ids, context): if context is None: context = {} active_ids = context['active_ids'] pairkey_obj = self.pool.get('crypto.pairkey') for wizard in self.browse(cr, uid, ids): pairkey_obj.generate_keys(cr, uid, active_ids, key_length=wizard.key_length) pairkey_obj.action_validate(cr, uid, active_ids) return {'type': 'ir.actions.act_window_close'} def on_cancel(self, cr, uid, ids, context): return {}
class Sale_config_settings(osv.TransientModel): _inherit = 'sale.config.settings' _columns = { 'limit_discount': fields.integer( 'Discount limit requires approval %', required=True, help="Discount after which approval of sale is required."), 'module_sale_discount_approval': fields.boolean( "Force two levels of approvals", help= 'Provide a double validation mechanism for sale exceeding minimum discount.\n' ), } _defaults = { 'limit_discount': 40, } def get_default_limit_discount(self, cr, uid, ids, context=None): ir_values = self.pool.get('ir.values') limit_discount = ir_values.get_default(cr, uid, 'sale.config.settings', 'limit_discount') return { 'limit_discount': limit_discount, } def set_limit_discount(self, cr, uid, ids, context=None): ir_values = self.pool.get('ir.values') wizard = self.browse(cr, uid, ids)[0] if wizard.limit_discount: limit_discount = wizard.limit_discount ir_values.set_default(cr, SUPERUSER_ID, 'sale.config.settings', 'limit_discount', limit_discount) def get_default_module_sale_discount_approval(self, cr, uid, ids, context=None): ir_values = self.pool.get('ir.values') module_sale_discount_approval = ir_values.get_default( cr, uid, 'sale.config.settings', 'module_sale_discount_approval') return { 'module_sale_discount_approval': module_sale_discount_approval == 'True', } def set_module_sale_discount_approval(self, cr, uid, ids, context=None): ir_values = self.pool.get('ir.values') wizard = self.browse(cr, uid, ids)[0] if wizard.module_sale_discount_approval: module_sale_discount_approval = 'True' else: module_sale_discount_approval = 'False' ir_values.set_default(cr, SUPERUSER_ID, 'sale.config.settings', 'module_sale_discount_approval', module_sale_discount_approval)
class appointment (osv.osv): _name = "medical.appointment" _inherit = "medical.appointment" def copy(self, cr, uid, id, default=None, context={}): default.update({'validity_status':'tobe'}) return super(appointment,self).copy(cr, uid, id, default, context) def onchange_appointment_date(self, cr, uid, ids, apt_date): if apt_date: validity_date = datetime.datetime.fromtimestamp(time.mktime(time.strptime(apt_date,"%Y-%m-%d %H:%M:%S"))) validity_date = validity_date+datetime.timedelta(days=7) v = {'appointment_validity_date':str(validity_date)} return {'value': v} return {} _columns = { 'no_invoice' : fields.boolean ('Invoice exempt'), 'appointment_validity_date' : fields.datetime ('Validity Date'), 'validity_status' : fields.selection([('invoiced','Invoiced'),('tobe','To be Invoiced')],'Status'), 'consultations' : fields.many2one ('product.product', 'Consultation Service', domain=[('type', '=', "service")], help="Consultation Services", required=True), } _defaults = { 'validity_status': lambda *a: 'tobe', 'no_invoice': lambda *a: True }
class init_wage(models.Model): _name = 'hr.contract.init.wage' _description = 'Starting Wages' _columns = { 'job_id': fields.many2one( 'hr.job', 'Job', ), 'starting_wage': fields.float('Starting Wage', digits_compute=dp.get_precision('Payroll'), required=True), 'is_default': fields.boolean( 'Use as Default', help="Use as default wage", ), 'contract_init_id': fields.many2one( 'hr.contract.init', 'Contract Settings', ), 'category_ids': fields.many2many( 'hr.employee.category', 'contract_init_category_rel', 'contract_init_id', 'category_id', 'Tags', ), } def _rec_message(self, cr, uid, ids, context=None): return _('A Job Position cannot be referenced more than once in a ' 'Contract Settings record.') _sql_constraints = [ ('unique_job_cinit', 'UNIQUE(job_id,contract_init_id)', _rec_message), ] def unlink(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] data = self.read(cr, uid, ids, ['contract_init_id'], context=context) for d in data: if not d.get('contract_init_id', False): continue d2 = self.pool.get('hr.contract.init').read( cr, uid, d['contract_init_id'][0], ['state'], context=context) if d2['state'] in ['approve', 'decline']: raise models.except_orm( _('Error'), _('You may not a delete a record that is not in a ' '"Draft" state')) return super(init_wage, self).unlink(cr, uid, ids, context=context)
class hr_employee(models.Model): _name = 'hr.employee' _inherit = 'hr.employee' _columns = { 'is_labour_union': fields.boolean('Labour Union Member', ), 'labour_union_date': fields.date('Date of Membership', ), }
class SurveySurvey(osv.Model): _inherit = 'survey.survey' _columns = {'disposable': fields.boolean(string=u'一次性调查')} _defaults = { 'users_can_go_back': True, 'auth_required': True, 'disposable': True, }
class account_invoice_line(osv.osv): _inherit = 'account.invoice.line' _description = 'Invoice lines' _columns = { # 'liq_line_id': fields.many2one('account.invoice.liquidation', 'Purchase liquidation'), 'discount_third': fields.boolean('Apl. Desto.') }
class sale_configuration(models.TransientModel): _inherit = 'sale.config.settings' _columns = { 'group_template_required': fields.boolean( "Mandatory use of templates.", implied_group='account_analytic_analysis.group_template_required', help= "Allows you to set the template field as required when creating an analytic account or a contract." ), }
class custom_stock_transfer_details_items(osv.TransientModel): _inherit = 'stock.transfer_details_items' _columns = { 'chassis_number': fields.char('Chassis Number', compute='fetch_info', readonly=True), 'engine_number': fields.char('Engine No.'), 'color': fields.char('Color', compute='fetch_info', readonly=True), 'model': fields.char('Model', compute='fetch_info', readonly=True), 'year': fields.char('Year', compute='fetch_info', readonly=True), 'location': fields.boolean('Loc'), } _defaults = { 'chassis_number': 'SAC-', 'engine_number': 'SAE-', } @api.onchange('quantity') def pre_check_quantity_limit(self): if self.transfer_id.picking_type != 'sale': return None products = [1856, 1850, 1851, 1852, 1853, 1854, 1855, 1857, 1858, 1862, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987] if self.product_id.id in products and self.quantity > 1: self.quantity = 1 @api.onchange('lot_id') def onchange_field_id(self): if self.lot_id: lot_ids.append(self.lot_id.id) return {'domain': {'lot_id': [('id', 'not in', lot_ids), ('status', '=', 'Available'), ('product_id', 'in', [self.product_id.id])]}} @api.one @api.depends('lot_id') def fetch_info(self): if self.lot_id: self.chassis_number = self.lot_id.chassis_number self.color = self.lot_id.color self.model = self.lot_id.model self.year = self.lot_id.year @api.multi def split_quantities(self): for det in self: if det.quantity > 1: det.quantity = (det.quantity - 1) new_id = det.copy(context=self.env.context) new_id.quantity = 1 new_id.packop_id = False self.split_quantities() if self and self[0]: return self[0].transfer_id.wizard_view()
class account_journal(orm.Model): _inherit = 'account.journal' _columns = { 'group_invoice_lines_by_account': fields.boolean( 'Group lines depending on account', help= 'If checked, the account move lines linked to this journal will be grouped (if possible) during their creation at the moment of invoice validation.' ), } _defaults = { 'group_invoice_lines_by_account': False, }
class labtest (osv.osv): _name = "medical.patient.lab.test" _inherit = "medical.patient.lab.test" _columns = { 'no_invoice' : fields.boolean ('Invoice exempt'), 'invoice_status' : fields.selection([('invoiced','Invoiced'),('tobe','To be Invoiced')],'Invoice Status'), } _defaults={ 'invoice_status': lambda *a: 'tobe', 'no_invoice': lambda *a: True }
class patient_prescription_order (osv.osv): _name = "medical.prescription.order" _inherit = "medical.prescription.order" _columns = { 'no_invoice' : fields.boolean ('Invoice exempt'), 'invoice_status' : fields.selection([('invoiced','Invoiced'),('tobe','To be Invoiced')],'Invoice Status'), } _defaults = { 'invoice_status': lambda *a: 'tobe', 'no_invoice': lambda *a: True }
class account_journal(orm.Model): _inherit = 'account.journal' _columns = { 'check_previous_date': fields.boolean( 'Controllo data in registrazioni precedenti', help= 'If checked, the entry won\'t be created if the entry date is not coherent with the other registrations in the same journal' ), } _defaults = { 'check_previous_date': True, }
class policy_line_absence(models.Model): _name = 'hr.policy.line.absence' _columns = { 'name': fields.char('Name', size=64, required=True), 'code': fields.char('Code', required=True, help="Use this code in the salary rules."), 'holiday_status_id': fields.many2one('hr.holidays.status', 'Leave', required=True), 'policy_id': fields.many2one('hr.policy.absence', 'Policy'), 'type': fields.selection( [('paid', 'Paid'), ('unpaid', 'Unpaid'), ('dock', 'Dock')], 'Type', required=True, help="Determines how the absence will be treated in payroll. " "The 'Dock Salary' type will deduct money (useful for " "salaried employees).", ), 'rate': fields.float('Rate', required=True, help='Multiplier of employee wage.'), 'use_awol': fields.boolean( 'Absent Without Leave', help='Use this policy to record employee time absence not covered ' 'by other leaves.') } def onchange_holiday(self, cr, uid, ids, holiday_status_id, context=None): res = {'value': {'name': False, 'code': False}} if not holiday_status_id: return res data = self.pool.get('hr.holidays.status').read(cr, uid, holiday_status_id, ['name', 'code'], context=context) res['value']['name'] = data['name'] res['value']['code'] = data['code'] return res
class res_users(osv.osv): _name = 'res.users' _inherit = 'res.users' _columns = { 'live_support': fields.boolean(string='Live Support', help='Approved For Live support') } def check_support(self, cr, uid): if uid: context = {} obj_user = self.pool.get('res.users').browse(cr, uid, uid) if (obj_user.live_support == True): return True else: return False
class product_product(osv.Model): _inherit = 'product.product' _columns = { 'wk_order_allow': fields.selection(( ('allow', 'Allow Order'), ('deny', 'Deny Orders'), ), 'When Product is out of Stock'), 'wk_in_stock_msg': fields.char('Message'), 'wk_out_of_stock_msg': fields.char('Message'), 'wk_override_default': fields.boolean('Override Default Message') } _defaults = { 'wk_order_allow': 'deny', 'wk_in_stock_msg': 'In Stock', 'wk_out_of_stock_msg': 'This product has gone out of Stock!' }
class WizardDailyReport(osv.TransientModel): _name='wiz.daily.report' _description='daily reporting of customer entries' _columns = { 'date': fields.date('Date', required=True), 'company_id_invoice': fields.many2one('res.company', 'Company ID', required=True), 'journal_id_daily': fields.many2one('account.journal', 'Journal ID'), 'select_all':fields.boolean('Select All Journals',store=True) } _defaults = { 'date': lambda *a: datetime.now().strftime('%Y-%m-%d') } def fetch_record(self): state = 'posted' value='and jour_it.journal_id=' + "'" + str(self.journal_id_daily.id) + "' " select_all_journal= value if not self.select_all else ' ' self.env.cr.execute( 'select jour_en.name journal_entry,jour_it.ref,part.name partner_name,part.cs_number cs_number,acc_jou.name journal,acc_acc.name account_name,jour_en.date,jour_it.credit,jour_it.debit from public.account_move_line jour_it' + ' left join public.account_move jour_en on jour_it.move_id=jour_en.id ' + 'left join public.res_partner part on jour_it.partner_id=part.id ' + 'left join public.account_journal acc_jou on jour_it.journal_id=acc_jou.id ' + 'left join public.account_account acc_acc on jour_it.account_id=acc_acc.id' + ' where jour_it.date = ' + "'" + self.date + "'" + ' and jour_it.company_id=' + "'" + str( self.company_id_invoice.id) + "'" +select_all_journal+ 'and jour_en.state=' + "'" + state + "'" + ' order by jour_en.name asc,jour_it.debit desc') daily_list = self.env.cr.dictfetchall() return daily_list def print_report(self, cr, uid, ids, data, context=None): return { 'type': 'ir.actions.report.xml', 'name': 'mutual_accounts_inventory.report_daily_report', 'report_name': 'mutual_accounts_inventory.report_daily_report' }
class contract_init(models.Model): _name = 'hr.contract.init' _description = 'Initial Contract Settings' _inherit = 'ir.needaction_mixin' _columns = { 'name': fields.char( 'Name', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}, ), 'date': fields.date( 'Effective Date', required=True, readonly=True, states={'draft': [('readonly', False)]}, ), 'wage_ids': fields.one2many( 'hr.contract.init.wage', 'contract_init_id', 'Starting Wages', readonly=True, states={'draft': [('readonly', False)]}, ), 'struct_id': fields.many2one( 'hr.payroll.structure', 'Payroll Structure', readonly=True, states={'draft': [('readonly', False)]}, ), 'trial_period': fields.integer( 'Trial Period', readonly=True, states={'draft': [('readonly', False)]}, help="Length of Trial Period, in days", ), 'active': fields.boolean('Active', ), 'state': fields.selection( [ ('draft', 'Draft'), ('approve', 'Approved'), ('decline', 'Declined'), ], 'State', readonly=True, ), } _defaults = { 'trial_period': 0, 'active': True, 'state': 'draft', } # Return records with latest date first _order = 'date desc' def _needaction_domain_get(self, cr, uid, context=None): users_obj = self.pool.get('res.users') if users_obj.has_group(cr, uid, 'base.group_hr_director'): domain = [('state', 'in', ['draft'])] return domain return False def unlink(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] data = self.read(cr, uid, ids, ['state'], context=context) for d in data: if d['state'] in ['approve', 'decline']: raise models.except_orm( _('Error'), _('You may not a delete a record that is not in a ' '"Draft" state')) return super(contract_init, self).unlink(cr, uid, ids, context=context) def set_to_draft(self, cr, uid, ids, context=None): self.write(cr, uid, ids, { 'state': 'draft', }, context=context) wf_service = netsvc.LocalService("workflow") for i in ids: wf_service.trg_delete(uid, 'hr.contract.init', i, cr) wf_service.trg_create(uid, 'hr.contract.init', i, cr) return True def state_approve(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'approve'}, context=context) return True def state_decline(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'decline'}, context=context) return True
class SalesSummaryReport(osv.TransientModel): _name = 'wiz.sales.summary' _description = 'PDF Report for showing all active ,disco and news sale accounts' _columns = { 'start_date': fields.date('Start Date', required=True), 'end_date': fields.date('End Date', required=True), 'only_new_sales': fields.boolean('Only New Sales') } _defaults = { 'start_date': lambda *a: datetime.now().strftime('%Y-%m-%d'), 'end_date': lambda *a: datetime.now().strftime('%Y-%m-%d'), } def new_sales(self): frequency = { 'cm': 0, 'cn': 0, 'lh': 0, 'b1': 0, 'b2': 0, 'b3': 0, } self.env.cr.execute( "SELECT res_partner.cs_number,res_partner.name as customer,res_company.name as company,sale_order.name,sale_order.payment_received,sale_order.amount_total FROM sale_order INNER JOIN res_partner ON sale_order.partner_id = res_partner.id INNER JOIN res_company ON res_partner.company_id = res_company.id where sale_order.status='NewInstallation' and sale_order.sale_confirm_date between " + "'" + str(self.start_date) + "'" + "and" + "'" + str(self.end_date) + "'" + " and state != 'draft' order by res_partner.cs_number") current_sales = self.env.cr.dictfetchall() if self.only_new_sales: return current_sales else: for cs in current_sales: if cs['cs_number'].find('CM') != -1 or cs['cs_number'].find( 'cm') != -1: frequency['cm'] += 1 elif cs['cs_number'].find('CN') != -1 or cs['cs_number'].find( 'cn') != -1: frequency['cn'] += 1 elif cs['cs_number'].find('LH') != -1 or cs['cs_number'].find( 'cm') != -1: frequency['lh'] += 1 elif cs['cs_number'].find('B1') != -1 or cs['cs_number'].find( 'b1') != -1: frequency['b1'] += 1 elif cs['cs_number'].find('B2') != -1 or cs['cs_number'].find( 'b2') != -1: frequency['b2'] += 1 elif cs['cs_number'].find('B3') != -1 or cs['cs_number'].find( 'b3') != -1: frequency['b3'] += 1 return frequency def ms_record(self): # "Active Customers Of Mutual Security Systems" self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CM%' and active=True and company_id=3" ) cm_active_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CN%' and active=True and company_id=3" ) cn_active_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%LH%' and active=True and company_id=3" ) lh_active_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B1%' and active=True and company_id=3" ) b1_active_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B2%' and active=True and company_id=3" ) b2_active_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B3%' and active=True and company_id=3" ) b3_active_ms = self.env.cr.dictfetchall() # "InActive Customers Of Mutual Security Systems" self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CM%' and active=False and cs_number is not null and company_id=3" ) cm_inactive_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CN%' and active=False and cs_number is not null and company_id=3" ) cn_inactive_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%LH%' and active=False and cs_number is not null and company_id=3" ) lh_inactive_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B1%' and active=False and cs_number is not null and company_id=3" ) b1_inactive_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B2%' and active=False and cs_number is not null and company_id=3" ) b2_inactive_ms = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B3%' and active=False and cs_number is not null and company_id=3" ) b3_inactive_ms = self.env.cr.dictfetchall() return [ { 'code': 'CM', 'active_customer': cm_active_ms[0]['cs_number'], 'inactive_customer': cm_inactive_ms[0]['cs_number'] }, { 'code': 'CN', 'active_customer': cn_active_ms[0]['cs_number'], 'inactive_customer': cn_inactive_ms[0]['cs_number'] }, { 'code': 'LH', 'active_customer': lh_active_ms[0]['cs_number'], 'inactive_customer': lh_inactive_ms[0]['cs_number'] }, { 'code': 'B1', 'active_customer': b1_active_ms[0]['cs_number'], 'inactive_customer': b1_inactive_ms[0]['cs_number'] }, { 'code': 'B2', 'active_customer': b2_active_ms[0]['cs_number'], 'inactive_customer': b2_inactive_ms[0]['cs_number'] }, { 'code': 'B3', 'active_customer': b3_active_ms[0]['cs_number'], 'inactive_customer': b3_inactive_ms[0]['cs_number'] }, ] def mss_record(self): # "Active Customers Of Mutual Security Systems" self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CM%' and active=True and company_id=1" ) cm_active_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CN%' and active=True and company_id=1" ) cn_active_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%LH%' and active=True and company_id=1" ) lh_active_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B1%' and active=True and company_id=1" ) b1_active_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B2%' and active=True and company_id=1" ) b2_active_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B3%' and active=True and company_id=1" ) b3_active_mss = self.env.cr.dictfetchall() # "InActive Customers Of Mutual Security Systems" self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CM%' and active=False and cs_number is not null and company_id=1" ) cm_inactive_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%CN%' and active=False and cs_number is not null and company_id=1" ) cn_inactive_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%LH%' and active=False and cs_number is not null and company_id=1" ) lh_inactive_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B1%' and active=False and cs_number is not null and company_id=1" ) b1_inactive_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B2%' and active=False and cs_number is not null and company_id=1" ) b2_inactive_mss = self.env.cr.dictfetchall() self.env.cr.execute( "SELECT count(cs_number) as cs_number FROM public.res_partner where cs_number like '%B3%' and active=False and cs_number is not null and company_id=1" ) b3_inactive_mss = self.env.cr.dictfetchall() return [ { 'code': 'CM', 'active_customer': cm_active_mss[0]['cs_number'], 'inactive_customer': cm_inactive_mss[0]['cs_number'] }, { 'code': 'CN', 'active_customer': cn_active_mss[0]['cs_number'], 'inactive_customer': cn_inactive_mss[0]['cs_number'] }, { 'code': 'LH', 'active_customer': lh_active_mss[0]['cs_number'], 'inactive_customer': lh_inactive_mss[0]['cs_number'] }, { 'code': 'B1', 'active_customer': b1_active_mss[0]['cs_number'], 'inactive_customer': b1_inactive_mss[0]['cs_number'] }, { 'code': 'B2', 'active_customer': b2_active_mss[0]['cs_number'], 'inactive_customer': b2_inactive_mss[0]['cs_number'] }, { 'code': 'B3', 'active_customer': b3_active_mss[0]['cs_number'], 'inactive_customer': b3_inactive_mss[0]['cs_number'] }, ] def print_report(self, cr, uid, ids, data, context=None): return { 'type': 'ir.actions.report.xml', 'name': 'mutual_sales_summary.report_sales_summary', 'report_name': 'mutual_sales_summary.report_sales_summary' }
class res_partner(osv.osv): _name = "res.partner" _inherit = "res.partner" def _check_length(self, cr, uid, ids, context=None): for partner in self.browse(cr, uid, ids, context=context): if (len(self.browse(cr, uid, ids, context=context).name)) >= 80: return False return True _columns = { 'reference': fields.char('Référence', select=1), 'exoner': fields.boolean('Exonere'), 'revendeur': fields.boolean('Revendeur'), 'timbre': fields.boolean('Timbre'), 'mf': fields.char('M.F', size=64), 'code_tva': fields.char('Code TVA', size=32), 'code_categ': fields.char('Code Categorie', size=32), 'num_etab': fields.char('Num Etablissement', size=32), 'property_account_receivable': fields.property( type='many2one', relation='account.account', string="Account Receivable", domain="[('type', '=', 'receivable')]", help="This account will be used instead of the default one as the receivable account for the current partner", required=True, default=None), } _constraints = [ (_check_length, ' Nom du client trop long.', ['name']) ] def create(self, cr, uid, vals, context=None): if 'child_ids' in vals and vals['child_ids'] : vals['reference'] = self.pool.get('ir.sequence').get(cr, uid, 'partner.reference') # ---------------------------------trouver l'id du partenaire qu'on va créer------------------------------------ cr.execute("SELECT MAX(id) FROM res_partner;") res = cr.fetchall() last_partner_id = res[0][0] new_partner_id = last_partner_id + 1 if 'customer' in vals and vals['customer'] and (vals['use_parent_address']==False): # ---------------------Trouver le code du compte client le plus grand--------------------------------------- cr.execute("SELECT MAX(CAST(code AS bigint))FROM account_account WHERE(code LIKE '411%' AND code ~ '^[0-9\.]+$')") res = cr.fetchall() last_customer_account_code = res[0][0] # ---------------------------------------------------------------------------------------------------------- new_customer_account_code = last_customer_account_code + 1 new_customer_account = self.pool.get('account.account').create(cr, uid,{'code': str(new_customer_account_code),'name': 'Client-' + vals['name'],'parent_id': 226, 'type': "receivable",'user_type': 2, 'active': True,'reconcile':True},context=context) new_property = self.pool.get('ir.property').create(cr, uid, { 'value_reference': "account.account" + "," + str(new_customer_account), 'res_id': "res.partner" + ',' + str(new_partner_id), 'fields_id': 1957}, context=context) if 'supplier' in vals and vals['supplier'] and (vals['use_parent_address']==False): # ---------------------Trouver le code du compte fournisseur le plus grand----------------------------- cr.execute( "SELECT MAX(CAST(code AS bigint))FROM account_account WHERE(code LIKE '401%' AND code ~ '^[0-9\.]+$')") res = cr.fetchall() last_supplier_account_code = res[0][0] # ---------------------------------------------------------------------------------------------------------- new_supplier_account_code = last_supplier_account_code + 1 new_supplier_account = self.pool.get('account.account').create(cr, uid, {'code': str(new_supplier_account_code), 'name': 'Frs-' + vals['name'], 'parent_id': 206, 'type': "payable", 'user_type': 3, 'active': True, 'reconcile': True}, context=context) new_property = self.pool.get('ir.property').create(cr, uid, { 'value_reference': "account.account" + "," + str(new_supplier_account), 'res_id': "res.partner" + ',' + str(new_partner_id), 'fields_id': 1960} , context=context) return super(res_partner, self).create(cr, uid, vals, context) def unlink(self, cr, uid, ids, context=None): partner_id = self.browse(cr, uid, ids[0], context=context).id cr.execute("SELECT id FROM ir_property WHERE res_id LIKE '%" + str(partner_id) + "%'") res = cr.fetchall() properties_ids = [] accounts_ids = [] for i in range(len(res)): properties_ids.append(int(res[i][0])) cr.execute("SELECT SUBSTR(value_reference,17,10) FROM ir_property WHERE res_id LIKE '%" + str(partner_id) + "%'") res = cr.fetchall() for i in range(len(res)): accounts_ids.append(int(res[i][0])) # ---------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------------------- self.pool.get('ir.property').unlink(cr, uid, properties_ids, context=None) self.pool.get('account.account').unlink(cr, uid, accounts_ids, context=None) res = super(res_partner, self).unlink(cr, uid, ids, context=context) return res
class WizardReport(models.TransientModel): _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'), # ~ 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['res.company']._company_default_get( cr, uid, 'account.invoice', context=c), 'fiscalyear': lambda self, cr, uid, c: self.pool['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({ '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 = self.pool['res.users'].browse(cr, uid, uid, context=context) if user.company_id: company_id = user.company_id.id else: company_id = self.pool['res.company'].search( cr, uid, [('parent_id', '=', False)])[0] data['form']['company_id'] = company_id fiscalyear_obj = self.pool['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 }
class product_uom(osv.osv): _name = 'product.uom' _inherit = 'product.uom' _description = 'Product Unit of Measure' _columns = {'on_formula': fields.boolean('On Formulation (m3)')}
class AccountVoucher(osv.osv): _inherit = "account.voucher" @api.one @api.depends('currency_id', 'payment_rate_currency_id', 'payment_rate', 'amount', 'date', 'journal_id') def _compute_rate_amount(self): print "--_compute_rate_amount-" if self.currency_id != self.payment_rate_currency_id: currency_obj = self.env['res.currency'] currency_str = payment_rate_str = '' if self.currency_id: currency_str = currency_obj.browse(self.currency_id.id) if self.payment_rate_currency_id: payment_rate_str = currency_obj.browse(self.payment_rate_currency_id.id) #currency_payment = currency_obj.browse(self.currency_id.id)#.rate amount_curr = u'%s\N{NO-BREAK SPACE}%s' % (currency_str.symbol, locale.format("%d", payment_rate_str.rate, grouping=True))#formatLang(self.env, currency_payment.rate, currency_obj=self.currency_id) amount_curr_payment = u'%s\N{NO-BREAK SPACE}%s' % (payment_rate_str.symbol, locale.format("%d", currency_str.rate, grouping=True)) #print "====",self.date,currency_str.rate,payment_rate_str.rate currency_help_label = _('The exchange rate was %s = %s') % (amount_curr, amount_curr_payment) self.amount_info = self.amount * currency_str.rate self.currency_inverse_help_label = currency_help_label def _get_currency_help_label(self, cr, uid, currency_id, payment_rate, payment_rate_currency_id, context=None): rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context) currency_pool = self.pool.get('res.currency') currency_str = payment_rate_str = '' if currency_id: currency_str = rml_parser.formatLang(1, currency_obj=currency_pool.browse(cr, uid, currency_id, context=context)) if payment_rate_currency_id: payment_rate_str = rml_parser.formatLang(currency_pool.browse(cr, uid, currency_id, context=context).rate, currency_obj=currency_pool.browse(cr, uid, payment_rate_currency_id, context=context)) currency_help_label = _('At the operation date, the exchange rate was\n%s = %s') % (currency_str, payment_rate_str) return currency_help_label def _fnct_currency_help_label(self, cr, uid, ids, name, args, context=None): res = {} for voucher in self.browse(cr, uid, ids, context=context): res[voucher.id] = self._get_currency_help_label(cr, uid, voucher.currency_id.id, voucher.payment_rate, voucher.company_currency_id.id, context=context) return res def _get_amount_help_label(self, cr, uid, currency_id, payment_rate, payment_rate_currency_id, context=None): # rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context) currency_pool = self.pool.get('res.currency') # currency_str = payment_rate_str = '' if currency_id: #print "=======",currency_pool.browse(cr, uid, currency_id, context=context).rate # currency_str = rml_parser.formatLang(1, currency_obj=currency_pool.browse(cr, uid, currency_id, context=context)) # if payment_rate_currency_id: # payment_rate_str = rml_parser.formatLang(currency_pool.browse(cr, uid, currency_id, context=context).rate, currency_obj=currency_pool.browse(cr, uid, payment_rate_currency_id, context=context)) # currency_help_label = _('At the operation date, the exchange rate was\n%s = %s') % (currency_str, payment_rate_str) return str(payment_rate*currency_pool.browse(cr, uid, currency_id, context=context).rate) def _fnct_amount_info_label(self, cr, uid, ids, name, args, context=None): res = {} for voucher in self.browse(cr, uid, ids, context=context): res[voucher.id] = self._get_amount_help_label(cr, uid, voucher.currency_id.id, voucher.amount, voucher.company_currency_id.id, context=context) return res _columns = { 'is_currency': fields.boolean('Is multi currency'), 'amount_info': fields.function(_fnct_amount_info_label, type='float', string='Amount Rate'), 'currency_inverse_help_label': fields.text('Rate'), 'company_currency_id': fields.related('company_id','currency_id', type='many2one', relation='res.currency', string='Company Currency'), 'currency_help_label': fields.function(_fnct_currency_help_label, type='text', string="Helping Sentence", help="This sentence helps you to know how to specify the payment rate by giving you the direct effect it has"), } # is_currency = fields.Boolean('Is multi currency') # amount_info = fields.Float(string='Amount Rate', compute='_compute_rate_amount') # currency_inverse_help_label = fields.Text(string='Helping Rate Sentence', compute='_compute_rate_amount') def onchange_rate(self, cr, uid, ids, rate, amount, currency_id, payment_rate_currency_id, company_id, context=None): company_currency = self.pool.get('res.company').browse(cr, uid, company_id, context=context).currency_id #currency_pool = self.pool.get('res.currency') #rate_view = currency_pool.browse(cr, uid, currency_id, context=context).rate #print "==onchange_rate==",amount,rate,rate_view,amount*rate_view res = {'value': {'paid_amount_in_company_currency': amount, 'amount_info': self._get_amount_help_label(cr, uid, currency_id, amount, company_currency.id, context=context), 'currency_help_label': self._get_currency_help_label(cr, uid, currency_id, rate, payment_rate_currency_id, context=context)}} if rate and amount and currency_id: company_currency = self.pool.get('res.company').browse(cr, uid, company_id, context=context).currency_id #context should contain the date, the payment currency and the payment rate specified on the voucher amount_in_company_currency = self.pool.get('res.currency').compute(cr, uid, currency_id, company_currency.id, amount, context=context) res['value']['paid_amount_in_company_currency'] = amount_in_company_currency return res def onchange_journal(self, cr, uid, ids, journal_id, line_ids, tax_id, partner_id, date, amount, ttype, company_id, context=None): if context is None: context = {} if not journal_id: return False journal_pool = self.pool.get('account.journal') journal = journal_pool.browse(cr, uid, journal_id, context=context) if ttype in ('sale', 'receipt'): account_id = journal.default_debit_account_id elif ttype in ('purchase', 'payment'): account_id = journal.default_credit_account_id else: account_id = journal.default_credit_account_id or journal.default_debit_account_id tax_id = False if account_id and account_id.tax_ids: tax_id = account_id.tax_ids[0].id vals = {'value':{} } if ttype in ('sale', 'purchase'): vals = self.onchange_price(cr, uid, ids, line_ids, tax_id, partner_id, context) vals['value'].update({'tax_id':tax_id,'amount': amount}) currency_id = False if journal.currency: currency_id = journal.currency.id else: currency_id = journal.company_id.currency_id.id period_ids = self.pool['account.period'].find(cr, uid, dt=date, context=dict(context, company_id=company_id)) is_currency = False if journal.currency.id and journal.currency.id != journal.company_id.currency_id.id: is_currency = True #print "===is_currency====",is_currency,journal.currency.id,journal.company_id.currency_id.id vals['value'].update({ 'currency_id': currency_id, 'payment_rate_currency_id': currency_id, 'is_currency': is_currency, 'period_id': period_ids and period_ids[0] or False }) #in case we want to register the payment directly from an invoice, it's confusing to allow to switch the journal #without seeing that the amount is expressed in the journal currency, and not in the invoice currency. So to avoid #this common mistake, we simply reset the amount to 0 if the currency is not the invoice currency. if context.get('payment_expected_currency') and currency_id != context.get('payment_expected_currency'): vals['value']['amount'] = 0 amount = 0 if partner_id: res = self.onchange_partner_id(cr, uid, ids, partner_id, journal_id, amount, currency_id, ttype, date, context) for key in res.keys(): vals[key].update(res[key]) return vals
class WizardTechnicianInventory(osv.TransientModel): _name = 'wiz.technician.inventory' _description = 'Generate Report for Technician Inventory' _columns = { 'partner_id': fields.many2one('res.partner', 'Technician'), 'all_rec': fields.boolean('Choose all Technician') } _default = { 'all_rec': False, } def fetch_record(self): self.env.cr.execute( """select id from res_partner where is_technician=True""") all_part = self.env.cr.dictfetchall() all_id = '' for a in all_part: all_id += str(a["id"]) + ',' if self.all_rec is False: self.env.cr.execute( """select sw.code,sw.partner_id,sq.product_id,pp.name_template,sum(sq.qty) as qty from stock_quant sq inner join stock_location sl on sq.location_id=sl.id inner join stock_warehouse sw on sl.id=sw.lot_stock_id inner join product_product pp on sq.product_id=pp.id where sq.qty>0 and sw.partner_id=""" + str(self.partner_id.id) + " group by sw.code,sw.partner_id,sq.product_id,pp.name_template" ) products = self.env.cr.dictfetchall() return self.create_prod_list(products, 1) else: self.env.cr.execute( """select sw.code,sw.partner_id,sq.product_id,pp.name_template,sum(sq.qty) as qty from stock_quant sq inner join stock_location sl on sq.location_id=sl.id inner join stock_warehouse sw on sl.id=sw.lot_stock_id inner join product_product pp on sq.product_id=pp.id where sq.qty>0 and sw.partner_id in (""" + all_id[:-1] + ")" + " group by sw.code,sw.partner_id,sq.product_id,pp.name_template" ) products = self.env.cr.dictfetchall() return self.create_prod_list(products, 2) def create_prod_list(self, product, all_or_one): new_sort_list = sorted(product, key=lambda k: (k['partner_id'], k['product_id'])) # for n in new_sort_list: tech_name = str(new_sort_list[0]['code']) tech_id = str(new_sort_list[0]['partner_id']) # print tech_name prodlist = [] return_list = [] # count = 1 if all_or_one == 2: for index, prod1 in enumerate(new_sort_list): if len(prodlist) == 0: prodlist.append(prod1) for prod2 in new_sort_list[index + 1:]: if tech_name == str( prod2["code"]) and prod2 not in prodlist: # print "if name not equal" prodlist.append(prod2) if tech_name != str(prod1['code']): # count += 1 # print ">>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<" # print tech_name # print prodlist # print ">>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<" list = self.env['res.partner'].search([ ['id', '=', tech_id], ]) # print list.name,list.id dict1 = { 'name': list.name, 'designation': list.function, 'city': list.city, 'address': list.street, 'items': prodlist } return_list.append(dict1) tech_name = prod1['code'] tech_id = prod1['partner_id'] prodlist = [] # print ">>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<" # print dict1 # print ">>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<" return return_list prodlist = [] elif all_or_one == 1: for item in new_sort_list: prodlist.append(item) list = self.env['res.partner'].search([ ['id', '=', tech_id], ]) # print list.name,list.id dict1 = { 'name': list.name, 'designation': list.function, 'city': list.city, 'address': list.street, 'items': prodlist } return_list.append(dict1) tech_name = item['code'] tech_id = item['partner_id'] return return_list def print_report(self, cr, uid, ids, data, context=None): return { 'type': 'ir.actions.report.xml', 'name': 'mutual_project.report_technician_inventory', 'report_name': 'mutual_project.report_technician_inventory' }
class product_product(osv.osv): _inherit = "product.product" @api.one @api.onchange('lst_price') # if these fields are changed, call method def check_change_price(self): #import pdb;pdb.set_trace(); pricelists = self.env['product.pricelist'].search([]) pricelist = pricelists[0] return {} def product_meli_get_products( self, cr, uid, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') #product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI) #url_login_oerp = "/meli_login" response = meli.get("/users/"+company.mercadolibre_seller_id+"/items/search", {'access_token':meli.access_token}) print "product_meli_get_products: " + response.content rjson = response.json() if 'error' in rjson: if rjson['message']=='invalid_token' or rjson['message']=='expired_token': ACCESS_TOKEN = '' REFRESH_TOKEN = '' company.write({'mercadolibre_access_token': ACCESS_TOKEN, 'mercadolibre_refresh_token': REFRESH_TOKEN, 'mercadolibre_code': '' } ) return { "type": "ir.actions.act_url", "url": url_login_meli, "target": "new", } results = rjson['results'] if (results): for item_id in results: print item_id posting_id = self.pool.get('product.product').search(cr,uid,[('meli_id','=',item_id)]) response = meli.get("/items/"+item_id, {'access_token':meli.access_token}) rjson = response.json() if (posting_id): print "Item already in database: " + str(posting_id[0]) else: idcreated = self.pool.get('product.product').create(cr,uid,{ 'name': rjson['title'], 'meli_id': rjson['id'] }) if (idcreated): product = product_obj.browse(cr, uid, idcreated) product_obj.product_meli_get_product( cr, uid, [idcreated] ) return {} def product_meli_get_product( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) product_template_obj = self.pool.get('product.template') product_template = product_template_obj.browse(cr, uid, product.product_tmpl_id.id) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token}) print "product_meli_get_product: " + response.content rjson = response.json() des = '' desplain = '' vid = '' if 'error' in rjson: return {} #TODO: traer la descripcion: con #https://api.mercadolibre.com/items/{ITEM_ID}/description?access_token=$ACCESS_TOKEN if rjson['descriptions']: response2 = meli.get("/items/"+product.meli_id+"/description", {'access_token':meli.access_token}) rjson2 = response2.json() des = rjson2['text'] desplain = rjson2['plain_text'] if (len(des)>0): desplain = des #TODO: verificar q es un video if rjson['video_id']: vid = '' #TODO: traer las imagenes #TODO: pictures = rjson['pictures'] if pictures and len(pictures): thumbnail_url = pictures[0]['url'] image = urllib2.urlopen(thumbnail_url).read() image_base64 = base64.encodestring(image) product.image_medium = image_base64 #if (len(pictures)>1): #complete product images: #delete all images... #categories mlcatid = "" if ('category_id' in rjson): category_id = rjson['category_id'] ml_cat_id = self.pool.get('mercadolibre.category').search(cr,uid,[('meli_category_id','=',category_id)]) if (ml_cat_id): print "category exists!" + str(ml_cat_id) mlcatid = ml_cat_id[0] else: print "Creating category: " + str(category_id) #https://api.mercadolibre.com/categories/MLA1743 response_cat = meli.get("/categories/"+str(category_id), {'access_token':meli.access_token}) rjson_cat = response_cat.json() print "category:" + str(rjson_cat) fullname = "" if ("path_from_root" in rjson_cat): path_from_root = rjson_cat["path_from_root"] for path in path_from_root: fullname = fullname + "/" + path["name"] #fullname = fullname + "/" + rjson_cat['name'] print "category fullname:" + fullname cat_fields = { 'name': fullname, 'meli_category_id': ''+str(category_id), } ml_cat_id = self.pool.get('mercadolibre.category').create(cr,uid,(cat_fields)) if (ml_cat_id): mlcatid = ml_cat_id imagen_id = '' if (len(rjson['pictures'])>0): imagen_id = rjson['pictures'][0]['id'] meli_fields = { 'name': str(rjson['title']), 'meli_imagen_id': imagen_id, 'meli_post_required': True, 'meli_id': rjson['id'], 'meli_permalink': rjson['permalink'], 'meli_title': rjson['title'], 'meli_description': desplain, # 'meli_description_banner_id': , 'meli_category': mlcatid, 'meli_listing_type': rjson['listing_type_id'], 'meli_buying_mode':rjson['buying_mode'], 'meli_price': str(rjson['price']), 'meli_price_fixed': True, 'meli_currency': rjson['currency_id'], 'meli_condition': rjson['condition'], 'meli_available_quantity': rjson['available_quantity'], 'meli_warranty': rjson['warranty'], ## 'meli_imagen_logo': fields.char(string='Imagen Logo', size=256), ## 'meli_imagen_id': fields.char(string='Imagen Id', size=256), 'meli_imagen_link': rjson['thumbnail'], ## 'meli_multi_imagen_id': fields.char(string='Multi Imagen Ids', size=512), 'meli_video': str(vid) } tmpl_fields = { 'name': str(rjson['title']) } product.write( meli_fields ) product_template.write( tmpl_fields ) #{"id":"MLA639109219","site_id":"MLA","title":"Disco Vinilo Queen - Rock - A Kind Of Magic","subtitle":null,"seller_id":171329758,"category_id":"MLA2038","official_store_id":null,"price":31,"base_price":31,"original_price":null,"currency_id":"ARS","initial_quantity":5,"available_quantity":5,"sold_quantity":0,"buying_mode":"buy_it_now","listing_type_id":"free","start_time":"2016-10-17T20:36:22.000Z","stop_time":"2016-12-16T20:36:22.000Z","end_time":"2016-12-16T20:36:22.000Z","expiration_time":null,"condition":"used","permalink":"http://articulo.mercadolibre.com.ar/MLA-639109219-disco-vinilo-queen-rock-a-kind-of-magic-_JM","thumbnail":"http://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-I.jpg","secure_thumbnail":"https://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-I.jpg","pictures":[{"id":"256905-MLA25108641321_102016","url":"http://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-O.jpg","secure_url":"https://mla-s1-p.mlstatic.com/256905-MLA25108641321_102016-O.jpg","size":"500x400","max_size":"960x768","quality":""},{"id":"185215-MLA25150338489_112016","url":"http://www.mercadolibre.com/jm/img?s=STC&v=O&f=proccesing_image_es.jpg","secure_url":"https://www.mercadolibre.com/jm/img?s=STC&v=O&f=proccesing_image_es.jpg","size":"500x500","max_size":"500x500","quality":""}],"video_id":null,"descriptions":[{"id":"MLA639109219-1196717922"}],"accepts_mercadopago":true,"non_mercado_pago_payment_methods":[],"shipping":{"mode":"not_specified","local_pick_up":false,"free_shipping":false,"methods":[],"dimensions":null,"tags":[]},"international_delivery_mode":"none","seller_address":{"id":193196973,"comment":"3B","address_line":"Billinghurst 1711","zip_code":"1425","city":{"id":"TUxBQlBBTDI1MTVa","name":"Palermo"},"state":{"id":"AR-C","name":"Capital Federal"},"country":{"id":"AR","name":"Argentina"},"latitude":-34.5906131,"longitude":-58.4101982,"search_location":{"neighborhood":{"id":"TUxBQlBBTDI1MTVa","name":"Palermo"},"city":{"id":"TUxBQ0NBUGZlZG1sYQ","name":"Capital Federal"},"state":{"id":"TUxBUENBUGw3M2E1","name":"Capital Federal"}}},"seller_contact":null,"location":{},"geolocation":{"latitude":-34.5906131,"longitude":-58.4101982},"coverage_areas":[],"attributes":[],"warnings":[],"listing_source":"","variations":[],"status":"active","sub_status":[],"tags":[],"warranty":null,"catalog_product_id":null,"domain_id":null,"seller_custom_field":null,"parent_item_id":null,"differential_pricing":null,"deal_ids":[],"automatic_relist":false,"date_created":"2016-10-17T20:36:22.000Z","last_updated":"2016-11-07T21:38:10.000Z"} return {} def product_meli_login(self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id REDIRECT_URI = company.mercadolibre_redirect_uri CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET) url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI) #url_login_oerp = "/meli_login" return { "type": "ir.actions.act_url", "url": url_login_meli, "target": "new", } def product_get_meli_loginstate( self, cr, uid, ids, field_name, attributes, context=None ): # recoger el estado y devolver True o False (meli) #False if logged ok #True if need login user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) ML_state = False if ACCESS_TOKEN=='': ML_state = True else: response = meli.get("/users/me/", {'access_token':meli.access_token} ) rjson = response.json() if 'error' in rjson: if rjson['message']=='invalid_token' or rjson['message']=='expired_token': ACCESS_TOKEN = '' REFRESH_TOKEN = '' company.write({'mercadolibre_access_token': ACCESS_TOKEN, 'mercadolibre_refresh_token': REFRESH_TOKEN, 'mercadolibre_code': '' } ) ML_state = True #raise osv.except_osv( _('MELI WARNING'), _('INVALID TOKEN (must login, go to Edit Company and login): error: %s, message: %s, status: %s') % ( rjson["error"], rjson["message"],rjson["status"],)) res = {} for product in self.browse(cr,uid,ids): res[product.id] = ML_state return res def product_meli_status_close( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) response = meli.put("/items/"+product.meli_id, { 'status': 'closed' }, {'access_token':meli.access_token}) #print "product_meli_status_close: " + response.content return {} def product_meli_status_pause( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) response = meli.put("/items/"+product.meli_id, { 'status': 'paused' }, {'access_token':meli.access_token}) #print "product_meli_status_pause: " + response.content return {} def product_meli_status_active( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) response = meli.put("/items/"+product.meli_id, { 'status': 'active' }, {'access_token':meli.access_token}) #print "product_meli_status_active: " + response.content return {} def product_meli_delete( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) if product.meli_status!='closed': self.product_meli_status_close( cr, uid, ids, context ) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) response = meli.put("/items/"+product.meli_id, { 'deleted': 'true' }, {'access_token':meli.access_token}) #print "product_meli_delete: " + response.content rjson = response.json() ML_status = rjson["status"] if "error" in rjson: ML_status = rjson["error"] if "sub_status" in rjson: if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted': product.write({ 'meli_id': '' }) return {} def product_meli_upload_image( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token # meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) if product.image==None or product.image==False: return { 'status': 'error', 'message': 'no image to upload' } # print "product_meli_upload_image" #print "product_meli_upload_image: " + response.content imagebin = base64.b64decode(product.image) imageb64 = product.image # print "data:image/png;base64,"+imageb64 # files = [ ('images', ('image_medium', imagebin, "image/png")) ] files = { 'file': ('image.jpg', imagebin, "image/jpeg"), } #print files response = meli.upload("/pictures", files, { 'access_token': meli.access_token } ) # print response.content rjson = response.json() if ("error" in rjson): raise osv.except_osv( _('MELI WARNING'), _('No se pudo cargar la imagen en MELI! Error: %s , Mensaje: %s, Status: %s') % ( rjson["error"], rjson["message"],rjson["status"],)) return { 'status': 'error', 'message': 'not uploaded'} _logger.info( rjson ) if ("id" in rjson): #guardar id product.write( { "meli_imagen_id": rjson["id"], "meli_imagen_link": rjson["variations"][0]["url"] }) #asociar imagen a producto if product.meli_id: response = meli.post("/items/"+product.meli_id+"/pictures", { 'id': rjson["id"] }, { 'access_token': meli.access_token } ) else: return { 'status': 'warning', 'message': 'uploaded but not assigned' } return { 'status': 'success', 'message': 'uploaded and assigned' } def product_meli_upload_multi_images( self, cr, uid, ids, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token # meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) if product.images==None: return { 'status': 'error', 'message': 'no images to upload' } image_ids = [] c = 0 #loop over images for product_image in product.images: if (product_image.image): print "product_image.image:" + str(product_image.image) imagebin = base64.b64decode( product_image.image ) #files = { 'file': ('image.png', imagebin, "image/png"), } files = { 'file': ('image.jpg', imagebin, "image/jpeg"), } response = meli.upload("/pictures", files, { 'access_token': meli.access_token } ) print "meli upload:" + response.content rjson = response.json() if ("error" in rjson): raise osv.except_osv( _('MELI WARNING'), _('No se pudo cargar la imagen en MELI! Error: %s , Mensaje: %s, Status: %s') % ( rjson["error"], rjson["message"],rjson["status"],)) #return { 'status': 'error', 'message': 'not uploaded'} else: image_ids+= [ { 'id': rjson['id'] }] c = c + 1 print "image_ids:" + str(image_ids) product.write( { "meli_multi_imagen_id": "%s" % (image_ids) } ) return image_ids def product_on_change_meli_banner(self, cr, uid, ids, banner_id ): banner_obj = self.pool.get('mercadolibre.banner') #solo para saber si ya habia una descripcion completada product_obj = self.pool.get('product.product') if len(ids): product = product_obj.browse(cr, uid, ids[0]) else: product = product_obj.browse(cr, uid, ids) banner = banner_obj.browse( cr, uid, banner_id ) #banner.description _logger.info( banner.description ) result = "" if (banner.description!="" and banner.description!=False and product.meli_imagen_link!=""): imgtag = "<img style='width: 420px; height: auto;' src='%s'/>" % ( product.meli_imagen_link ) result = banner.description.replace( "[IMAGEN_PRODUCTO]", imgtag ) if (result): _logger.info( "result: %s" % (result) ) else: result = banner.description return { 'value': { 'meli_description' : result } } def product_get_meli_status( self, cr, uid, ids, field_name, attributes, context=None ): user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id warningobj = self.pool.get('warning') product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token ML_status = "unknown" if ACCESS_TOKEN=='': ML_status = "unknown" else: meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) if product.meli_id: response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token} ) rjson = response.json() ML_status = rjson["status"] if "error" in rjson: ML_status = rjson["error"] if "sub_status" in rjson: if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted': product.write({ 'meli_id': '' }) res = {} for product in self.browse(cr,uid,ids): res[product.id] = ML_status return res def product_get_permalink( self, cr, uid, ids, field_name, attributes, context=None ): ML_permalink = '' user_obj = self.pool.get('res.users').browse(cr, uid, uid) company = user_obj.company_id product_obj = self.pool.get('product.product') product = product_obj.browse(cr, uid, ids[0]) CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token ML_permalink = "" if ACCESS_TOKEN=='': ML_permalink = "" else: meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) if product.meli_id: response = meli.get("/items/"+product.meli_id, {'access_token':meli.access_token} ) rjson = response.json() if "permalink" in rjson: ML_permalink = rjson["permalink"] if "error" in rjson: ML_permalink = "" #if "sub_status" in rjson: #if len(rjson["sub_status"]) and rjson["sub_status"][0]=='deleted': # product.write({ 'meli_id': '' }) res = {} for product in self.browse(cr,uid,ids): res[product.id] = ML_permalink return res def product_post(self, cr, uid, ids, context=None): import pdb;pdb.set_trace(); # product_ids = context['active_ids'] product_ids = ids product_obj = self.pool.get('product.product') user_obj = self.pool.get('res.users').browse(cr, uid, uid) #user_obj.company_id.meli_login() company = user_obj.company_id warningobj = self.pool.get('warning') #company = self.pool.get('res.company').browse(cr,uid,1) REDIRECT_URI = company.mercadolibre_redirect_uri CLIENT_ID = company.mercadolibre_client_id CLIENT_SECRET = company.mercadolibre_secret_key ACCESS_TOKEN = company.mercadolibre_access_token REFRESH_TOKEN = company.mercadolibre_refresh_token meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN) if ACCESS_TOKEN=='': meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET) url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI) return { "type": "ir.actions.act_url", "url": url_login_meli, "target": "new", } for product_id in product_ids: product = product_obj.browse(cr,uid,product_id) if (product.meli_id): response = meli.get("/items/%s" % product.meli_id, {'access_token':meli.access_token}) # print product.meli_category.meli_category_id if product.meli_title==False: # print 'Assigning title: product.meli_title: %s name: %s' % (product.meli_title, product.name) product.meli_title = product.name if product.meli_price==False: # print 'Assigning price: product.meli_price: %s standard_price: %s' % (product.meli_price, product.standard_price) product.meli_price = product.standard_price body = { "title": product.meli_title or '', "description": product.meli_description or '', "category_id": product.meli_category.meli_category_id or '0', "listing_type_id": product.meli_listing_type or '0', "buying_mode": product.meli_buying_mode or '', "price": product.meli_price or '0', "currency_id": product.meli_currency or '0', "condition": product.meli_condition or '', "available_quantity": product.meli_available_quantity or '0', "warranty": product.meli_warranty or '', #"pictures": [ { 'source': product.meli_imagen_logo} ] , "video_id": product.meli_video or '', } # print body assign_img = False and product.meli_id #publicando imagen cargada en OpenERP if product.image==None: return warningobj.info(cr, uid, title='MELI WARNING', message="Debe cargar una imagen de base en el producto.", message_html="" ) elif product.meli_imagen_id==False: # print "try uploading image..." resim = product.product_meli_upload_image() if "status" in resim: if (resim["status"]=="error" or resim["status"]=="warning"): error_msg = 'MELI: mensaje de error: ', resim _logger.error(error_msg) else: assign_img = True and product.meli_imagen_id #modificando datos si ya existe el producto en MLA if (product.meli_id): body = { "title": product.meli_title or '', #"description": product.meli_description or '', #"category_id": product.meli_category.meli_category_id, #"listing_type_id": product.meli_listing_type, "buying_mode": product.meli_buying_mode or '', "price": product.meli_price or '0', #"currency_id": product.meli_currency, "condition": product.meli_condition or '', "available_quantity": product.meli_available_quantity or '0', "warranty": product.meli_warranty or '', "pictures": [], #"pictures": [ { 'source': product.meli_imagen_logo} ] , "video_id": product.meli_video or '', } #publicando multiples imagenes multi_images_ids = {} if (product.images): # print 'website_multi_images presente: ', product.images #recorrer las imagenes y publicarlas multi_images_ids = product.product_meli_upload_multi_images() #asignando imagen de logo (por source) if product.meli_imagen_logo: if product.meli_imagen_id: if 'pictures' in body.keys(): body["pictures"]+= [ { 'id': product.meli_imagen_id } ] else: body["pictures"] = [ { 'id': product.meli_imagen_id } ] if (multi_images_ids): if 'pictures' in body.keys(): body["pictures"]+= multi_images_ids else: body["pictures"] = multi_images_ids if 'pictures' in body.keys(): body["pictures"]+= [ { 'source': product.meli_imagen_logo} ] else: body["pictures"]+= [ { 'source': product.meli_imagen_logo} ] else: imagen_producto = "" if (product.meli_description!="" and product.meli_description!=False and product.meli_imagen_link!=""): imgtag = "<img style='width: 420px; height: auto;' src='%s'/>" % ( product.meli_imagen_link ) result = product.meli_description.replace( "[IMAGEN_PRODUCTO]", imgtag ) if (result): _logger.info( "result: %s" % (result) ) product.meli_description = result else: result = product.meli_description else: return warningobj.info(cr, uid, title='MELI WARNING', message="Debe completar el campo 'Imagen_Logo' con el url: http://www.nuevohorizonte-sa.com.ar/images/logo1.png", message_html="") #check fields if product.meli_description==False: return warningobj.info(cr, uid, title='MELI WARNING', message="Debe completar el campo 'description' (en html)", message_html="") #put for editing, post for creating if product.meli_id: response = meli.put("/items/"+product.meli_id, body, {'access_token':meli.access_token}) else: assign_img = True and product.meli_imagen_id response = meli.post("/items", body, {'access_token':meli.access_token}) #check response # print response.content rjson = response.json() #check error if "error" in rjson: #print "Error received: %s " % rjson["error"] error_msg = 'MELI: mensaje de error: %s , mensaje: %s, status: %s, cause: %s ' % (rjson["error"], rjson["message"], rjson["status"], rjson["cause"]) _logger.error(error_msg) missing_fields = error_msg #expired token if "message" in rjson and (rjson["message"]=='invalid_token' or rjson["message"]=="expired_token"): meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET) url_login_meli = meli.auth_url(redirect_URI=REDIRECT_URI) #print "url_login_meli:", url_login_meli #raise osv.except_osv( _('MELI WARNING'), _('INVALID TOKEN or EXPIRED TOKEN (must login, go to Edit Company and login): error: %s, message: %s, status: %s') % ( rjson["error"], rjson["message"],rjson["status"],)) return warningobj.info(cr, uid, title='MELI WARNING', message="Debe iniciar sesión en MELI. ", message_html="") else: #Any other errors return warningobj.info(cr, uid, title='MELI WARNING', message="Completar todos los campos! ", message_html="<br><br>"+missing_fields ) #last modifications if response is OK if "id" in rjson: product.write( { 'meli_id': rjson["id"]} ) posting_fields = {'posting_date': str(datetime.now()),'meli_id':rjson['id'],'product_id':product.id,'name': 'Post: ' + product.meli_title } posting_id = self.pool.get('mercadolibre.posting').search(cr,uid,[('meli_id','=',rjson['id'])]) if not posting_id: posting_id = self.pool.get('mercadolibre.posting').create(cr,uid,(posting_fields)) return {} _columns = { 'meli_imagen_id': fields.char(string='Imagen Id', size=256), 'meli_post_required': fields.boolean(string='Este producto es publicable en Mercado Libre'), 'meli_id': fields.char( string='Id del item asignado por Meli', size=256), 'meli_permalink': fields.function( product_get_permalink, method=True, type='char', size=256, string='PermaLink in MercadoLibre' ), 'meli_title': fields.char(string='Nombre del producto en Mercado Libre',size=256), 'meli_description': fields.html(string='Descripción'), 'meli_description_banner_id': fields.many2one("mercadolibre.banner","Banner"), 'meli_category': fields.many2one("mercadolibre.category","Categoría de MercadoLibre"), 'meli_listing_type': fields.selection([("free","Libre"),("bronze","Bronce"),("silver","Plata"),("gold","Oro"),("gold_premium","Gold Premium"),("gold_special","Gold Special"),("gold_pro","Oro Pro")], string='Tipo de lista'), 'meli_buying_mode': fields.selection( [("buy_it_now","Compre ahora"),("classified","Clasificado")], string='Método de compra'), 'meli_price': fields.char(string='Precio de venta', size=128), 'meli_price_fixed': fields.boolean(string='Price is fixed'), 'meli_currency': fields.selection([("ARS","Peso Argentino (ARS)")],string='Moneda (ARS)'), 'meli_condition': fields.selection([ ("new", "Nuevo"), ("used", "Usado"), ("not_specified","No especificado")],'Condición del producto'), 'meli_available_quantity': fields.integer(string='Cantidad disponible'), 'meli_warranty': fields.char(string='Garantía', size=256), 'meli_imagen_logo': fields.char(string='Imagen Logo', size=256), 'meli_imagen_id': fields.char(string='Imagen Id', size=256), 'meli_imagen_link': fields.char(string='Imagen Link', size=256), 'meli_multi_imagen_id': fields.char(string='Multi Imagen Ids', size=512), 'meli_video': fields.char( string='Video (id de youtube)', size=256), 'meli_state': fields.function( product_get_meli_loginstate, method=True, type='boolean', string="Inicio de sesión requerida", store=False ), 'meli_status': fields.function( product_get_meli_status, method=True, type='char', size=128, string="Estado del producto en MLA", store=False ), ### Agregar imagen/archivo uno o mas, y la descripcion en HTML... # TODO Agregar el banner } _defaults = { 'meli_imagen_logo': 'None', 'meli_video': '' }
class report_bank_bookunpaid(orm.TransientModel): _name = 'dym.bank.bookunpaid' _description = 'Report Bank Book Unpaid' _columns = { 'start_date': fields.date('Start Date'), 'end_date': fields.date('End Date'), 'start_value_date': fields.date('Start Value Date'), 'end_value_date': fields.date('End Value Date'), 'branch_id': fields.many2one('dym.branch', 'Branch'), 'journal_id': fields.many2one( 'account.journal', 'Journal', domain= "[('type','in',['bank','cash','pettycash']),('branch_id','in',[False,branch_id])]" ), 'projection': fields.boolean(string='Projection'), 'unpaid': fields.boolean(string='Unpaid'), } def branch_id_onchange(self, cr, uid, ids, branch_id, context=None): dom = {} val = {} return {'domain': dom, 'value': val} def print_report(self, cr, uid, ids, context=None): if context is None: context = {} data = self.read(cr, uid, ids)[0] journal_id = data['journal_id'] # start_date = data['start_date'] # end_date = data['end_date'] start_value_date = data['start_value_date'] end_value_date = data['end_value_date'] branch_id = data['branch_id'] data.update({ 'branch_id': branch_id, 'journal_id': journal_id, # 'start_date': start_value_date, # 'end_date': end_value_date, 'start_value_date': start_value_date, 'end_value_date': end_value_date, }) if context.get('xls_export'): return { 'type': 'ir.actions.report.xml', 'report_name': 'dym_report_bank_bookunpaid_xls', 'datas': data } else: context['landscape'] = True return self.pool['report'].get_action( cr, uid, [], 'dym_bank_bookunpaid.report_bank_bookunpaid', data=data, context=context) def xls_export(self, cr, uid, ids, context=None): return self.print_report(cr, uid, ids, context)
class restday(models.TransientModel): _name = 'hr.restday.wizard' _description = 'Schedule Template Change Wizard' _columns = { 'employee_id': fields.many2one( 'hr.employee', 'Employee', required=True, ), 'contract_id': fields.related( 'employee_id', 'contract_id', type='many2one', relation='hr.contract', string='Contract', readonly=True, ), 'st_current_id': fields.many2one( 'hr.schedule.template', 'Current Template', readonly=True, ), 'st_new_id': fields.many2one( 'hr.schedule.template', 'New Template', ), 'permanent': fields.boolean('Make Permanent', ), 'temp_restday': fields.boolean( 'Temporary Rest Day Change', help="If selected, change the rest day to the specified day only " "for the selected schedule.", ), 'dayofweek': fields.selection( [('0', 'Monday'), ('1', 'Tuesday'), ('2', 'Wednesday'), ('3', 'Thursday'), ('4', 'Friday'), ('5', 'Saturday'), ('6', 'Sunday')], 'Rest Day', select=True, ), 'temp_week_start': fields.date('Start of Week', ), 'week_start': fields.date('Start of Week', ), } _defaults = { 'temp_restday': False, } def onchange_employee(self, cr, uid, ids, ee_id, context=None): res = {'value': {'st_current_id': False}} if ee_id: ee = self.pool.get('hr.employee').browse(cr, uid, ee_id, context=None) res['value'][ 'st_current_id'] = ee.contract_id.schedule_template_id.id return res def onchange_week(self, cr, uid, ids, newdate): res = {'value': {'week_start': newdate}} if newdate: d = datetime.strptime(newdate, "%Y-%m-%d") if d.weekday() != 0: res['value']['week_start'] = False return res return res def onchange_temp_week(self, cr, uid, ids, newdate): res = {'value': {'temp_week_start': newdate}} if newdate: d = datetime.strptime(newdate, "%Y-%m-%d") if d.weekday() != 0: res['value']['temp_week_start'] = False return res return res def _create_detail(self, cr, uid, schedule, actual_dayofweek, template_dayofweek, week_start, context=None): # First, see if there's a schedule for the actual dayofweek. # If so, use it. # for worktime in schedule.template_id.worktime_ids: if worktime.dayofweek == actual_dayofweek: template_dayofweek = actual_dayofweek prevutcdtStart = False prevDayofWeek = False user = self.pool.get('res.users').browse(cr, uid, uid, context=context) local_tz = timezone(user.tz) dSchedStart = datetime.strptime(schedule.date_start, OE_DFORMAT).date() dWeekStart = schedule.date_start < week_start and datetime.strptime( week_start, OE_DFORMAT).date() or dSchedStart for worktime in schedule.template_id.worktime_ids: if worktime.dayofweek != template_dayofweek: continue hour, sep, minute = worktime.hour_from.partition(':') toHour, toSep, toMin = worktime.hour_to.partition(':') if len(sep) == 0 or len(toSep) == 0: raise models.except_orm( _('Invalid Time Format'), _('The time should be entered as HH:MM')) # TODO - Someone affected by DST should fix this # dtStart = datetime.strptime( dWeekStart.strftime('%Y-%m-%d') + ' ' + hour + ':' + minute + ':00', '%Y-%m-%d %H:%M:%S') locldtStart = local_tz.localize(dtStart, is_dst=False) utcdtStart = locldtStart.astimezone(utc) if actual_dayofweek != '0': utcdtStart = utcdtStart + \ relativedelta(days=+int(actual_dayofweek)) dDay = utcdtStart.astimezone(local_tz).date() # If this worktime is a continuation (i.e - after lunch) set the # start time based on the difference from the previous record # if prevDayofWeek and prevDayofWeek == actual_dayofweek: prevHour = prevutcdtStart.strftime('%H') prevMin = prevutcdtStart.strftime('%M') curHour = utcdtStart.strftime('%H') curMin = utcdtStart.strftime('%M') delta_seconds = ( datetime.strptime(curHour + ':' + curMin, '%H:%M') - datetime.strptime(prevHour + ':' + prevMin, '%H:%M')).seconds utcdtStart = prevutcdtStart + timedelta(seconds=+delta_seconds) dDay = prevutcdtStart.astimezone(local_tz).date() delta_seconds = ( datetime.strptime(toHour + ':' + toMin, '%H:%M') - datetime.strptime(hour + ':' + minute, '%H:%M')).seconds utcdtEnd = utcdtStart + timedelta(seconds=+delta_seconds) val = { 'name': schedule.name, 'dayofweek': actual_dayofweek, 'day': dDay, 'date_start': utcdtStart.strftime('%Y-%m-%d %H:%M:%S'), 'date_end': utcdtEnd.strftime('%Y-%m-%d %H:%M:%S'), 'schedule_id': schedule.id, } self.pool.get('hr.schedule').write(cr, uid, schedule.id, { 'detail_ids': [(0, 0, val)], }, context=context) prevDayofWeek = worktime.dayofweek prevutcdtStart = utcdtStart def _change_restday(self, cr, uid, employee_id, week_start, dayofweek, context=None): sched_obj = self.pool.get('hr.schedule') sched_detail_obj = self.pool.get('hr.schedule.detail') schedule_ids = sched_obj.search(cr, uid, [('employee_id', '=', employee_id), ('date_start', '<=', week_start), ('date_end', '>=', week_start), ('state', 'not in', ['locked'])], context=context) sched = sched_obj.browse(cr, uid, schedule_ids[0], context=context) dtFirstDay = datetime.strptime(sched.detail_ids[0].date_start, OE_DTFORMAT) date_start = (dtFirstDay.strftime(OE_DFORMAT) < week_start and week_start + ' ' + dtFirstDay.strftime('%H:%M:%S') or dtFirstDay.strftime(OE_DTFORMAT)) dtNextWeek = datetime.strptime(date_start, OE_DTFORMAT) + relativedelta(weeks=+1) # First get the current rest days rest_days = sched_obj.get_rest_days_by_id( cr, uid, sched.id, dtFirstDay.strftime(OE_DFORMAT), context=context) # Next, remove the schedule detail for the new rest day for dtl in sched.detail_ids: if (dtl.date_start < week_start or datetime.strptime( dtl.date_start, OE_DTFORMAT) >= dtNextWeek): continue if dtl.dayofweek == dayofweek: sched_detail_obj.unlink(cr, uid, dtl.id, context=context) # Enter the new rest day(s) # sched_obj = self.pool.get('hr.schedule') nrest_days = [dayofweek] + rest_days[1:] dSchedStart = datetime.strptime(sched.date_start, OE_DFORMAT).date() dWeekStart = sched.date_start < week_start and datetime.strptime( week_start, OE_DFORMAT).date() or dSchedStart if dWeekStart == dSchedStart: sched_obj.add_restdays(cr, uid, sched, 'restday_ids1', rest_days=nrest_days, context=context) elif dWeekStart == dSchedStart + relativedelta(days=+7): sched_obj.add_restdays(cr, uid, sched, 'restday_ids2', rest_days=nrest_days, context=context) elif dWeekStart == dSchedStart + relativedelta(days=+14): sched_obj.add_restdays(cr, uid, sched, 'restday_ids3', rest_days=nrest_days, context=context) elif dWeekStart == dSchedStart + relativedelta(days=+21): sched_obj.add_restdays(cr, uid, sched, 'restday_ids4', rest_days=nrest_days, context=context) elif dWeekStart == dSchedStart + relativedelta(days=+28): sched_obj.add_restdays(cr, uid, sched, 'restday_ids5', rest_days=nrest_days, context=context) # Last, add a schedule detail for the first rest day in the week using # the template for the new (temp) rest day # if len(rest_days) > 0: self._create_detail(cr, uid, sched, str(rest_days[0]), dayofweek, week_start, context=context) def _remove_add_schedule(self, cr, uid, schedule_id, week_start, tpl_id, context=None): """Remove the current schedule and add a new one in its place according to the new template. If the week that the change starts in is not at the beginning of a schedule create two new schedules to accommodate the truncated old one and the partial new one. """ sched_obj = self.pool.get('hr.schedule') sched = sched_obj.browse(cr, uid, schedule_id, context=context) vals2 = False vals1 = { 'name': sched.name, 'employee_id': sched.employee_id.id, 'template_id': tpl_id, 'date_start': sched.date_start, 'date_end': sched.date_end, } if week_start > sched.date_start: dWeekStart = datetime.strptime(week_start, '%Y-%m-%d').date() start_day = dWeekStart.strftime('%Y-%m-%d') vals1['template_id'] = sched.template_id.id vals1['date_end'] = (dWeekStart + relativedelta(days=-1)).strftime('%Y-%m-%d') vals2 = { 'name': (sched.employee_id.name + ': ' + start_day + ' Wk ' + str(dWeekStart.isocalendar()[1])), 'employee_id': sched.employee_id.id, 'template_id': tpl_id, 'date_start': start_day, 'date_end': sched.date_end, } sched_obj.unlink(cr, uid, schedule_id, context=context) _l.warning('vals1: %s', vals1) sched_obj.create(cr, uid, vals1, context=context) if vals2: _l.warning('vals2: %s', vals2) sched_obj.create(cr, uid, vals2, context=context) def _change_by_template(self, cr, uid, employee_id, week_start, new_template_id, doall, context=None): sched_obj = self.pool.get('hr.schedule') schedule_ids = sched_obj.search(cr, uid, [('employee_id', '=', employee_id), ('date_start', '<=', week_start), ('date_end', '>=', week_start), ('state', 'not in', ['locked'])], context=context) # Remove the current schedule and add a new one in its place according # to the new template # if len(schedule_ids) > 0: self._remove_add_schedule(cr, uid, schedule_ids[0], week_start, new_template_id, context=context) # Also, change all subsequent schedules if so directed if doall: ids = sched_obj.search(cr, uid, [('employee_id', '=', employee_id), ('date_start', '>', week_start), ('state', 'not in', ['locked'])], context=context) for i in ids: self._remove_add_schedule(cr, uid, i, week_start, new_template_id, context) def change_restday(self, cr, uid, ids, context=None): data = self.read(cr, uid, ids[0], [], context=context) # Change the rest day for only one schedule if (data.get('temp_restday') and data.get('dayofweek') and data.get('temp_week_start')): self._change_restday(cr, uid, data['employee_id'][0], data['temp_week_start'], data['dayofweek'], context=context) # Change entire week's schedule to the chosen schedule template if (not data.get('temp_restday') and data.get('st_new_id') and data.get('week_start')): if data.get('week_start', False): self._change_by_template(cr, uid, data['employee_id'][0], data['week_start'], data['st_new_id'][0], data.get('permanent', False), context=context) # If this change is permanent modify employee's contract to # reflect the new template # if data.get('permanent', False): self.pool.get('hr.contract').write( cr, uid, data['contract_id'][0], { 'schedule_template_id': data['st_new_id'][0], }, context=context) return { 'name': 'Change Schedule Template', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'hr.restday.wizard', 'type': 'ir.actions.act_window', 'target': 'new', 'context': context }
class hr_job(models.Model): _name = 'hr.job' _inherit = 'hr.job' def _get_all_child_ids(self, cr, uid, ids, field_name, arg, context=None): result = dict.fromkeys(ids) for i in ids: result[i] = self.search(cr, uid, [('parent_id', 'child_of', i)], context=context) return result _columns = { 'department_manager': fields.boolean('Department Manager', ), 'parent_id': fields.many2one( 'hr.job', 'Immediate Superior', ondelete='cascade', ), 'child_ids': fields.one2many( 'hr.job', 'parent_id', 'Immediate Subordinates', ), 'all_child_ids': fields.function( _get_all_child_ids, type='many2many', relation='hr.job', ), 'parent_left': fields.integer( 'Left Parent', select=1, ), 'parent_right': fields.integer( 'Right Parent', select=1, ), } _parent_name = "parent_id" _parent_store = True _parent_order = 'name' _order = 'parent_left' def _check_recursion(self, cr, uid, ids, context=None): # Copied from product.category # This is a brute-force approach to the problem, but should be good # enough. # level = 100 while len(ids): cr.execute('select distinct parent_id from hr_job where id IN %s', (tuple(ids), )) ids = filter(None, map(lambda x: x[0], cr.fetchall())) if not level: return False level -= 1 return True def _rec_message(self, cr, uid, ids, context=None): return _('Error!\nYou cannot create recursive jobs.') _constraints = [ (_check_recursion, _rec_message, ['parent_id']), ] def write(self, cr, uid, ids, vals, context=None): res = super(hr_job, self).write(cr, uid, ids, vals, context=None) if isinstance(ids, (int, long)): ids = [ids] dept_obj = self.pool.get('hr.department') if vals.get('department_manager', False): for di in ids: job = self.browse(cr, uid, di, context=context) dept_id = False if vals.get('department_id', False): dept_id = vals['department_id'] else: dept_id = job.department_id.id employee_id = False for ee in job.employee_ids: employee_id = ee.id if employee_id: dept_obj.write(cr, uid, dept_id, { 'manager_id': employee_id, }, context=context) elif vals.get('department_id', False): for di in ids: job = self.browse(cr, uid, di, context=context) if job.department_manager: employee_id = False for ee in job.employee_ids: employee_id = ee.id dept_obj.write(cr, uid, vals['department_id'], { 'manager_id': employee_id, }, context=context) elif vals.get('parent_id', False): ee_obj = self.pool.get('hr.employee') parent_job = self.browse(cr, uid, vals['parent_id'], context=context) parent_id = False for ee in parent_job.employee_ids: parent_id = ee.id for job in self.browse(cr, uid, ids, context=context): ee_obj.write(cr, uid, [ee.id for ee in job.employee_ids], { 'parent_id': parent_id, }, context=context) return res