Example #1
0
class WizardReports(osv.TransientModel):
    _name = 'wiz.invoices.writeoff'
    _description = 'PDF Reports for showing all disconnection,reconnection'

    _columns = {
        'date':
        fields.date('Invoice Date', required=True),
        'cheque_no':
        fields.char('Cheque No', required=True),
        'bank_code':
        fields.selection([
            ('FBL', 'FBL'),
            ('JSBL', 'JSBL'),
        ],
                         required=True,
                         string='Bank Code'),
        'invoice_amount':
        fields.float('Invoice Amount', required=True),
        'received_amount':
        fields.float('Received Amount', required=True)
    }

    def inv_status_changed(self, central, south, north, main):
        self.env.cr.execute(
            "UPDATE account_invoice "
            "SET state='cancel', payment_received=True,courier=True" +
            ",cheque_no='" + str(self.cheque_no) + "'" +
            ",comment='Payment has been received against parent invoice therefore user cancelled this invoice' "
            "FROM res_partner WHERE account_invoice.partner_id = res_partner.id and account_invoice.state='draft' "
            + "and res_partner.bank_code='" + str(self.bank_code) + "'" +
            "and account_invoice.invoice_date='" + str(self.date) + "'" +
            "and account_invoice.amount_total='" + str(self.invoice_amount) +
            "'" + "and account_invoice.partner_id!='" + str(central) + "'" +
            "and account_invoice.partner_id != '" + str(south) + "'" +
            "and account_invoice.partner_id !='" + str(north) + "'" +
            "and account_invoice.partner_id !=" + str(main))
        return True

    @api.one
    def inv_status_change_request(self):
        if self.bank_code == 'FBL':
            fbl_central = 9464
            fbl_south = 9522
            fbl_north = 9450
            fbl_main = 9572
            result = self.inv_status_changed(fbl_central, fbl_south, fbl_north,
                                             fbl_main)
            return result

        if self.bank_code == 'JSBL':
            jsbl_central = 11056
            jsbl_south = 11057
            jsbl_north = 11058
            jsbl_main = 3349
            result = self.inv_status_changed(jsbl_central, jsbl_south,
                                             jsbl_north, jsbl_main)
            return result

        raise osv.except_osv("Done........",
                             "Records have been successfully updated")
class nomor_faktur_pajak(osv.osv):
    _name = "nomor.faktur.pajak"
    _description = 'Nomor faktur Pajak'

    def _nomor_faktur(self, cr, uid, ids, nomorfaktur, arg, context=None):
        res = {}
        for nomor in self.browse(cr, uid, ids, context):    
            res[nomor.id] = "%s.%s.%s" % (nomor.nomor_perusahaan, nomor.tahun_penerbit, nomor.nomor_urut)
        return res
    
    _columns = {
        'nomor_perusahaan' : fields.char('Nomor Perusahaan', size=3),
        'tahun_penerbit': fields.char('Tahun Penerbit', size=2),
        'nomor_urut': fields.char('Nomor Urut', size=8),
        'name': fields.function(_nomor_faktur, type='char', string="Nomor Faktur", store=True),
        'invoice_id': fields.many2one('account.invoice','Invoice No'),
        'partner_id'    : fields.many2one('res.partner', "Customer"),
        'dpp'   : fields.float('Untaxed Amount'),
        'tax_amount': fields.float("Tax Amount"),
        'date_used' : fields.date("Used Date"),
        'company_id': fields.many2one('res.company', 'Company'),
        'currency_id': fields.many2one('res.currency', 'Currency'),
        'type'      : fields.selection([('in','Faktur Pajak Masukan'),('out','Faktur Pajak Keluaran')],'Type'),
        'status': fields.selection([('1','Used'),('0','Not Used')],'Status'),
    }
    
    _defaults = {
        'status': '0',
    }
    
    _sql_constraints = [
        ('faktur_unique', 'unique(nomor_perusahaan,tahun_penerbit,nomor_urut)', 'Number Faktur Must Be Unique.'),
    ]
Example #3
0
class mrp_production_workcenter_line(osv.osv):
    _name = 'mrp.production.workcenter.line'
    _inherit = 'mrp.production.workcenter.line'

    _columns = {
        'man_hour_standard':
        fields.float('Man Hour Standard', digits=(16, 2)),
        'man_number_standard':
        fields.integer('Man Number Standard'),
        'man_hour_actual':
        fields.float('Man Hour Actual', digits=(16, 2)),
        'man_number_actual':
        fields.integer('Man Number Actual'),
        'man_hour_diff':
        fields.float('Man Hour Diff', digits=(16, 2)),
        'man_number_diff':
        fields.integer('Man Number Diff'),
        'wo_machine_hour_lines':
        fields.one2many('vit_pharmacy_wo_hour.wo_machine_hour', 'mpwcl_id',
                        'Wo Machine Hour'),
    }

    @api.onchange('man_hour_actual', 'man_number_actual'
                  )  # if these fields are changed, call method
    def on_change_nett_diff(self):
        self.man_hour_diff = self.man_hour_standard - self.man_hour_actual
        self.man_number_diff = self.man_number_standard - self.man_number_actual
Example #4
0
    def _get_conversion_rate(self, cr, uid, ids, field_name, field_value, args, context=None):
        _logger.info('Start Get Conversion Rate')
        result = {}
        if not ids:
            return result

        trans_id = ids[0]
        trans = self.get_trans(cr, uid, ids, context)
        if trans:
            today = datetime.today()
            rate_ids = trans.lease_trans_id.rate_ids
            if rate_ids:
                for rate_id in rate_ids:
                    if datetime.strptime(rate_id.start_date, '%Y-%m-%d') <= today and datetime.strptime(
                            rate_id.end_date, '%Y-%m-%d') >= today:
                        result[trans_id] = rate_id.rate * rate_id.rupiah * trans.rental_charge
                        break
            return result[trans_id]
        else:
            return result

        'lease_trans_id': fields.many2one('bm.lease.transaction', 'Trans ID'),
        'lot_id': fields.many2one('bm.lot', 'Lot #', required=True),
        # 'rental_conversion': fields.function(_get_conversion_rate, type='float',  digits=(16,2), string="Conversion"),
        'lettable_area': fields.float('Lettable Area (sqm)', required=True),
        'rental_charge': fields.float('Rental (/sqm/month)', required=True),
        'service_charge': fields.float('Service Charge (/sqm/month)', required=True),
        'promotion_levy': fields.float('Promotion Levy (/sqm/month)', required=True),
class policy_fee_details(models.TransientModel):
    _name = 'policy_fee_details'

    _columns = {
        'membership': fields.char('Membership'),
        'fee': fields.float('Fee'),
        'total_member': fields.float('Total Member'),
        'total_fee': fields.float('Total Fee Per Membership'),
    }
Example #6
0
class hr_payslip_line(models.Model):
    _inherit = 'hr.payslip.line'
    _columns = {
        'total_ytd':
        fields.float('Total Year-to-date',
                     digits_compute=dp.get_precision('Payroll'))
    }
Example #7
0
class pos_stock_inventory_categ_detail_line(osv.osv):
    _name = 'pos.stock.inventory.categ.detail.line'
    _description = 'Detalle del Inventario por Categoria'
    _rec_name = 'product_id'
    _columns = {
        'ref_id':
        fields.many2one('pos.stock.inventory.categ.detail', 'ID Ref'),
        'location_id':
        fields.many2one(
            'stock.location',
            'Ubicacion',
        ),
        'product_id':
        fields.many2one('product.product', 'Producto'),
        'product_uom_id':
        fields.many2one(
            'product.uom',
            'Unidad Base',
        ),
        'product_qty':
        fields.float('Cantidad', digits=(14, 2)),
        'default_code':
        fields.related('product_id',
                       'default_code',
                       type='char',
                       string='Codigo Interno',
                       readonly=True),
    }
    _defaults = {}
    _order = 'id'
Example #8
0
class policy_line_ot(models.Model):

    _name = 'hr.policy.line.ot'

    def _tz_list(self, cr, uid, context=None):

        res = tuple()
        for name in common_timezones:
            res += ((name, name),)
        return res

    _columns = {
        'name': fields.char('Name', size=64, required=True),
        'policy_id': fields.many2one('hr.policy.ot', 'Policy'),
        'type': fields.selection([('daily', 'Daily'),
                                  ('weekly', 'Weekly'),
                                  ('restday', 'Rest Day'),
                                  ('holiday', 'Public Holiday')],
                                 'Type', required=True),
        'weekly_working_days': fields.integer('Weekly Working Days'),
        'active_after': fields.integer(
            'Active After', help="Minutes after which this policy applies"),
        'active_start_time': fields.char(
            'Active Start Time', size=5, help="Time in 24 hour time format"),
        'active_end_time': fields.char(
            'Active End Time', size=5, help="Time in 24 hour time format"),
        'tz': fields.selection(_tz_list, 'Time Zone'),
        'rate': fields.float(
            'Rate', required=True, help='Multiplier of employee wage.'),
        'code': fields.char(
            'Code', required=True, help="Use this code in the salary rules.")
    }
Example #9
0
class policy_line_presence(models.Model):

    _name = 'hr.policy.line.presence'

    _columns = {
        'name':
        fields.char('Name', size=64, required=True),
        'policy_id':
        fields.many2one('hr.policy.presence', 'Policy'),
        'code':
        fields.char('Code',
                    required=True,
                    help="Use this code in the salary rules."),
        'rate':
        fields.float('Rate',
                     required=True,
                     help='Multiplier of employee wage.'),
        'type':
        fields.selection([('normal', 'Normal Working Hours'),
                          ('holiday', 'Holidays'), ('restday', 'Rest Days')],
                         'Type',
                         required=True),
        'active_after':
        fields.integer(
            'Active After',
            required=True,
            help='Minutes after first punch of the day in which policy will '
            'take effect.'),
        'duration':
        fields.integer('Duration', required=True, help="In minutes.")
    }

    _defaults = {
        'rate': 1.0,
    }
Example #10
0
class bm_lease_rate(osv.osv):
    _name = "bm.lease.rate"
    _description = "Building Management Lease Rate"

    _columns = {
        'lease_trans_id': fields.many2one('bm.lease.transaction', 'Trans ID'),
        'start_date': fields.date('Start Date', required=True),
        'end_date': fields.date('End Date', required=True),
        'rate': fields.float('Rate', required=True),
        'rupiah': fields.float('Rupiah', required=True),
    }

    _defaults = {
        'rate': lambda *a: 0.0,
        'rupiah': lambda *a: 0.0,
    }
Example #11
0
class hr_salary_rule_variable(models.Model):
    _name = 'hr.salary.rule.variable'
    _description = 'Variables used on salary rules that change over the years'
    _columns = {
        'salary_rule_id':
        fields.many2one(
            'hr.salary.rule',
            'Salary Rule',
            ondelete='cascade',
            required=True,
        ),
        'date_from':
        fields.date(
            'Date From',
            required=True,
        ),
        'date_to':
        fields.date('Date To', ),
        'type':
        fields.selection([('python', 'Python Code'),
                          ('fixed', 'Fixed Amount')],
                         string='Type'),
        'python_code':
        fields.text('Python Code'),
        'fixed_amount':
        fields.float('Fixed Amount'),
    }
Example #12
0
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)
Example #13
0
class custom_calendar_event_type(osv.osv):
    _name = 'calendar.event.type'
    _inherit = 'calendar.event.type'
    _columns = {
        'x_code_acte': fields.char('Code acte', size=8),
        'x_price_acte': fields.float('Prix acte', digits=(4,0)),
        
    }
class account_liquidation_line(osv.osv):
    _name = 'account.liquidation.line'
    _description = 'Purchase liquidation lines'
    
    _columns = {
    
        'liquidation_id': fields.many2one('account.liquidation', 'Purchase liquidation'),
        'acc_partner_id': fields.many2one('account.account', 'Partner account'),
        'partner_id': fields.many2one('res.partner', 'Partner'),
        'acc_product_id': fields.many2one('account.account', 'Product account'),
        'product_id': fields.many2one('product.product', 'Product'),
        
        'price_unit': fields.float('Price unit'),
        'quantity': fields.float('Quantity'),
        'name': fields.text('Description'),

    }
Example #15
0
class hr_payslip_worked_days(models.Model):
    _inherit = 'hr.payslip.worked_days'

    def _get_total(self, cr, uid, ids, field_name, arg=None, context=None):
        res = {}
        for wd in self.browse(cr, uid, ids, context=context):
            res[wd.id] = wd.number_of_hours \
                * wd.hourly_rate * wd.rate / 100
        return res

    _columns = {
        'hourly_rate':
        fields.float('Hourly Rate',
                     help="""\
The employee's standard hourly rate for one hour of work.
Example, 25 Euros per hour."""),
        'rate':
        fields.float('Rate (%)',
                     help="""\
The rate by which to multiply the standard hourly rate.
Example, an overtime hour could be paid the standard rate multiplied by 150%.
"""),

        # When a worked day has a number of hours and an hourly rate,
        # it is necessary to have a date interval,
        # because hourly rates are likely to change over the time.
        'date_from':
        fields.date('Date From'),
        'date_to':
        fields.date('Date To'),
        'total':
        fields.function(
            _get_total,
            method=True,
            type="float",
            string="Total",
        ),
    }
    _defaults = {
        'hourly_rate': 0,
        'rate': 100,
        'date_from':
        lambda *a: datetime.now().strftime(DEFAULT_SERVER_DATE_FORMAT),
        'date_to':
        lambda *a: datetime.now().strftime(DEFAULT_SERVER_DATE_FORMAT)
    }
Example #16
0
class pos_order_report_journal_line(osv.osv):
    _name = 'pos.order.report.journal.line'
    _description = 'Pagos del Reporte'
    _columns = {
        'report_id': fields.many2one('pos.order.report.jasper', 'ID Ref'),
        'name': fields.char('Descripcion', size=128),
        'sum': fields.float('Total', digits=(14, 2)),
    }
    _defaults = {}
Example #17
0
class pos_order_report_tax_line(osv.osv):
    _name = 'pos.order.report.tax.line'
    _description = 'Impuestos del Reporte'
    _columns = {
        'report_id': fields.many2one('pos.order.report.jasper', 'ID Ref'),
        'name': fields.char('Descripcion', size=128),
        'amount': fields.float('Total', digits=(14, 2)),
    }
    _defaults = {}
Example #18
0
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,
    }
Example #19
0
class journal_expenses(orm.Model):
    _name = 'journal.details'

    _columns = {
        'journal_name': fields.char('Nombre diario'),
        'id_periodo': fields.integer('id periodo'),
        'period_name': fields.char('Nombre periodo'),
        'gasto_detallado': fields.float('Gasto sin impuesto'),
        'id_gasto': fields.integer('ID gasto')
    }
Example #20
0
class wage_increment(models.Model):

    _name = 'hr.contract.wage.increment'
    _description = 'HR Contract Wage Increment'

    _columns = {
        'effective_date': fields.date(
            'Effective Date',
            required=True,
        ),
        'wage': fields.float('Amount', digits=(16, 2)),
        'contract_id': fields.many2one(
            'hr.contract',
            'Contract',
        ),
    }

    def _get_contract_id(self, cr, uid, context=None):

        if context is None:
            context = {}
        return context.get('active_id', False)

    _defaults = {'contract_id': _get_contract_id}

    _rec_name = 'effective_date'

    def action_wage_increment(self, cr, uid, ids, context=None):

        hr_obj = self.pool.get('hr.contract')

        # Copy the contract and adjust start/end dates and wage accordingly.
        #
        for wi in self.browse(cr, uid, ids, context=context):

            data = hr_obj.copy_data(cr,
                                    uid,
                                    wi.contract_id.id,
                                    context=context)
            data['name'] = data['name'] + \
                _(' - Wage Change ') + wi.effective_date
            data['wage'] = wi.wage
            data['date_start'] = wi.effective_date

            c_id = hr_obj.create(cr, uid, data, context=context)
            if c_id:
                effective_date = datetime.strptime(wi.effective_date,
                                                   '%Y-%m-%d').date()
                date_end = effective_date + relativedelta(days=1)
                vals = {
                    'date_end': date_end.stftime('%Y-%m-%d'),
                }
                hr_obj.write(cr, uid, wi.contract_id.id, vals, context=context)

        return {'type': 'ir.actions.act_window_close'}
Example #21
0
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
Example #22
0
class stock_move(osv.osv):
    _name = "stock.move"
    _inherit = "stock.move"
    _description = "Stock Move"

    _columns = {
        'log_qty': fields.float('Log Quantity'),
        'product_qty_nett': fields.float("Nett Quantity", store=True),
        'product_qty_diff': fields.float("Diff/Loss Quantity", store=True),
        'weight_log': fields.float('Weight'),
        'length_log': fields.float('Length'),
        'height_log': fields.float('Height'),
        'diameter_log': fields.float('Diameter'),
    }
Example #23
0
class product_pricelist_item(osv.osv):
    _inherit = 'product.pricelist.item'

    def _price_field_get(self, cr, uid, context=None):
        pt = self.pool.get('product.price.type')
        ids = pt.search(cr, uid, [], context=context)
        result = []
        for line in pt.browse(cr, uid, ids, context=context):
            result.append((line.id, line.name))

        result.append((-1, _('Other Pricelist')))
        result.append((-2, _('Supplier Prices on the product form')))
        result.append((-3, _('Precio fijo')))
        return result

    _columns = {
        'base':
        fields.selection(_price_field_get,
                         'Based on',
                         required=True,
                         size=-1,
                         help="Base price for computation."),
        'fixed_price':
        fields.float('Precio Fijo', digits=(9, 2)),
        'product_partner_ident':
        fields.char('Identificacion Cliente', required=True),
        'partner_desc':
        fields.char('Descripcion del Cliente', required=True),
        # 'o2s_id': fields.integer('O2s sequence'),
    }

    def product_id_change(self, cr, uid, ids, product_id, context=None):
        res = super(product_pricelist_item,
                    self).product_id_change(cr, uid, ids, product_id, context)
        if 'value' in res and product_id:
            product = self.pool.get('product.product').browse(
                cr, uid, product_id)
            res['value']['partner_desc'] = product.name
        return res
class account_bank_statement_line(osv.osv):
    _inherit = "account.bank.statement.line"
    _description = "Bank Statement Line"
    _columns = {
        'type':
        fields.selection([('supplier', 'Supplier'), ('customer', 'Customer'),
                          ('general', 'General')], 'Type'),
        't_type':
        fields.selection([('receipt', 'Receipt'), ('payment', 'Payment')],
                         "Transaction Type"),
        't_amount':
        fields.float("Amount", digits=(16, 2)),
    }
    _defaults = {
        'date': False,
    }

    def onchange_trnstyp_amount(self, cr, uid, ids, t_type, t_amount):
        res = {}
        if t_amount:
            sign = (t_type == 'payment') and -1 or 1
            res['amount'] = t_amount * sign
        return {'value': res}
class produce_sale_price_history(osv.osv):
    """
    Keep track of the ``product.template`` sale prices as they are changed.
    """

    _name = 'product.sale.price.history'
    _rec_name = 'datetime'
    _order = 'datetime desc'

    _columns = {
        'company_id':
        fields.many2one('res.company', required=True),
        'product_template_id':
        fields.many2one('product.template',
                        'Product Template',
                        required=True,
                        ondelete='cascade'),
        'datetime':
        fields.datetime('Historization Time'),
        'list_price':
        fields.float('Historized list price'),
    }

    def _get_default_company(self, cr, uid, context=None):
        if 'force_company' in context:
            return context['force_company']
        else:
            company = self.pool['res.users'].browse(cr,
                                                    uid,
                                                    uid,
                                                    context=context).company_id
            return company.id if company else False

    _defaults = {
        'datetime': fields.datetime.now,
        'company_id': _get_default_company,
    }
class sale_order(osv.osv):
    _inherit = 'sale.order'
    _name = 'sale.order'

    _columns = {
        'all_discounts':
        fields.float('All order lines discount',
                     required=True,
                     help='Change all order lines discount.'),
    }

    def update_discount_lines(self, cr, uid, ids, context=None):
        if context.get('all_discounts', 0) < 100 and context.get(
                'all_discounts', 0) >= 0:
            lines = self.browse(cr, uid, ids,
                                context=context).order_line.filtered(
                                    lambda r: r.product_id.type == 'product')
            lines.write({'discount': context['all_discounts']})
            return
        else:
            raise osv.except_osv(
                _('Error!'),
                _("Your discount value is out of vlaues,it's value between 0 and 100,but 100 except."
                  ))
Example #27
0
class stock_transfer_details_items(models.TransientModel):
    _name = 'stock.transfer_details_items'
    _inherit = 'stock.transfer_details_items'
    _description = 'Picking wizard items'

    _columns = {
        'product_qty_nett': fields.float("Nett Quantity", store=True),
        'product_qty_diff': fields.float("Diff/Loss Quantity", store=True),
        'weight_log': fields.float('Weight'),
        'length_log': fields.float('Length'),
        'height_log': fields.float('Height'),
        'diameter_log': fields.float('Diameter'),
    }

    @api.onchange('weight_log', 'length_log', 'height_log',
                  'diameter_log')  # if these fields are changed, call method
    def on_change_nett_diff(self):
        # import pdb;pdb.set_trace()
        if self.product_id.uom_id == "Cylindrical":
            self.product_qty_nett = self.diameter_log * self.length_log
        else:
            self.product_qty_nett = self.weight_log * self.length_log * self.height_log

        self.product_qty_diff = self.quantity - self.product_qty_nett
Example #28
0
class TransportVehicule(models.Model):
    _name = 'transport.vehicule'
    _description = "Vehicule"
    _order = 'name'

    def _vehicle_name_get_fnc(self):
        res = {}
        for record in self:
            record.name = record.model_id.brand_id.name + '/' + record.model_id.name + '/' + record.imatriculation
        return res

    def return_action_to_open(self):
        """ This opens the xml view specified in xml_id for the current vehicle """
        if self.env.context is None:
            context = {}
        if self.env.context.get('xml_id'):
            context.pop('group_by', False)
            res = self.pool.get('ir.actions.act_window').for_xml_id(
                self.env.cr,
                self.env.uid,
                'fleet',
                context['xml_id'],
                context=self.env.context)
            res['context'] = self.env.context
            res['context'].update({'default_vehicle_id': ids[0]})
            res['domain'] = [('vehicle_id', '=', ids[0])]
            return res
        return False

    def act_show_log_cost(self):
        """ This opens log view to view and add new log for this vehicle, groupby default to only show effective costs
            @return: the costs log view
        """
        if self.env.context is None:
            context = {}
        res = self.pool.get('ir.actions.act_window').for_xml_id(
            self.env.cr,
            self.env.uid,
            'fleet',
            'fleet_vehicle_costs_act',
            context=self.env.context)
        res['context'] = context
        res['context'].update({
            'default_vehicle_id': ids[0],
            'search_default_parent_false': True
        })
        res['domain'] = [('vehicle_id', '=', ids[0])]
        return res

    def _get_odometer(self):
        res = dict.fromkeys(self.env.ids, 0)
        for record in self:
            ids = self.pool.get('fleet.vehicle.odometer').search(
                self.env.cr,
                self.env.uid, [('vehicle_id', '=', record.id)],
                limit=1,
                order='value desc')
            if len(ids) > 0:
                res[record.id] = self.pool.get(
                    'fleet.vehicle.odometer').browse(self.env.cr,
                                                     self.env.uid,
                                                     ids[0],
                                                     context=context).value
        return res

    def _set_odometer(self):
        if value:
            date = datetime.now()
            data = {'value': value, 'date': date, 'vehicle_id': id}
            return self.pool.get('fleet.vehicle.odometer').create(
                self.env.cr, self.env.uid, data, context=self.env.context)

    def _search_get_overdue_contract_reminder(self):
        res = []
        for field, operator, value in self.env.args:
            assert operator in ('=', '!=', '<>') and value in (
                True, False), 'Operation not supported'
            if (operator == '=' and value == True) or (operator in ('<>', '!=')
                                                       and value == False):
                search_operator = 'in'
            else:
                search_operator = 'not in'
            datetime.now()
            cr.execute(
                'select cost.vehicle_id, count(contract.id) as contract_number FROM fleet_vehicle_cost cost left join fleet_vehicle_log_contract contract on contract.cost_id = cost.id WHERE contract.expiration_date is not null AND contract.expiration_date < %s AND contract.state IN (\'open\', \'toclose\') GROUP BY cost.vehicle_id',
                (today, ))
            res_ids = [x[0] for x in self.env.cr.fetchall()]
            res.append(('id', search_operator, res_ids))
        return res

    def _search_contract_renewal_due_soon(self):
        res = []
        for field, operator, value in self.env.args:
            assert operator in ('=', '!=', '<>') and value in (
                True, False), 'Operation not supported'
            if (operator == '=' and value == True) or (operator in ('<>', '!=')
                                                       and value == False):
                search_operator = 'in'
            else:
                search_operator = 'not in'
            today = datetime.now()
            datetime_today = datetime.datetime.strptime(
                today, tools.DEFAULT_SERVER_DATE_FORMAT)
            limit_date = str(
                (datetime_today + relativedelta(days=+15)).strftime(
                    tools.DEFAULT_SERVER_DATE_FORMAT))
            cr.execute(
                'select cost.vehicle_id, count(contract.id) as contract_number FROM fleet_vehicle_cost cost left join fleet_vehicle_log_contract contract on contract.cost_id = cost.id WHERE contract.expiration_date is not null AND contract.expiration_date > %s AND contract.expiration_date < %s AND contract.state IN (\'open\', \'toclose\') GROUP BY cost.vehicle_id',
                (today, limit_date))
            res_ids = [x[0] for x in self.env.cr.fetchall()]
            res.append(('id', search_operator, res_ids))
        return res

    def _get_contract_reminder_fnc(self):
        res = {}
        for record in self:
            overdue = False
            due_soon = False
            total = 0
            name = ''
            for element in record.log_contracts:
                if element.state in ('open',
                                     'toclose') and element.expiration_date:
                    current_date_str = fields.date.context_today(
                        self,
                        self.env.cr,
                        self.env.uid,
                        context=self.env.context)
                    due_time_str = element.expiration_date
                    current_date = str_to_datetime(current_date_str)
                    due_time = str_to_datetime(due_time_str)
                    diff_time = (due_time - current_date).days
                    if diff_time < 0:
                        overdue = True
                        total += 1
                    if diff_time < 15 and diff_time >= 0:
                        due_soon = True
                        total += 1
                    if overdue or due_soon:
                        ids = self.pool.get(
                            'fleet.vehicle.log.contract').search(
                                self.env.cr,
                                self.env.uid,
                                [('vehicle_id', '=', record.id),
                                 ('state', 'in', ('open', 'toclose'))],
                                limit=1,
                                order='expiration_date asc')
                        if len(ids) > 0:
                            #we display only the name of the oldest overdue/due soon contract
                            name = (self.pool.get(
                                'fleet.vehicle.log.contract').browse(
                                    self.env.cr,
                                    self.env.uid,
                                    ids[0],
                                    context=context).cost_subtype_id.name)

            res[record.id] = {
                'contract_renewal_overdue': overdue,
                'contract_renewal_due_soon': due_soon,
                'contract_renewal_total':
                (total -
                 1),  #we remove 1 from the real total for display purposes
                'contract_renewal_name': name,
            }
        return res

    def _get_default_state(self):
        try:
            model, model_id = self.pool.get(
                'ir.model.data').get_object_reference(self.env.cr,
                                                      self.env.uid, 'fleet',
                                                      'vehicle_state_active')
        except ValueError:
            model_id = False
        return model_id

    def _count_all(self):
        Odometer = self.pool['fleet.vehicle.odometer']
        LogFuel = self.pool['fleet.vehicle.log.fuel']
        LogService = self.pool['fleet.vehicle.log.services']
        LogContract = self.pool['fleet.vehicle.log.contract']
        Cost = self.pool['fleet.vehicle.cost']
        return {
            vehicle_id: {
                'odometer_count':
                Odometer.search_count(self.env.cr,
                                      self.env.uid,
                                      [('vehicle_id', '=', vehicle_id)],
                                      context=self.env.context),
                'fuel_logs_count':
                LogFuel.search_count(self.env.cr,
                                     self.env.uid,
                                     [('vehicle_id', '=', vehicle_id)],
                                     context=self.env.context),
                'service_count':
                LogService.search_count(self.env.cr,
                                        self.env.uid,
                                        [('vehicle_id', '=', vehicle_id)],
                                        context=self.env.context),
                'contract_count':
                LogContract.search_count(self.env.cr,
                                         self.env.uid,
                                         [('vehicle_id', '=', vehicle_id)],
                                         context=self.env.context),
                'cost_count':
                Cost.search_count(self.env.cr,
                                  self.env.uid,
                                  [('vehicle_id', '=', vehicle_id),
                                   ('parent_id', '=', False)],
                                  context=self.env.context)
            }
            for vehicle_id in ids
        }

    name = fields.Char(
        string='Nom du véhicule',
        required=True,
        readonly=True,
        translate=True,
        select=True,
        states={'draft': [('readonly', False)]},
    )
    state = fields.Selection(
        [
            ('draft', 'Brouillon'),
            ('cancel', 'Annulé'),
            ('confirm', 'Confirmé'),
            ('exploitation', 'En exploitation'),
            ('panne', 'En panne'),
            ('reparation', 'En Reparation'),
            ('rebut', 'En Rebut'),
        ],
        string='Status',
        index=True,
        readonly=True,
        default='draft',
        copy=False,
        help=
        " * Le statut 'Brouillon' est utilisé lorsque l'enregistrement est crée mais non confirmé.\n"
        " * Le statut 'Annulé' est utilisé quand un utilisateur annule l'enregistrement.\n"
        " * Le statut 'Confirmé' est utilisé quand un utilisateur confirme la création d'un enregistrement.\n"
        " * Le statut 'exploitation' est utilisé quand le véhicule est en exploitation.\n"
        " * Le statut 'panne' est utilisé quand le véhicule est en panne.\n"
        " * Le statut 'En Reparation' est utilisé quand le véhicule est en reparation.\n"
        " * Le statut 'En Rebut' est utilisé quand le véhicule est en rebut.\n"
    )
    feuilleroute_ids = fields.One2many(comodel_name='transport.feuille.route',
                                       inverse_name='vehicule_id',
                                       string='Feuilles de route',
                                       readonly=True,
                                       states={'draft': [('readonly', False)]},
                                       copy=True)
    voyage_ids = fields.One2many(comodel_name='transport.voyage',
                                 inverse_name='vehicule_id',
                                 string='Voyages effectués',
                                 readonly=True,
                                 states={'draft': [('readonly', False)]},
                                 copy=True)
    piece_ids = fields.One2many(comodel_name='transport.piece',
                                inverse_name='vehicule_id',
                                string='Liste des pièces',
                                readonly=True,
                                states={'draft': [('readonly', False)]},
                                copy=True)
    capacite = fields.Float(
        string='Capacité véhicule',
        readonly=True,
        required=True,
        states={'draft': [('readonly', False)]},
        help='Capacité du véhicule',
    )
    typecarburant = fields.Selection([
        ('gazoil', 'Gazoil'),
        ('essence', 'Essence'),
        ('super', 'Super'),
        ('petrole', 'Pétrole'),
        ('autres', 'Autres'),
    ],
                                     string='Type de Carburant',
                                     index=True,
                                     readonly=True,
                                     default='gazoil',
                                     states={'draft': [('readonly', False)]},
                                     copy=False,
                                     required=1,
                                     help=" * Le Gazoil .\n"
                                     " * L'Essence .\n"
                                     " * Le super .\n"
                                     " * Le Pétrole .\n"
                                     " * Autres .\n")
    product_id = fields.Many2one(comodel_name='product.product',
                                 readonly=True,
                                 required=True,
                                 string='Produit carburé',
                                 ondelete='set null',
                                 states={'draft': [('readonly', False)]},
                                 index=True)
    uom_id = fields.Many2one(string='Unité de mésure',
                             comodel_name='product.uom',
                             required=True,
                             index=True,
                             readonly=True,
                             store=True,
                             related='product_id.uom_id',
                             help='Véhicule de transport')
    acquisition_date = fields.Datetime(string='Date achat',
                                       required=True,
                                       readonly=True,
                                       index=True,
                                       states={'draft': [('readonly', False)]},
                                       copy=False,
                                       default=fields.Datetime.now)
    year_model = fields.Char()
    serial_number = fields.Char()
    registration = fields.Char()
    fleet_type = fields.Selection([('tractor', 'Motorized Unit'),
                                   ('trailer', 'Trailer'), ('dolly', 'Dolly'),
                                   ('other', 'Autre')],
                                  string='Unit Fleet Type')

    active = fields.Boolean(default=True)
    chauffeur_id = fields.Many2one('res.partner', string="Driver")
    employee_id = fields.Many2one('hr.employee',
                                  string="Driver",
                                  domain=[('is_driver', '=', True)])
    #expense_ids = fields.One2many('tms.expense', 'unit_id', string='Expenses')
    supplier_unit = fields.Boolean()
    reference = fields.Text(
        string='Reference',
        readonly=True,
        states={'draft': [('readonly', False)]},
        help='Reference',
    )
    installe_le = fields.Datetime(string='Installé le',
                                  required=True,
                                  readonly=True,
                                  index=True,
                                  states={'draft': [('readonly', False)]},
                                  copy=False,
                                  default=fields.Datetime.now,
                                  help='Date d\'installation')
    mise_en_service = fields.Date(string='Première Mise en service',
                                  required=True,
                                  readonly=True,
                                  index=True,
                                  states={'draft': [('readonly', False)]},
                                  copy=False,
                                  default=fields.Datetime.now,
                                  help='Date de premiere mise en service')
    expiration = fields.Date(string='Date de fin',
                             required=True,
                             readonly=True,
                             index=True,
                             states={'draft': [('readonly', False)]},
                             copy=False,
                             default=fields.Datetime.now)
    duree_vie_usine = fields.Float(string='Durée de vie(en nbre de jour)',
                                   readonly=True,
                                   states={'draft': [('readonly', False)]},
                                   help='Durée de vie à la sortie d\'usine',
                                   required=False)
    days_to_expire = fields.Integer(
        string="Nombre de jour restant",
        compute='_compute_days_to_expire',
        help="Nombre de jour restant Pour expiration")

    observation = fields.Text(
        string='Observation',
        readonly=True,
        states={'draft': [('readonly', False)]},
        help='Observation',
    )
    company_id = fields.Many2one(comodel_name='res.company',
                                 readonly=True,
                                 required=False,
                                 string='Entreprise',
                                 ondelete='set null',
                                 states={'draft': [('readonly', False)]},
                                 index=True)
    imatriculation = fields.Char(
        string='Imatriculation',
        required=True,
        readonly=True,
        translate=True,
        select=True,
        states={'draft': [('readonly', False)]},
        help='License plate number of the vehicle (ie: plate number for a car)'
    )
    vin_sn = fields.Char(
        string='Numéro chassit',
        required=True,
        readonly=True,
        translate=True,
        select=True,
        states={'draft': [('readonly', False)]},
        help='Unique number written on the vehicle motor (VIN/SN number)')
    color = fields.Char(string='Couleur',
                        required=False,
                        readonly=True,
                        translate=True,
                        select=True,
                        states={'draft': [('readonly', False)]},
                        help='Couleur')
    location = fields.Char(string='Localisation',
                           required=False,
                           readonly=True,
                           translate=True,
                           select=True,
                           states={'draft': [('readonly', False)]},
                           help='Location of the vehicle (garage, ...)')
    seats = fields.Integer(string='Chaises',
                           required=True,
                           readonly=True,
                           translate=True,
                           select=True,
                           states={'draft': [('readonly', False)]},
                           help='Nombre de chaise')
    doors = fields.Integer(string='Portes',
                           required=True,
                           readonly=True,
                           translate=True,
                           select=True,
                           states={'draft': [('readonly', False)]},
                           help='Nombre de Portes')
    fuel_type = fields.Selection([
        ('gasoline', 'Gasoline'),
        ('diesel', 'Diesel'),
        ('electric', 'Electric'),
        ('hybrid', 'Hybrid'),
    ],
                                 string='Type carburant',
                                 index=True,
                                 readonly=True,
                                 default='gasoline',
                                 copy=False,
                                 states={'draft': [('readonly', False)]},
                                 help=" Fuel Used by the vehicle \n")
    chauffeur_id = fields.Many2one(
        string='Chauffeur',
        comodel_name='transport.chauffeur',
        required=True,
        index=True,
        readonly=True,
        states={'draft': [('readonly', False)]},
        help='Chauffeur ou conducteur du vehicule.',
    )
    model_id = fields.Many2one(
        string='Modèle',
        comodel_name='fleet.vehicle.model',
        required=True,
        index=True,
        readonly=True,
        states={'draft': [('readonly', False)]},
        help='Modèle du vehicule.',
    )
    log_fuel = fields.One2many(comodel_name='fleet.vehicle.log.fuel',
                               inverse_name='vehicule_id',
                               string='Fuel Logs',
                               readonly=True,
                               states={'draft': [('readonly', False)]},
                               copy=True)
    log_services = fields.One2many(comodel_name='fleet.vehicle.log.services',
                                   inverse_name='vehicule_id',
                                   string='Services Logs',
                                   readonly=True,
                                   states={'draft': [('readonly', False)]},
                                   copy=True)
    log_contracts = fields.One2many(comodel_name='fleet.vehicle.log.contract',
                                    inverse_name='vehicule_id',
                                    string='Contracts',
                                    readonly=True,
                                    states={'draft': [('readonly', False)]},
                                    copy=True)
    fuel_type = fields.Selection([
        ('kilometers', 'Kilometers'),
        ('miles', 'Miles'),
    ],
                                 string='Odometer Unit',
                                 index=True,
                                 readonly=True,
                                 default='kilometers',
                                 copy=False,
                                 required=True,
                                 states={'draft': [('readonly', False)]},
                                 help=" Unit of the odometer \n")
    fuel_type = fields.Selection([
        ('manual', 'Manual'),
        ('automatic', 'Automatic'),
    ],
                                 string='Transmission',
                                 index=True,
                                 readonly=True,
                                 default='gasoline',
                                 copy=False,
                                 states={'draft': [('readonly', False)]},
                                 help=" Transmission Used by the vehicle \n")
    horsepower = fields.Integer(string='Horsepower',
                                required=False,
                                readonly=True,
                                translate=True,
                                select=True,
                                states={'draft': [('readonly', False)]},
                                help='Horsepower')
    horsepower_tax = fields.float(string='Horsepower Taxation',
                                  required=False,
                                  readonly=True,
                                  translate=True,
                                  select=True,
                                  states={'draft': [('readonly', False)]},
                                  help='Horsepower Taxation')
    power = fields.Integer(string='Power',
                           required=False,
                           readonly=True,
                           translate=True,
                           select=True,
                           states={'draft': [('readonly', False)]},
                           help='Power in kW of the vehicle')
    car_value = fields.float(string='Valeur Véhicule',
                             required=False,
                             readonly=True,
                             translate=True,
                             select=True,
                             states={'draft': [('readonly', False)]},
                             help='Valeur Véhicule')
    cost_count = fields.Integer(string='Costs',
                                store=True,
                                readonly=True,
                                compute='_count_all',
                                track_visibility='always')
    contract_count = fields.Integer(string='Contracts',
                                    store=True,
                                    readonly=True,
                                    compute='_count_all',
                                    track_visibility='always')
    service_count = fields.Integer(string='Services',
                                   store=True,
                                   readonly=True,
                                   compute='_count_all',
                                   track_visibility='always')
    fuel_logs_count = fields.Integer(string='Fuel Logs',
                                     store=True,
                                     readonly=True,
                                     compute='_count_all',
                                     track_visibility='always')
    odometer_count = fields.Float(string='Odometer',
                                  store=True,
                                  readonly=True,
                                  compute='_count_all',
                                  track_visibility='always')
    odometer = fields.Integer(string='Last Odometer',
                              store=True,
                              readonly=True,
                              compute='_get_odometer',
                              inverse='_set_odometer',
                              track_visibility='always')

    contract_renewal_due_soon = fields.Integer(
        string='Has Contracts to renew',
        store=True,
        readonly=True,
        compute='_get_contract_reminder_fnc',
        track_visibility='always')
    contract_renewal_overdue = fields.Integer(
        string='Has Contracts Overdue',
        store=True,
        readonly=True,
        compute='_get_contract_reminder_fnc',
        track_visibility='always')
    contract_renewal_name = fields.Integer(
        string='Name of contract to renew soon',
        store=True,
        readonly=True,
        compute='_get_contract_reminder_fnc',
        track_visibility='always')
    service_count = fields.Integer(
        string='Total of contracts due or overdue minus one',
        store=True,
        readonly=True,
        compute='_get_contract_reminder_fnc',
        track_visibility='always')

    @api.depends('expiration', 'mise_en_service')
    def _compute_days_to_expire(self):
        for rec in self:
            if rec.expiration:
                date = datetime.strptime(rec.expiration, '%Y-%m-%d')
                mise_en_service = datetime.strptime(rec.mise_en_service,
                                                    '%Y-%m-%d')
            else:
                date = datetime.now()
            now = datetime.now()
            delta = date - now
            delat_all = mise_en_service - date
            rec.days_to_expire = delta.days if delta.days > 0 else 0
            rec.duree_vie_usine = delat_all.days if delat_all.days > 0 else 0

    def on_change_model(self):
        if not model_id:
            return {}
        model = self.pool.get('fleet.vehicle.model').browse(
            self.env.cr, self.env.uid, model_id, context=self.env.context)
        return {
            'value': {
                'image_medium': model.image,
            }
        }

    def create(self, values):
        context = dict(self.env.context or {}, mail_create_nolog=True)
        values['state'] = 'draft'
        vehicle_id = super(
            TransportVehicule,
            self.with_context(mail_create_nolog=True)).create(values)
        vehicle = self.browse(vehicle_id)
        self.message_post(self.env.cr,
                          self.env.uid, [vehicle_id],
                          body=_('%s %s has been added to the fleet!') %
                          (vehicle.model_id.name, vehicle.imatriculation),
                          context=context)
        return vehicle_id

    def write(self, values):
        """
        This function write an entry in the openchatter whenever we change important information
        on the vehicle like the model, the drive, the state of the vehicle or its license plate
        """
        context = dict(self.env.context or {}, mail_create_nolog=True)
        for vehicle in self:
            changes = []
            if 'model_id' in vals and vehicle.model_id.id != vals['model_id']:
                value = self.pool.get('fleet.vehicle.model').browse(
                    self.env.cr,
                    self.env.uid,
                    vals['model_id'],
                    context=context).name
                oldmodel = vehicle.model_id.name or _('None')
                changes.append(
                    _("Model: from '%s' to '%s'") % (oldmodel, value))
            if 'chauffeur_id' in vals and vehicle.chauffeur_id.id != vals[
                    'chauffeur_id']:
                value = self.pool.get('res.partner').browse(
                    self.env.cr,
                    self.env.uid,
                    vals['chauffeur_id'],
                    context=context).name
                olddriver = (vehicle.chauffeur_id.name) or _('None')
                changes.append(
                    _("Driver: from '%s' to '%s'") % (olddriver, value))
            if 'state_id' in vals and vehicle.state_id.id != vals['state_id']:
                value = self.pool.get('fleet.vehicle.state').browse(
                    self.env.cr,
                    self.env.uid,
                    vals['state_id'],
                    context=context).name
                oldstate = vehicle.state_id.name or _('None')
                changes.append(
                    _("State: from '%s' to '%s'") % (oldstate, value))
            if 'imatriculation' in vals and vehicle.imatriculation != vals[
                    'imatriculation']:
                old_imatriculation = vehicle.imatriculation or _('None')
                changes.append(
                    _("License Plate: from '%s' to '%s'") %
                    (old_imatriculation, vals['imatriculation']))

            if len(changes) > 0:
                self.message_post(self.env.cr,
                                  self.env.uid, [vehicle.id],
                                  body=", ".join(changes),
                                  context=context)

        vehicle_id = super(
            TransportVehicule,
            self.with_context(mail_create_nolog=True)).write(vals)
        return True

    @api.multi
    def unlink(self):
        for record in self:
            if record.state == 'draft' or record.state == 'cancel':
                #super(TransportVehicule, self).unlink()
                models.Model.unlink(self)
            else:
                raise UserError(
                    _('Vous pouvez seulement supprimer les enregistrements qui sont soit annulés, soit à l\'état brouillon'
                      ))
                #raise Warning(_('You can only delete draft or cancel record'))
    @api.multi
    def bouton_cancel(self):
        for record in self:
            record.write({'state': 'cancel'})

    @api.multi
    def bouton_confirm(self):
        for record in self:
            record.write({'state': 'confirm'})

    @api.multi
    def bouton_rebut(self):
        for record in self:
            record.write({'state': 'rebut'})

    @api.multi
    def bouton_reparation(self):
        for record in self:
            record.write({'state': 'reparation'})

    @api.multi
    def bouton_panne(self):
        for record in self:
            record.write({'state': 'panne'})

    @api.multi
    def bouton_exploitation(self):
        for record in self:
            record.write({'state': 'exploitation'})
Example #29
0
class wage_increment_run(models.Model):

    _name = 'hr.contract.wage.increment.run'
    _description = 'Wage Increment Batches'

    _inherit = ['ir.needaction_mixin']

    _columns = {
        'name':
        fields.char(
            'Name',
            size=64,
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'effective_date':
        fields.date(
            'Effective Date',
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'type':
        fields.selection(
            [
                ('fixed', 'Fixed Amount'),
                ('percent', 'Percentage'),
                ('final', 'Final Amount'),
                ('manual', 'Manual'),
            ],
            'Type',
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'adjustment_amount':
        fields.float(
            'Adjustment Amount',
            digits_compute=dp.get_precision('Payroll'),
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'increment_ids':
        fields.one2many(
            'hr.contract.wage.increment',
            'run_id',
            'Adjustments',
            required=False,
            readonly=False,
            states={
                'confirm': [('readonly', False)],
                'approve': [('readonly', True)],
                'decline': [('readonly', True)],
            },
        ),
        'state':
        fields.selection([('draft', 'Draft'), ('confirm', 'Confirmed'),
                          ('approve', 'Approved'), ('decline', 'Declined')],
                         'State',
                         readonly=True),
    }

    _defaults = {
        'state': 'draft',
    }

    def _needaction_domain_get(self, cr, uid, context=None):

        users_obj = self.pool.get('res.users')
        domain = []

        if users_obj.has_group(cr, uid, 'hr_security.group_hr_director'):
            domain = [('state', 'in', ['confirm'])]
            return domain

        return False

    def unlink(self, cr, uid, ids, context=None):

        if isinstance(ids, (int, long)):
            ids = [ids]

        for run in self.browse(cr, uid, ids, context=context):
            if run.state in ['approve']:
                raise models.except_orm(
                    _('The adjustment run cannot be deleted!'),
                    _('You may not delete a wage adjustment that is in the '
                      '%s state.') % run.state)

        return super(wage_increment_run, self).unlink(cr,
                                                      uid,
                                                      ids,
                                                      context=context)

    def _state(self, cr, uid, ids, signal, state, context=None):

        wkf = netsvc.LocalService('workflow')
        for run in self.browse(cr, uid, ids, context=context):
            [
                wkf.trg_validate(uid, 'hr.contract.wage.increment', incr.id,
                                 signal, cr) for incr in run.increment_ids
            ]
            self.write(cr, uid, run.id, {'state': state}, context=context)

        return True

    def state_confirm(self, cr, uid, ids, context=None):

        return self._state(cr, uid, ids, 'signal_confirm', 'confirm', context)

    def state_approve(self, cr, uid, ids, context=None):

        return self._state(cr, uid, ids, 'signal_approve', 'approve', context)

    def state_decline(self, cr, uid, ids, context=None):

        return self._state(cr, uid, ids, 'signal_decline', 'decline', context)
Example #30
0
class wage_increment(models.Model):

    _name = 'hr.contract.wage.increment'
    _description = 'HR Contract Wage Adjustment'

    def _calculate_difference(self,
                              cr,
                              uid,
                              ids,
                              field_name,
                              args,
                              context=None):

        res = dict.fromkeys(ids)
        for incr in self.browse(cr, uid, ids, context=context):
            if incr.wage >= incr.contract_id.wage:
                percent = ((incr.wage / incr.contract_id.wage) - 1.0) * 100.0
            else:
                percent = (1.0 - (incr.wage / incr.contract_id.wage)) * -100.0
            res[incr.id] = {
                'wage_difference': incr.wage - incr.current_wage,
                'wage_difference_percent': percent,
            }

        return res

    def _get_department(self, cr, uid, ids, field_name, arg, context=None):

        res = dict.fromkeys(ids, False)
        for incr in self.browse(cr, uid, ids, context=context):
            res[incr.id] = incr.employee_id.department_id.id,

        return res

    _columns = {
        'effective_date':
        fields.date(
            'Effective Date',
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'wage':
        fields.float(
            'New Wage',
            digits_compute=dp.get_precision('Payroll'),
            required=True,
            readonly=True,
            states={'draft': [('readonly', False)]},
        ),
        'new_contract_id':
        fields.many2one(
            'hr.contract',
            'New Contract',
            readonly=True,
        ),
        'contract_id':
        fields.many2one(
            'hr.contract',
            'Contract',
            readonly=True,
        ),
        'current_wage':
        fields.related(
            'contract_id',
            'wage',
            type='float',
            string='Current Wage',
            store=True,
            readonly=True,
        ),
        'wage_difference':
        fields.function(
            _calculate_difference,
            type='float',
            method=True,
            string='Difference',
            multi='diff',
            readonly=True,
        ),
        'wage_difference_percent':
        fields.function(
            _calculate_difference,
            type='float',
            method=True,
            string='Percentage',
            multi='diff',
            readonly=True,
        ),
        'employee_id':
        fields.related(
            'contract_id',
            'employee_id',
            relation='hr.employee',
            type='many2one',
            string='Employee',
            store=True,
            readonly=True,
        ),
        'job_id':
        fields.related(
            'contract_id',
            'job_id',
            relation='hr.job',
            type='many2one',
            string='Job',
            store=True,
            readonly=True,
        ),
        'department_id':
        fields.related(
            'employee_id',
            'department_id',
            relation='hr.department',
            type='many2one',
            string='Department',
            store=True,
            readonly=True,
        ),
        'state':
        fields.selection(
            [('draft', 'Draft'), ('confirm', 'Confirmed'),
             ('approve', 'Approved'), ('decline', 'Declined')],
            'State',
            readonly=True,
        ),
        'run_id':
        fields.many2one(
            'hr.contract.wage.increment.run',
            'Batch Run',
            readonly=True,
            ondelete='cascade',
        ),
    }

    def _get_contract_data(self, cr, uid, field_list, context=None):

        if context is None:
            context = {}
        employee_id = self._get_employee(cr, uid, context=context)
        ee_data = self.pool.get('hr.employee').read(cr,
                                                    uid,
                                                    employee_id,
                                                    ['contract_id'],
                                                    context=context)
        contract_id = ee_data.get('contract_id', False)[0]
        if not contract_id:
            return False

        data = self.pool.get('hr.contract').read(cr,
                                                 uid,
                                                 contract_id,
                                                 field_list,
                                                 context=context)

        return data

    def _get_contract_id(self, cr, uid, context=None):

        data = self._get_contract_data(cr, uid, ['id'], context)
        return data.get('id', False)

    def _get_employee(self, cr, uid, context=None):

        if context is None:
            context = {}
        employee_id = context.get('active_id', False)

        return employee_id

    def _get_effective_date(self, cr, uid, context=None):

        contract_id = self._get_contract_id(cr, uid, context=context)
        if not contract_id:
            return False

        contract = self.pool.get('hr.contract').browse(cr,
                                                       uid,
                                                       contract_id,
                                                       context=context)
        if contract.pps_id:
            first_day = 1
            if contract.pps_id.type == 'monthly':
                first_day = contract.pps_id.mo_firstday
            date_format = '%Y-%m-' + first_day
            dThisMonth = datetime.now().strftime(date_format).strptime(
                DEFAULT_SERVER_DATE_FORMAT).date()
            dNextMonth = (datetime.now() + relativedelta(months=+1)).strftime(
                date_format).strptime(DEFAULT_SERVER_DATE_FORMAT).date()
            if dThisMonth < datetime.now().date():
                return dNextMonth.strftime(DEFAULT_SERVER_DATE_FORMAT)
            else:
                return dThisMonth.strftime(DEFAULT_SERVER_DATE_FORMAT)

        return False

    _defaults = {
        'contract_id': _get_contract_id,
        'employee_id': _get_employee,
        'effective_date': _get_effective_date,
        'state': 'draft',
    }

    _rec_name = 'effective_date'

    def _check_state(self, cr, uid, wage_incr, context=None):

        wage_incr_ids = self.search(
            cr,
            uid, [
                ('contract_id', '=', wage_incr.contract_id.id),
                ('state', 'in', ['draft', 'confirm', 'approved']),
                ('id', '!=', wage_incr.id),
            ],
            context=context)
        if len(wage_incr_ids) > 0:
            data = self.pool.get('hr.contract').read(cr,
                                                     uid,
                                                     wage_incr.contract_id.id,
                                                     ['name'],
                                                     context=context)
            raise models.except_orm(
                _('Warning'),
                _('There is already another wage adjustment in progress for '
                  'this contract: %s.') % (data['name']))

        contract_obj = self.pool.get('hr.contract')
        data = contract_obj.read(cr,
                                 uid,
                                 wage_incr.contract_id.id,
                                 ['state', 'date_end'],
                                 context=context)

        if data['state'] in ['draft', 'done']:
            data = self.pool.get('hr.contract').read(cr,
                                                     uid,
                                                     wage_incr.contract_id.id,
                                                     ['name'],
                                                     context=context)
            raise models.except_orm(
                _('Warning!'),
                _('The current state of the contract does not permit a wage '
                  'change: %s') % (data['name']))

        if data.get('date_end', False) and data['date_end'] != '':
            dContractEnd = datetime.strptime(data['date_end'],
                                             DEFAULT_SERVER_DATE_FORMAT)
            dEffective = datetime.strptime(wage_incr.effective_date,
                                           DEFAULT_SERVER_DATE_FORMAT)
            if dEffective >= dContractEnd:
                data = self.pool.get('hr.contract').read(
                    cr,
                    uid,
                    wage_incr.contract_id.id, ['name'],
                    context=context)
                raise models.except_orm(
                    _('Warning!'),
                    _('The contract end date is on or before the effective '
                      'date of the adjustment: %s') % (data['name']))
        return True

    def action_wage_increment(self, cr, uid, ids, context=None):

        hr_obj = self.pool.get('hr.contract')

        if isinstance(ids, (int, long)):
            ids = [ids]

        # Copy the contract and adjust start/end dates and wage accordingly.
        #
        for wi in self.browse(cr, uid, ids, context=context):

            if -0.01 < wi.wage_difference < 0.01:
                continue

            self._check_state(cr, uid, wi, context=context)

            default = {
                'wage': wi.wage,
                'date_start': wi.effective_date,
                'name': False,
                'state': False,
                'message_ids': False,
                'trial_date_start': False,
                'trial_date_end': False,
            }
            data = hr_obj.copy_data(cr,
                                    uid,
                                    wi.contract_id.id,
                                    default=default,
                                    context=context)
            notes = data.get('notes', False)
            if not notes:
                notes = ''
            notes = notes + \
                _('\nSuperceedes (because of wage adjustment) previous '
                  'contract: ') + wi.contract_id.name
            data['notes'] = notes

            c_id = hr_obj.create(cr, uid, data, context=context)
            if c_id:
                if wi.contract_id.notes:
                    notes = wi.contract_id.notes
                else:
                    notes = ''
                notes = notes + \
                    _('\nSuperceeded (for wage adjustment) by contract: ') + \
                    wi.contract_id.name
                vals = {'notes': notes, 'date_end': False}
                wkf = netsvc.LocalService('workflow')

                # Set the new contract to the appropriate state
                wkf.trg_validate(uid, 'hr.contract', c_id, 'signal_confirm',
                                 cr)

                # Terminate the current contract (and trigger appropriate state
                # change)
                vals['date_end'] = datetime.strptime(
                    wi.effective_date, '%Y-%m-%d').date() + \
                    relativedelta(days=-1)
                hr_obj.write(cr, uid, wi.contract_id.id, vals, context=context)
                wkf.trg_validate(uid, 'hr.contract', wi.contract_id.id,
                                 'signal_done', cr)

        return

    def create(self, cr, uid, vals, context=None):

        contract_id = vals.get('contract_id', False)

        if not contract_id:
            if context is not None:
                contract_id = context.get('active_id')

        data = self.pool.get('hr.contract').read(cr,
                                                 uid,
                                                 contract_id,
                                                 ['name', 'date_start'],
                                                 context=context)

        # Check that the contract start date is before the effective date
        if vals['effective_date'] <= data['date_start']:
            raise models.except_orm(
                _('Error'),
                _('The effective date of the adjustment must be after the '
                  'contract start date. Contract: %s.') % (data['name']))

        wage_incr_ids = self.search(
            cr,
            uid, [
                ('contract_id', '=', contract_id),
                ('state', 'in', ['draft', 'confirm', 'approved']),
            ],
            context=context)
        if len(wage_incr_ids) > 0:
            raise models.except_orm(
                _('Warning'),
                _('There is already another wage adjustment in progress for '
                  'this contract: %s.') % (data['name']))

        return super(wage_increment, self).create(cr,
                                                  uid,
                                                  vals,
                                                  context=context)

    def do_signal_confirm(self, cr, uid, ids, context=None):

        for wi in self.browse(cr, uid, ids, context=context):
            self._check_state(cr, uid, wi, context=context)
            self.write(cr, uid, wi.id, {'state': 'confirm'}, context=context)

    def do_signal_approve(self, cr, uid, ids, context=None):

        for i in ids:
            self.action_wage_increment(cr, uid, [i], context=context)
            self.write(cr, uid, i, {'state': 'approve'}, context=context)

    def unlink(self, cr, uid, ids, context=None):

        for incr in self.browse(cr, uid, ids, context=context):
            if incr.state in ['approve']:
                raise models.except_orm(
                    _('The record cannot be deleted!'),
                    _("""\
You may not delete a record that is in a %s state:
Employee: %s""") % (incr.state, incr.employee_id.name))

        return super(wage_increment, self).unlink(cr,
                                                  uid,
                                                  ids,
                                                  context=context)