class monthlyGoal(models.Model): _name = 'bi_finance.monthly_goal' _description = 'Objectif Mensuel' name = fields.Char(string="Titre", compute='_compute_name') month = fields.Selection(selection='_month', string='Mois', required=True) goal_percentage_in_time = fields.Percent( string="Pourcentage", required=True, help="Objectif du nombre de livraison livrée à temps (en %)", default=0) day_before_delivery = fields.Integer( string="Delai d'avance", required=True, help="Delai d'avance sur la livraison (jour)", default=5) quality = fields.Percent( string="Qualité", required=True, help= "Objectif du nombre des produits livrés sans problème de qualité (en %)", default=0) currency_id = fields.Many2one('res.currency', string='Currency') goal = fields.Monetary(string="Objectif du mois", compute='_goal_compute') brand_goal_stock_ids = fields.One2many('bi_finance.brand_goal_stock', 'monthly_goal_id', string="Stock - Catégories") goal_ebitda = fields.Monetary(string="Ebitda") yearly_goal_id = fields.Many2one('bi_finance.yearly_goal', ondelete='cascade', string="Objectif annuel", required=True) monthly_goal_employee_ids = fields.One2many( 'bi_finance.monthly_goal_employee', 'monthly_goal_id', string="Objectif mensuels des employés") @api.depends('goal', 'monthly_goal_employee_ids') def _goal_compute(self): for r in self: if 0 == len(r.monthly_goal_employee_ids): r.goal = 0 else: for m in r.monthly_goal_employee_ids: r.goal += m.goal @api.onchange('month', ' yearly_goal_id') def _compute_name(self): for record in self: if record.month == '' and not record.yearly_goal_id: record.name = "mois annee" elif not record.yearly_goal_id: record.name = "{mois} année".format( mois=self._month()[int(record.month) - 1][1]) elif record.month == '': record.name = "mois {annee}".format( annee=record.yearly_goal_id.year) else: record.name = "{mois} {annee}".format( mois=self._month()[int(record.month) - 1][1], annee=record.yearly_goal_id.year) def _month(self): list_month = [('1', 'Janvier'), ('2', 'Février'), ('3', 'Mars'), ('4', 'Avril'), ('5', 'Mai'), ('6', 'Juin'), ('7', 'Juillet'), ('8', 'Aout'), ('9', 'Septembre'), ('10', 'Octobre'), ('11', 'Novembre'), ('12', 'Décembre')] return list_month
class Contract(models.Model): _inherit = 'car.contract' payment_ids = fields.One2many(comodel_name='car.payment', inverse_name='contract_id', string='Payments') payment_count = fields.Integer(compute='_get_payment_count', string='Payment') payment_amount = fields.Monetary(compute='_get_total_payment', string='Total Payment', digits=dp.get_precision('Account'), currency_field='currency_id', track_visibility='always') remain_amount = fields.Monetary(compute='_get_total_payment', string='Total Remain', digits=dp.get_precision('Account'), currency_field='currency_id', track_visibility='always') late_amount = fields.Monetary(compute='_get_total_payment', string='Total Late', digits=dp.get_precision('Account'), currency_field='currency_id', track_visibility='always') late_percent = fields.Percent(compute='_get_total_payment', string='Late Percent', store=True) @api.multi @api.depends('depreciation_ids') def _get_total_payment(self): moment = fields.date.today() for c in self: amount = 0.0 waiting = 0.0 collect = 0.0 for d in c.depreciation_ids: amount += d.collect_amount if moment >= d.waiting_at: waiting += d.waiting_amount collect += d.collect_amount c.late_amount = collect - waiting c.payment_amount = amount c.remain_amount = c.amount_depreciation - amount late_percent = c.amount_depreciation and (round(c.late_amount / c.amount_depreciation, 4) * 100) or 0.0 # c.write({'late_percent': late_percent}) c.late_percent = late_percent @api.multi @api.depends('payment_ids') def _get_payment_count(self): for c in self: c.payment_count = len(c.payment_ids) @api.multi def show_payment(self): self.ensure_one() return { 'name': 'Payments', 'res_model': 'car.payment', 'type': 'ir.actions.act_window', 'view_id': False, 'view_type': 'form', 'view_mode': 'tree,form', 'target': 'current', 'context': "{ 'search_default_contract_id': [%s], 'default_contract_id': '%s'}" % (self.id, self.id) } @api.multi def unlink(self): self.ensure_one() if self.payment_count: raise ValidationError('Error! This contract has less than one payment. This cannot be deleted.') else: self.vehicle_id.state = 'validate' self.depreciation_ids.unlink() return super(Contract, self).unlink()
class item_task(models.Model): _name = 'cam.item_task' _description = 'cam.item_task' def display_name(self): for rec in self: task = "" if rec.task_id: task = rec.task_id.display_name if rec.task_id.display_name else "" workshop = "" if rec.workshop_id: workshop = "/" + rec.workshop_id.display_name + "/" if rec.workshop_id.display_name else "" progress_percentage = "("+str(rec.progress_percentage)+"%)" if rec.progress_percentage else "" rec.display_name = ''.join([task, workshop, progress_percentage]) display_name = fields.Char(compute=display_name) mechanic_id = fields.Many2one("cam.mechanic",string="Mecanico") workshop_id = fields.Many2one(realted="mechanic_id.workshop_id",string="Taller") def _get_states(self): return [("charged","Cargada"), ("assigned","Asignada"), ("in_progress","En Progreso"), ("paused","En Pausa"), ("finalized","Finalizada") ] @api.depends('mechanic_id') @api.onchange('mechanic_id') def check_is_assigned(self): res = [] for rec in self: if rec.mechanic_id: rec.state = 'assigned' else: rec.state = 'charged' res.append((rec.id,rec.state)) state = fields.Selection(_get_states, string="Estado de progreso",required="True",default=check_is_assigned) progress_percentage = fields.Percent("% de avance",readonly=True) over_under_work = fields.Integer("Exceso/Ahorro de trabajo") def _get_type(self): return [("planned","Planificada"), ("extra","Extra/diagnostico"), ] type = fields.Selection(_get_type, string="Tipo",required="True") def _get_result(self): return [("solved","Solucionado"), ("not_solved","No solucionado"), ("incomplete","Incompleto"), ("pending","Pendiente"), ] result = fields.Selection(_get_result, string="Resultado") result_description = fields.Text("Motivo del Resultado") elapsed_time_ids = fields.One2many("cam.elapsed_time","item_task_id",string="Tiempo empleado",readonly=True) service_id = fields.Many2one("cam.service",string="Servicio",required=True, readonly=True) task_id = fields.Many2one("cam.task",string="Tarea",required=True) start_time = fields.Datetime("Fecha inicio",compute="_compute_times",readonly=True) end_time = fields.Datetime("Fecha fin",compute="_compute_times",readonly=True) estimated_time = fields.Integer(related="task_id.estimated_time",readonly=True) elapsed_time = fields.Integer(string="tiempo empleado (min)",compute="_compute_times",readonly=True) @api.depends('elapsed_time_ids','elapsed_time_ids.start_time','elapsed_time_ids.end_time','elapsed_time_ids.elapsed_time') @api.onchange('elapsed_time_ids') def _compute_times(self): for rec in self: elap_time = 0 start_time = rec.start_time end_time = rec.end_time for etime in rec.elapsed_time_ids: elap_time += etime.elapsed_time if bool(etime.start_time): if bool(start_time): if etime.start_time < start_time: start_time = etime.start_time else: start_time = etime.start_time if bool(etime.end_time): if bool(end_time): if etime.end_time > end_time: end_time = etime.end_time else: end_time = etime.end_time rec.start_time = start_time rec.end_time = end_time rec.elapsed_time = elap_time estimated = rec.estimated_time elapsed = rec.elapsed_time if estimated>elapsed: rec.progress_percentage = elap_time * 100 / estimated else: rec.progress_percentage = 100 if rec.state == 'finalized': rec.over_under_work = elap_time - estimated rec.progress_percentage = 100 def start(self): for rec in self: if ( (rec.service_id.state == 'finished') | (rec.service_id.state == 'finished_but')): raise ValidationError('No se puede iniciar una tares si el servicio esta cerrado') elap_time = self.env['cam.elapsed_time'].create({'item_task_id':rec.id}) rec.state = 'in_progress' rec._compute_times() rec.service_id._compute_times() #create elapsed time #set start_time print('start') def stop(self): for rec in self: for et in rec.elapsed_time_ids: if not (et.end_time): et.end_time = fields.Datetime.now() rec.state = 'paused' rec._compute_times() rec.service_id._compute_times() print('stop') def continue_task(self): for rec in self: if ( (rec.service_id.state == 'finished') | (rec.service_id.state == 'finished_but')): raise ValidationError('No se puede iniciar una tares si el servicio esta cerrado') elap_time = self.env['cam.elapsed_time'].create({'item_task_id':rec.id}) rec.state = 'in_progress' rec._compute_times() rec.service_id._compute_times() print('continue') def end(self,itwf): for rec in self: for et in rec.elapsed_time_ids: if not (et.end_time): et.end_time = fields.Datetime.now() rec.state = 'finalized' rec.result = itwf.result rec.result_description = itwf.result_description itwf.unlink() rec._compute_times() rec.service_id._compute_times() print('end')
class ResPartner(models.Model): """Partner with birth date in date format.""" _inherit = "res.partner" birthdate_date = fields.Date("Birthdate") age = fields.Char(string="Age", readonly=True, compute="_compute_age") age_years = fields.Integer( string="Age (years old)", compute='_compute_age', search='_search_age', ) place_of_birth = fields.Char('Place of Birth', tracking=True) country_of_birth = fields.Many2one('res.country', string="Country of Birth", tracking=True) gender = fields.Selection([("male", "Male"), ("female", "Female"), ("other", "Other")]) # CONADIS physical_exoneration = fields.Selection([ ('lactation', 'Lactancia'), ('discapacity', 'Discapacidad'), ], string=u"Exoneración Física") conadis = fields.Char(string="CONADIS") conadis_percent = fields.Percent(string="Porcentaje") observation_physical = fields.Text(string=u'Observación') is_deceased = fields.Boolean(compute='_compute_is_deceased', ) date_death = fields.Datetime(string='Deceased Date', ) @api.depends("birthdate_date") def _compute_age(self): self.compute_age_years() def compute_age_years(self): now = datetime.now() for record in self: if record.birthdate_date: birthdate_date = fields.Datetime.from_string( record.birthdate_date, ) if record.is_deceased: date_death = fields.Datetime.from_string(record.date_death) delta = relativedelta(date_death, birthdate_date) is_deceased = _(' (deceased)') else: delta = relativedelta(now, birthdate_date) is_deceased = '' years_months_days = '%d%s %d%s %d%s%s' % ( delta.years, _('y'), delta.months, _('m'), delta.days, _('d'), is_deceased) years = delta.years else: years_months_days = _('No DoB') years = False record.age = years_months_days if years: record.age_years = years @api.constrains('birthdate_date') def _check_birthdate_date(self): """ It will not allow birthday in the future. """ now = datetime.now() for record in self: if not record.birthdate_date: continue birthday = fields.Datetime.from_string(record.birthdate_date) if birthday > now: raise ValidationError( _('Partners cannot be born in the future.', )) def _compute_is_deceased(self): for record in self: record.is_deceased = bool(record.date_death) @api.onchange('birthdate_date') def _onchange_birthdate_date(self): self.compute_age_years()
class StockQualityCheckPoint(models.Model): _name = 'stock.quality.check.point' _description = "Stock Quality Control Check Points" def _get_point_id_domain(self): template_id = self.env.context.get('default_template_id', False) if template_id: template_rec = self.env['stock.quality.template'].browse( template_id) return [('id', 'in', template_rec.mapped('point_ids').mapped('id')) ] return [] line_id = fields.Many2one('stock.quality.check.line', 'Quality Line Reference') point_id = fields.Many2one('stock.quality.point', string='Name', ondelete='restrict', required=True, domain=lambda self: self._get_point_id_domain()) type = fields.Selection(related='point_id.type') value = fields.Char(' ', help="Value") value_boolean = fields.Boolean(' ', help="Selection if type Boolean") percentaje = fields.Percent(string='Percentaje') help = fields.Char('Help', help="Type of value required for this quality point") @api.onchange('point_id') def _onchange_point_id(self): if self.point_id.type == 'percentaje': self.help = 'Enter the number of ocurrences (integer), percentaje will be automatically calculated.' if self.point_id.type == 'integer': self.help = 'Enter the number of ocurrences (integer).' if self.point_id.type == 'float': self.help = 'Enter the a number.' if self.point_id.type == 'string': self.help = 'Enter the value.' if self.point_id.type == 'boolean': self.help = 'Toggle Yes/No the button.' @api.onchange('value') def _onchange_picking_id(self): for record in self: value = record.value count = self.env.context.get('count', False) if record.type in ('integer', 'percentaje'): try: value = int(value) except: raise ValidationError("You have to enter an integer!") if record.type == 'float': try: value = float(value) except: raise ValidationError( "You have to enter an integer or number with decimals!" ) if record.type == 'integer' and count and value > count: raise ValidationError( "Number must be less than or equal to %s" % count) elif value and record.type == 'percentaje' and record.line_id.count > 0: record.percentaje = int((value * 100) / record.line_id.count)
class Depreciation(models.Model): _inherit = 'car.depreciation' depreciation_ids = fields.One2many(comodel_name="car.payment.depreciation", inverse_name="depreciation_id", string="Depreciation", required=False) collect_at = fields.Date(compute='_get_collect_at', string='Collect At') collect_amount = fields.Monetary(compute='_get_collect_amount', string='Collect Amount', currency_field='currency_id', track_visibility='always', digits=dp.get_precision('Account'), store=True) remain_amount = fields.Monetary(compute='_get_remain_amount', string='Remain Amount', currency_field='currency_id', track_visibility='always', digits=dp.get_precision('Account'), store=True) remain_percent = fields.Percent(compute='_get_remain_percent', string='Remain Percent', store=True) remain_cumul = fields.Monetary(compute='_get_remain_cumul', string='Remain Cumul', currency_field='currency_id', track_visibility='always', digits=dp.get_precision('Account')) # @api.model_cr # def init(self): # # tools.drop_view_if_exists(self.env.cr, 'car_depreciation') # self.env.cr.execute(""" # CREATE OR REPLACE VIEW car_depreciation AS ( # SELECT # id, contract_id, company_id, partner_id, waiting_at, currency_id, waiting_amount, state, # vehicle_id, customer_id # FROM car_depreciation)""") @api.multi @api.depends('depreciation_ids') def _get_collect_at(self): pay_env = self.env['car.payment.depreciation'] for r in self: item = pay_env.search([('depreciation_id', '=', r.id)], order='collect_at desc', limit=1) if item: r.collect_at = item.collect_at @api.multi @api.depends('waiting_amount', 'depreciation_ids') def _get_collect_amount(self): pay_env = self.env['car.payment.depreciation'] for r in self: already_paid = pay_env.search([('depreciation_id', '=', r.id)]) amount = 0.0 for payment in already_paid: amount += payment.collect_amount r.collect_amount = amount @api.multi @api.depends('waiting_amount', 'collect_amount', 'remain_amount', 'depreciation_ids') def _get_remain_percent(self): for r in self: ratio = r.waiting_amount and round(r.remain_amount / r.waiting_amount, 4) or 0.0 remain_percent = ratio * 100 # r.write({'remain_percent': remain_percent}) r.remain_percent = remain_percent @api.multi @api.depends('waiting_amount', 'collect_amount', 'depreciation_ids') def _get_remain_amount(self): for r in self: if r.waiting_amount: r.remain_amount = r.waiting_amount - r.collect_amount else: r.remain_amount = 0.0 @api.multi @api.depends('waiting_amount', 'collect_amount', 'remain_amount', 'depreciation_ids') def _get_remain_cumul(self): cumul = 0.0 for r in self: cumul += r.remain_amount r.remain_cumul = cumul