class Company(models.Model): _inherit = 'res.company' po_lead = fields.Float( string='Purchase Lead Time', required=True, help="Margin of error for vendor lead times. When the system " "generates Purchase Orders for procuring products, " "they will be scheduled that many days earlier " "to cope with unexpected vendor delays.", default=0.0) po_lock = fields.Selection( [('edit', 'Allow to edit purchase orders'), ('lock', 'Confirmed purchase orders are not editable')], string="Purchase Order Modification", default="edit", help= 'Purchase Order Modification used when you want to purchase order editable after confirm' ) po_double_validation = fields.Selection( [('one_step', 'Confirm purchase orders in one step'), ('two_step', 'Get 2 levels of approvals to confirm a purchase order') ], string="Levels of Approvals", default='one_step', help="Provide a double validation mechanism for purchases") po_double_validation_amount = fields.Monetary( string='Double validation amount', default=5000, help="Minimum amount for which a double validation is required")
class MixedModel(models.Model): _name = 'test_new_api.mixed' number = fields.Float(digits=(10, 2), default=3.14) date = fields.Date() now = fields.Datetime(compute='_compute_now') lang = fields.Selection(string='Language', selection='_get_lang') reference = fields.Reference(string='Related Document', selection='_reference_models') comment1 = fields.Html(sanitize=False) comment2 = fields.Html(sanitize_attributes=True, strip_classes=False) comment3 = fields.Html(sanitize_attributes=True, strip_classes=True) comment4 = fields.Html(sanitize_attributes=True, strip_style=True) currency_id = fields.Many2one( 'res.currency', default=lambda self: self.env.ref('base.EUR')) amount = fields.Monetary() @api.one def _compute_now(self): # this is a non-stored computed field without dependencies self.now = fields.Datetime.now() @api.model def _get_lang(self): return self.env['res.lang'].get_installed() @api.model def _reference_models(self): models = self.env['ir.model'].sudo().search([('state', '!=', 'manual') ]) return [(model.model, model.name) for model in models if not model.model.startswith('ir.')]
class AccountInvoiceLine(models.Model): _inherit = 'account.invoice.line' _order = 'invoice_id, layout_category_id, sequence, id' @api.depends('price_unit', 'discount', 'invoice_line_tax_ids', 'quantity', 'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id', 'invoice_id.date_invoice') def _compute_total_price(self): for line in self: price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = line.invoice_line_tax_ids.compute_all( price, line.invoice_id.currency_id, line.quantity, product=line.product_id, partner=line.invoice_id.partner_id) line.price_total = taxes['total_included'] sale_line_ids = fields.Many2many('sale.order.line', 'sale_order_line_invoice_rel', 'invoice_line_id', 'order_line_id', string='Sales Order Lines', readonly=True, copy=False) layout_category_id = fields.Many2one('sale.layout_category', string='Section') layout_category_sequence = fields.Integer(string='Layout Sequence') # TODO: remove layout_category_sequence in master or make it work properly price_total = fields.Monetary(compute='_compute_total_price', string='Total Amount', store=True)
class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' lock_confirmed_po = fields.Boolean( "Lock Confirmed Orders", default=lambda self: self.env.user.company_id.po_lock == 'lock') po_lock = fields.Selection(related='company_id.po_lock', string="Purchase Order Modification *") po_order_approval = fields.Boolean( "Order Approval", default=lambda self: self.env.user.company_id.po_double_validation == 'two_step') po_double_validation = fields.Selection( related='company_id.po_double_validation', string="Levels of Approvals *") po_double_validation_amount = fields.Monetary( related='company_id.po_double_validation_amount', string="Minimum Amount", currency_field='company_currency_id') company_currency_id = fields.Many2one( 'res.currency', related='company_id.currency_id', readonly=True, help='Utility field to express amount currency') default_purchase_method = fields.Selection( [ ('purchase', 'Ordered quantities'), ('receive', 'Delivered quantities'), ], string="Bill Control", default_model="product.template", help="This default value is applied to any new product created. " "This can be changed in the product detail form.", default="receive") module_purchase_requisition = fields.Boolean("Purchase Agreements") group_warning_purchase = fields.Boolean( "Warnings", implied_group='purchase.group_warning_purchase') module_stock_dropshipping = fields.Boolean("Dropshipping") group_manage_vendor_price = fields.Boolean( "Vendor Pricelists", implied_group="purchase.group_manage_vendor_price") is_installed_sale = fields.Boolean(string="Is the Sale Module Installed") group_analytic_account_for_purchases = fields.Boolean( 'Analytic accounting for purchases', implied_group='purchase.group_analytic_accounting') @api.multi def get_values(self): res = super(ResConfigSettings, self).get_values() res.update(is_installed_sale=self.env['ir.module.module'].search([( 'name', '=', 'sale'), ('state', '=', 'installed')]).id) return res def set_values(self): super(ResConfigSettings, self).set_values() self.po_lock = 'lock' if self.lock_confirmed_po else 'edit' self.po_double_validation = 'two_step' if self.po_order_approval else 'one_step'
class CrmLead(models.Model): _inherit = 'crm.lead' sale_amount_total = fields.Monetary(compute='_compute_sale_amount_total', string="Sum of Orders", help="Untaxed Total of Confirmed Orders", currency_field='company_currency') sale_number = fields.Integer(compute='_compute_sale_amount_total', string="Number of Quotations") order_ids = fields.One2many('sale.order', 'opportunity_id', string='Orders') @api.depends('order_ids') def _compute_sale_amount_total(self): for lead in self: total = 0.0 nbr = 0 company_currency = lead.company_currency or self.env.user.company_id.currency_id for order in lead.order_ids: if order.state in ('draft', 'sent', 'sale'): nbr += 1 if order.state not in ('draft', 'sent', 'cancel'): total += order.currency_id.compute(order.amount_untaxed, company_currency) lead.sale_amount_total = total lead.sale_number = nbr @api.model def retrieve_sales_dashboard(self): res = super(CrmLead, self).retrieve_sales_dashboard() date_today = fields.Date.from_string(fields.Date.context_today(self)) res['invoiced'] = { 'this_month': 0, 'last_month': 0, } account_invoice_domain = [ ('state', 'in', ['open', 'paid']), ('user_id', '=', self.env.uid), ('date_invoice', '>=', date_today.replace(day=1) - relativedelta(months=+1)), ('type', 'in', ['out_invoice', 'out_refund']) ] invoice_data = self.env['account.invoice'].search_read(account_invoice_domain, ['date_invoice', 'amount_untaxed_signed']) for invoice in invoice_data: if invoice['date_invoice']: invoice_date = fields.Date.from_string(invoice['date_invoice']) if invoice_date <= date_today and invoice_date >= date_today.replace(day=1): res['invoiced']['this_month'] += invoice['amount_untaxed_signed'] elif invoice_date < date_today.replace(day=1) and invoice_date >= date_today.replace(day=1) - relativedelta(months=+1): res['invoiced']['last_month'] += invoice['amount_untaxed_signed'] res['invoiced']['target'] = self.env.user.target_sales_invoiced return res
class SaleOrder(models.Model): _inherit = "sale.order" margin = fields.Monetary( compute='_product_margin', help= "It gives profitability by calculating the difference between the Unit Price and the cost.", currency_field='currency_id', digits=dp.get_precision('Product Price'), store=True) @api.depends('order_line.margin') def _product_margin(self): for order in self: order.margin = sum( order.order_line.filtered( lambda r: r.state != 'cancel').mapped('margin'))
class AccountAnalyticLine(models.Model): _name = 'account.analytic.line' _description = 'Analytic Line' _order = 'date desc, id desc' @api.model def _default_user(self): return self.env.context.get('user_id', self.env.user.id) name = fields.Char('Description', required=True) date = fields.Date('Date', required=True, index=True, default=fields.Date.context_today) amount = fields.Monetary('Amount', required=True, default=0.0) unit_amount = fields.Float('Quantity', default=0.0) account_id = fields.Many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='restrict', index=True) partner_id = fields.Many2one('res.partner', string='Partner') user_id = fields.Many2one('res.users', string='User', default=_default_user) tag_ids = fields.Many2many('account.analytic.tag', 'account_analytic_line_tag_rel', 'line_id', 'tag_id', string='Tags', copy=True) company_id = fields.Many2one(related='account_id.company_id', string='Company', store=True, readonly=True) branch_id = fields.Many2one(related='account_id.branch_id', string='Branch', store=True, readonly=True) currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True)
class AccountAnalyticLine(models.Model): _inherit = 'account.analytic.line' timesheet_invoice_type = fields.Selection( [('billable_time', 'Billable Time'), ('billable_fixed', 'Billable Fixed'), ('non_billable', 'Non Billable'), ('non_billable_project', 'No task found')], string="Billable Type", readonly=True, copy=False) timesheet_invoice_id = fields.Many2one( 'account.invoice', string="Invoice", readonly=True, copy=False, help="Invoice created from the timesheet") timesheet_revenue = fields.Monetary("Revenue", default=0.0, readonly=True, currency_field='company_currency_id', copy=False) @api.model def create(self, values): result = super(AccountAnalyticLine, self).create(values) # applied only for timesheet if result.project_id: result._timesheet_postprocess(values) return result @api.multi def write(self, values): # prevent to update invoiced timesheets if one line is of type delivery if self.sudo().filtered( lambda aal: aal.so_line.product_id.invoice_policy == "delivery" ) and self.filtered(lambda timesheet: timesheet.timesheet_invoice_id): if any([ field_name in values for field_name in [ 'unit_amount', 'employee_id', 'task_id', 'timesheet_revenue', 'so_line', 'amount', 'date' ] ]): raise UserError( _('You can not modify already invoiced timesheets (linked to a Sales order items invoiced on Time and material).' )) result = super(AccountAnalyticLine, self).write(values) # applied only for timesheet self.filtered(lambda t: t.project_id)._timesheet_postprocess(values) return result @api.model def _timesheet_preprocess(self, values): values = super(AccountAnalyticLine, self)._timesheet_preprocess(values) # task implies so line if 'task_id' in values: task = self.env['project.task'].sudo().browse(values['task_id']) values['so_line'] = task.sale_line_id.id or values.get( 'so_line', False) # Set product_uom_id now so delivered qty is computed in SO line if not 'product_uom_id' in values and all( [v in values for v in ['employee_id', 'project_id']]): employee = self.env['hr.employee'].sudo().browse( values['employee_id']) values[ 'product_uom_id'] = employee.company_id.project_time_mode_id.id return values @api.multi def _timesheet_postprocess(self, values): sudo_self = self.sudo( ) # this creates only one env for all operation that required sudo() # (re)compute the amount (depending on unit_amount, employee_id for the cost, and account_id for currency) if any([ field_name in values for field_name in ['unit_amount', 'employee_id', 'account_id'] ]): for timesheet in sudo_self: uom = timesheet.employee_id.company_id.project_time_mode_id cost = timesheet.employee_id.timesheet_cost or 0.0 amount = -timesheet.unit_amount * cost amount_converted = timesheet.employee_id.currency_id.compute( amount, timesheet.account_id.currency_id) timesheet.write({ 'amount': amount_converted, 'product_uom_id': uom.id, }) # (re)compute the theorical revenue if any([ field_name in values for field_name in ['so_line', 'unit_amount', 'account_id'] ]): sudo_self._timesheet_compute_theorical_revenue() return values @api.multi def _timesheet_compute_theorical_revenue(self): for timesheet in self: values = timesheet._timesheet_compute_theorical_revenue_values() timesheet.write(values) return True @api.multi def _timesheet_compute_theorical_revenue_values(self): """ This method set the theorical revenue on the current timesheet lines. If invoice on delivered quantity: timesheet hours * (SO Line Price) * (1- discount), elif invoice on ordered quantities & create task: min ( timesheet hours * (SO Line unit price) * (1- discount), TOTAL SO - TOTAL INVOICED - sum(timesheet revenues with invoice_id=False) ) else: 0 """ self.ensure_one() timesheet = self # find the timesheet UoM timesheet_uom = timesheet.product_uom_id if not timesheet_uom: # fallback on default company timesheet UoM timesheet_uom = self.env.user.company_id.project_time_mode_id # default values unit_amount = timesheet.unit_amount so_line = timesheet.so_line values = { 'timesheet_revenue': 0.0, 'timesheet_invoice_type': 'non_billable_project' if not timesheet.task_id else 'non_billable', } # set the revenue and billable type according to the product and the SO line if timesheet.task_id and so_line.product_id.type == 'service': # find the analytic account to convert revenue into its currency analytic_account = timesheet.account_id # convert the unit of mesure into hours sale_price_hour = so_line.product_uom._compute_price( so_line.price_unit, timesheet_uom) sale_price = so_line.currency_id.compute( sale_price_hour, analytic_account.currency_id ) # amount from SO should be convert into analytic account currency # calculate the revenue on the timesheet if so_line.product_id.invoice_policy == 'delivery': values[ 'timesheet_revenue'] = analytic_account.currency_id.round( unit_amount * sale_price * (1 - (so_line.discount / 100))) values[ 'timesheet_invoice_type'] = 'billable_time' if so_line.product_id.service_type == 'timesheet' else 'billable_fixed' elif so_line.product_id.invoice_policy == 'order' and so_line.product_id.service_type == 'timesheet': quantity_hour = unit_amount if so_line.product_uom.category_id == timesheet_uom.category_id: quantity_hour = so_line.product_uom._compute_quantity( so_line.product_uom_qty, timesheet_uom) # compute the total revenue the SO since we are in fixed price total_revenue_so = analytic_account.currency_id.round( quantity_hour * sale_price * (1 - (so_line.discount / 100))) # compute the total revenue already existing (without the current timesheet line) domain = [('so_line', '=', so_line.id)] if timesheet.ids: domain += [('id', 'not in', timesheet.ids)] analytic_lines = timesheet.search(domain) total_revenue_invoiced = sum( analytic_lines.mapped('timesheet_revenue')) # compute (new) revenue of current timesheet line values['timesheet_revenue'] = min( analytic_account.currency_id.round( unit_amount * so_line.currency_id.compute( so_line.price_unit, analytic_account.currency_id) * (1 - so_line.discount)), total_revenue_so - total_revenue_invoiced) values['timesheet_invoice_type'] = 'billable_fixed' # if the so line is already invoiced, and the delivered qty is still smaller than the ordered, then link the timesheet to the invoice if so_line.invoice_status == 'invoiced': values[ 'timesheet_invoice_id'] = so_line.invoice_lines and so_line.invoice_lines[ 0].invoice_id.id elif so_line.product_id.invoice_policy == 'order' and so_line.product_id.service_type != 'timesheet': values['timesheet_invoice_type'] = 'billable_fixed' return values
class ResPartner(models.Model): _name = 'res.partner' _inherit = 'res.partner' @api.multi def _credit_debit_get(self): tables, where_clause, where_params = self.env[ 'account.move.line']._query_get() where_params = [tuple(self.ids)] + where_params if where_clause: where_clause = 'AND ' + where_clause self._cr.execute( """SELECT account_move_line.partner_id, act.type, SUM(account_move_line.amount_residual) FROM account_move_line LEFT JOIN account_account a ON (account_move_line.account_id=a.id) LEFT JOIN account_account_type act ON (a.user_type_id=act.id) WHERE act.type IN ('receivable','payable') AND account_move_line.partner_id IN %s AND account_move_line.reconciled IS FALSE """ + where_clause + """ GROUP BY account_move_line.partner_id, act.type """, where_params) for pid, type, val in self._cr.fetchall(): partner = self.browse(pid) if type == 'receivable': partner.credit = val elif type == 'payable': partner.debit = -val @api.multi def _asset_difference_search(self, account_type, operator, operand): if operator not in ('<', '=', '>', '>=', '<='): return [] if type(operand) not in (float, int): return [] sign = 1 if account_type == 'payable': sign = -1 res = self._cr.execute( ''' SELECT partner.id FROM res_partner partner LEFT JOIN account_move_line aml ON aml.partner_id = partner.id RIGHT JOIN account_account acc ON aml.account_id = acc.id WHERE acc.internal_type = %s AND NOT acc.deprecated GROUP BY partner.id HAVING %s * COALESCE(SUM(aml.amount_residual), 0) ''' + operator + ''' %s''', (account_type, sign, operand)) res = self._cr.fetchall() if not res: return [('id', '=', '0')] return [('id', 'in', [r[0] for r in res])] @api.model def _credit_search(self, operator, operand): return self._asset_difference_search('receivable', operator, operand) @api.model def _debit_search(self, operator, operand): return self._asset_difference_search('payable', operator, operand) @api.multi def _invoice_total(self): account_invoice_report = self.env['account.invoice.report'] if not self.ids: self.total_invoiced = 0.0 return True user_currency_id = self.env.user.company_id.currency_id.id all_partners_and_children = {} all_partner_ids = [] for partner in self: # price_total is in the company currency all_partners_and_children[partner] = self.with_context( active_test=False).search([('id', 'child_of', partner.id)]).ids all_partner_ids += all_partners_and_children[partner] # searching account.invoice.report via the orm is comparatively expensive # (generates queries "id in []" forcing to build the full table). # In simple cases where all invoices are in the same currency than the user's company # access directly these elements # generate where clause to include multicompany rules where_query = account_invoice_report._where_calc([ ('partner_id', 'in', all_partner_ids), ('state', 'not in', ['draft', 'cancel']), ('type', 'in', ('out_invoice', 'out_refund')) ]) account_invoice_report._apply_ir_rules(where_query, 'read') from_clause, where_clause, where_clause_params = where_query.get_sql() # price_total is in the company currency query = """ SELECT SUM(price_total) as total, partner_id FROM account_invoice_report account_invoice_report WHERE %s GROUP BY partner_id """ % where_clause self.env.cr.execute(query, where_clause_params) price_totals = self.env.cr.dictfetchall() for partner, child_ids in all_partners_and_children.items(): partner.total_invoiced = sum(price['total'] for price in price_totals if price['partner_id'] in child_ids) @api.multi def _compute_journal_item_count(self): AccountMoveLine = self.env['account.move.line'] for partner in self: partner.journal_item_count = AccountMoveLine.search_count([ ('partner_id', '=', partner.id) ]) @api.multi def _compute_contracts_count(self): AccountAnalyticAccount = self.env['account.analytic.account'] for partner in self: partner.contracts_count = AccountAnalyticAccount.search_count([ ('partner_id', '=', partner.id) ]) def get_followup_lines_domain(self, date, overdue_only=False, only_unblocked=False): domain = [('reconciled', '=', False), ('account_id.deprecated', '=', False), ('account_id.internal_type', '=', 'receivable'), '|', ('debit', '!=', 0), ('credit', '!=', 0), ('company_id', '=', self.env.user.company_id.id)] if only_unblocked: domain += [('blocked', '=', False)] if self.ids: if 'exclude_given_ids' in self._context: domain += [('partner_id', 'not in', self.ids)] else: domain += [('partner_id', 'in', self.ids)] #adding the overdue lines overdue_domain = [ '|', '&', ('date_maturity', '!=', False), ('date_maturity', '<', date), '&', ('date_maturity', '=', False), ('date', '<', date) ] if overdue_only: domain += overdue_domain return domain @api.one def _compute_has_unreconciled_entries(self): # Avoid useless work if has_unreconciled_entries is not relevant for this partner if not self.active or not self.is_company and self.parent_id: return self.env.cr.execute( """ SELECT 1 FROM( SELECT p.last_time_entries_checked AS last_time_entries_checked, MAX(l.write_date) AS max_date FROM account_move_line l RIGHT JOIN account_account a ON (a.id = l.account_id) RIGHT JOIN res_partner p ON (l.partner_id = p.id) WHERE p.id = %s AND EXISTS ( SELECT 1 FROM account_move_line l WHERE l.account_id = a.id AND l.partner_id = p.id AND l.amount_residual > 0 ) AND EXISTS ( SELECT 1 FROM account_move_line l WHERE l.account_id = a.id AND l.partner_id = p.id AND l.amount_residual < 0 ) GROUP BY p.last_time_entries_checked ) as s WHERE (last_time_entries_checked IS NULL OR max_date > last_time_entries_checked) """, (self.id, )) self.has_unreconciled_entries = self.env.cr.rowcount == 1 @api.multi def mark_as_reconciled(self): self.env['account.partial.reconcile'].check_access_rights('write') return self.sudo().with_context( company_id=self.env.user.company_id.id).write({ 'last_time_entries_checked': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) }) @api.one def _get_company_currency(self): if self.company_id: self.currency_id = self.sudo().company_id.currency_id else: self.currency_id = self.env.user.company_id.currency_id credit = fields.Monetary(compute='_credit_debit_get', search=_credit_search, string='Total Receivable', help="Total amount this customer owes you.") debit = fields.Monetary( compute='_credit_debit_get', search=_debit_search, string='Total Payable', help="Total amount you have to pay to this vendor.") debit_limit = fields.Monetary('Payable Limit') total_invoiced = fields.Monetary(compute='_invoice_total', string="Total Invoiced", groups='account.group_account_invoice') currency_id = fields.Many2one( 'res.currency', compute='_get_company_currency', readonly=True, string="Currency", help='Utility field to express amount currency') contracts_count = fields.Integer(compute='_compute_contracts_count', string="Contracts", type='integer') journal_item_count = fields.Integer(compute='_compute_journal_item_count', string="Journal Items", type="integer") property_account_payable_id = fields.Many2one( 'account.account', company_dependent=True, string="Account Payable", oldname="property_account_payable", domain= "[('internal_type', '=', 'payable'), ('deprecated', '=', False)]", help= "This account will be used instead of the default one as the payable account for the current partner", required=True) property_account_receivable_id = fields.Many2one( 'account.account', company_dependent=True, string="Account Receivable", oldname="property_account_receivable", domain= "[('internal_type', '=', 'receivable'), ('deprecated', '=', False)]", help= "This account will be used instead of the default one as the receivable account for the current partner", required=True) property_account_position_id = fields.Many2one( 'account.fiscal.position', company_dependent=True, string="Fiscal Position", help= "The fiscal position will determine taxes and accounts used for the partner.", oldname="property_account_position") property_payment_term_id = fields.Many2one( 'account.payment.term', company_dependent=True, string='Customer Payment Terms', help= "This payment term will be used instead of the default one for sales orders and customer invoices", oldname="property_payment_term") property_supplier_payment_term_id = fields.Many2one( 'account.payment.term', company_dependent=True, string='Vendor Payment Terms', help= "This payment term will be used instead of the default one for purchase orders and vendor bills", oldname="property_supplier_payment_term") ref_company_ids = fields.One2many( 'res.company', 'partner_id', string='Companies that refers to partner', oldname="ref_companies") has_unreconciled_entries = fields.Boolean( compute='_compute_has_unreconciled_entries', help= "The partner has at least one unreconciled debit and credit since last time the invoices & payments matching was performed." ) last_time_entries_checked = fields.Datetime( oldname='last_reconciliation_date', string='Latest Invoices & Payments Matching Date', readonly=True, copy=False, help= 'Last time the invoices & payments matching was performed for this partner. ' 'It is set either if there\'s not at least an unreconciled debit and an unreconciled credit ' 'or if you click the "Done" button.') invoice_ids = fields.One2many('account.invoice', 'partner_id', string='Invoices', readonly=True, copy=False) contract_ids = fields.One2many('account.analytic.account', 'partner_id', string='Contracts', readonly=True) bank_account_count = fields.Integer(compute='_compute_bank_count', string="Bank") trust = fields.Selection([('good', 'Good Debtor'), ('normal', 'Normal Debtor'), ('bad', 'Bad Debtor')], string='Degree of trust you have in this debtor', default='normal', company_dependent=True) invoice_warn = fields.Selection(WARNING_MESSAGE, 'Invoice', help=WARNING_HELP, required=True, default="no-message") invoice_warn_msg = fields.Text('Message for Invoice') @api.multi def _compute_bank_count(self): bank_data = self.env['res.partner.bank'].read_group( [('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id']) mapped_data = dict([(bank['partner_id'][0], bank['partner_id_count']) for bank in bank_data]) for partner in self: partner.bank_account_count = mapped_data.get(partner.id, 0) def _find_accounting_partner(self, partner): ''' Find the partner for which the accounting entries will be created ''' return partner.commercial_partner_id @api.model def _commercial_fields(self): return super(ResPartner, self)._commercial_fields() + \ ['debit_limit', 'property_account_payable_id', 'property_account_receivable_id', 'property_account_position_id', 'property_payment_term_id', 'property_supplier_payment_term_id', 'last_time_entries_checked'] @api.multi def action_view_partner_invoices(self): self.ensure_one() action = self.env.ref( 'account.action_invoice_refund_out_tree').read()[0] action['domain'] = literal_eval(action['domain']) action['domain'].append(('partner_id', 'child_of', self.id)) return action
class AccountClosing(models.Model): """ This object holds an interval total and a grand total of the accounts of type receivable for a company, as well as the last account_move that has been counted in a previous object It takes its earliest brother to infer from when the computation needs to be done in order to compute its own data. """ _name = 'account.sale.closing' _order = 'date_closing_stop desc, sequence_number desc' name = fields.Char(help="Frequency and unique sequence number", required=True) company_id = fields.Many2one('res.company', string='Company', readonly=True, required=True) date_closing_stop = fields.Datetime(string="Closing Date", help='Date to which the values are computed', readonly=True, required=True) date_closing_start = fields.Datetime(string="Starting Date", help='Date from which the total interval is computed', readonly=True, required=True) frequency = fields.Selection(string='Closing Type', selection=[('daily', 'Daily'), ('monthly', 'Monthly'), ('annually', 'Annual')], readonly=True, required=True) total_interval = fields.Monetary(string="Period Total", help='Total in receivable accounts during the interval, excluding overlapping periods', readonly=True, required=True) cumulative_total = fields.Monetary(string="Cumulative Grand Total", help='Total in receivable accounts since the beginnig of times', readonly=True, required=True) sequence_number = fields.Integer('Sequence #', readonly=True, required=True) last_move_id = fields.Many2one('account.move', string='Last journal entry', help='Last Journal entry included in the grand total', readonly=True) last_move_hash = fields.Char(string='Last journal entry\'s inalteralbility hash', readonly=True) currency_id = fields.Many2one('res.currency', string='Currency', help="The company's currency", readonly=True, related='company_id.currency_id', store=True) def _query_for_aml(self, company, first_move_sequence_number, date_start): params = {'company_id': company.id} query = '''WITH aggregate AS (SELECT m.id AS move_id, aml.balance AS balance, aml.id as line_id FROM account_move_line aml JOIN account_journal j ON aml.journal_id = j.id JOIN account_account acc ON acc.id = aml.account_id JOIN account_account_type t ON (t.id = acc.user_type_id AND t.type = 'receivable') JOIN account_move m ON m.id = aml.move_id WHERE j.type = 'sale' AND aml.company_id = %(company_id)s AND m.state = 'posted' ''' if first_move_sequence_number is not False and first_move_sequence_number is not None: params['first_move_sequence_number'] = first_move_sequence_number query += '''AND m.l10n_fr_secure_sequence_number > %(first_move_sequence_number)s''' elif date_start: #the first time we compute the closing, we consider only from the installation of the module params['date_start'] = date_start query += '''AND m.date >= %(date_start)s''' query += " ORDER BY m.l10n_fr_secure_sequence_number DESC) " query += '''SELECT array_agg(move_id) AS move_ids, array_agg(line_id) AS line_ids, sum(balance) AS balance FROM aggregate''' self.env.cr.execute(query, params) return self.env.cr.dictfetchall()[0] def _compute_amounts(self, frequency, company): """ Method used to compute all the business data of the new object. It will search for previous closings of the same frequency to infer the move from which account move lines should be fetched. @param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually) frequencies are literal (daily means 24 hours and so on) @param {recordset} company: the company for which the closing is done @return {dict} containing {field: value} for each business field of the object """ interval_dates = self._interval_dates(frequency, company) previous_closing = self.search([ ('frequency', '=', frequency), ('company_id', '=', company.id)], limit=1, order='sequence_number desc') first_move = self.env['account.move'] date_start = interval_dates['interval_from'] cumulative_total = 0 if previous_closing: first_move = previous_closing.last_move_id date_start = previous_closing.create_date cumulative_total += previous_closing.cumulative_total aml_aggregate = self._query_for_aml(company, first_move.l10n_fr_secure_sequence_number, date_start) total_interval = aml_aggregate['balance'] or 0 cumulative_total += total_interval # We keep the reference to avoid gaps (like daily object during the weekend) last_move = first_move if aml_aggregate['move_ids']: last_move = last_move.browse(aml_aggregate['move_ids'][0]) return {'total_interval': total_interval, 'cumulative_total': cumulative_total, 'last_move_id': last_move.id, 'last_move_hash': last_move.l10n_fr_hash, 'date_closing_stop': interval_dates['date_stop'], 'date_closing_start': date_start, 'name': interval_dates['name_interval'] + ' - ' + interval_dates['date_stop'][:10]} def _interval_dates(self, frequency, company): """ Method used to compute the theoretical date from which account move lines should be fetched @param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually) frequencies are literal (daily means 24 hours and so on) @param {recordset} company: the company for which the closing is done @return {dict} the theoretical date from which account move lines are fetched. date_stop date to which the move lines are fetched, always now() the dates are in their actpy Database string representation """ date_stop = datetime.utcnow() interval_from = None name_interval = '' if frequency == 'daily': interval_from = date_stop - timedelta(days=1) name_interval = _('Daily Closing') elif frequency == 'monthly': month_target = date_stop.month > 1 and date_stop.month - 1 or 12 year_target = month_target < 12 and date_stop.year or date_stop.year - 1 interval_from = date_stop.replace(year=year_target, month=month_target) name_interval = _('Monthly Closing') elif frequency == 'annually': year_target = date_stop.year - 1 interval_from = date_stop.replace(year=year_target) name_interval = _('Annual Closing') return {'interval_from': FieldDateTime.to_string(interval_from), 'date_stop': FieldDateTime.to_string(date_stop), 'name_interval': name_interval} @api.multi def write(self, vals): raise UserError(_('Sale Closings are not meant to be written or deleted under any circumstances.')) @api.multi def unlink(self): raise UserError(_('Sale Closings are not meant to be written or deleted under any circumstances.')) @api.model def _automated_closing(self, frequency='daily'): """To be executed by the CRON to create an object of the given frequency for each company that needs it @param {string} frequency: a valid value of the selection field on the object (daily, monthly, annually) frequencies are literal (daily means 24 hours and so on) @return {recordset} all the objects created for the given frequency """ res_company = self.env['res.company'].search([]) account_closings = self.env['account.sale.closing'] for company in res_company.filtered(lambda c: c._is_accounting_unalterable()): new_sequence_number = company.l10n_fr_closing_sequence_id.next_by_id() values = self._compute_amounts(frequency, company) values['frequency'] = frequency values['company_id'] = company.id values['sequence_number'] = new_sequence_number account_closings |= account_closings.create(values) return account_closings
class AccountVoucherLine(models.Model): _name = 'account.voucher.line' _description = 'Voucher Lines' name = fields.Text(string='Description', required=True) sequence = fields.Integer( default=10, help="Gives the sequence of this line when displaying the voucher.") voucher_id = fields.Many2one('account.voucher', 'Voucher', required=1, ondelete='cascade') product_id = fields.Many2one('product.product', string='Product', ondelete='set null', index=True) account_id = fields.Many2one( 'account.account', string='Account', required=True, domain=[('deprecated', '=', False)], help="The income or expense account related to the selected product.") price_unit = fields.Float(string='Unit Price', required=True, digits=dp.get_precision('Product Price'), oldname='amount') price_subtotal = fields.Monetary(string='Amount', store=True, readonly=True, compute='_compute_subtotal') quantity = fields.Float(digits=dp.get_precision('Product Unit of Measure'), required=True, default=1) account_analytic_id = fields.Many2one('account.analytic.account', 'Analytic Account') company_id = fields.Many2one('res.company', related='voucher_id.company_id', string='Company', store=True, readonly=True) tax_ids = fields.Many2many('account.tax', string='Tax', help="Only for tax excluded from price") currency_id = fields.Many2one('res.currency', related='voucher_id.currency_id') branch_id = fields.Many2one('res.branch', related='voucher_id.branch_id', string='Branch', readonly=True, store=True) @api.one @api.depends('price_unit', 'tax_ids', 'quantity', 'product_id', 'voucher_id.currency_id') def _compute_subtotal(self): self.price_subtotal = self.quantity * self.price_unit if self.tax_ids: taxes = self.tax_ids.compute_all( self.price_unit, self.voucher_id.currency_id, self.quantity, product=self.product_id, partner=self.voucher_id.partner_id) self.price_subtotal = taxes['total_excluded'] @api.onchange('product_id', 'voucher_id', 'price_unit', 'company_id') def _onchange_line_details(self): if not self.voucher_id or not self.product_id or not self.voucher_id.partner_id: return onchange_res = self.product_id_change(self.product_id.id, self.voucher_id.partner_id.id, self.price_unit, self.company_id.id, self.voucher_id.currency_id.id, self.voucher_id.voucher_type) for fname, fvalue in onchange_res['value'].items(): setattr(self, fname, fvalue) def _get_account(self, product, fpos, type): accounts = product.product_tmpl_id.get_product_accounts(fpos) if type == 'sale': return accounts['income'] return accounts['expense'] @api.multi def product_id_change(self, product_id, partner_id=False, price_unit=False, company_id=None, currency_id=None, type=None): # TDE note: mix of old and new onchange badly written in 9, multi but does not use record set context = self._context company_id = company_id if company_id is not None else context.get( 'company_id', False) company = self.env['res.company'].browse(company_id) currency = self.env['res.currency'].browse(currency_id) if not partner_id: raise UserError(_("You must first select a partner!")) part = self.env['res.partner'].browse(partner_id) if part.lang: self = self.with_context(lang=part.lang) product = self.env['product.product'].browse(product_id) fpos = part.property_account_position_id account = self._get_account(product, fpos, type) values = { 'name': product.partner_ref, 'account_id': account.id, } if type == 'purchase': values['price_unit'] = price_unit or product.standard_price taxes = product.supplier_taxes_id or account.tax_ids if product.description_purchase: values['name'] += '\n' + product.description_purchase else: values['price_unit'] = price_unit or product.lst_price taxes = product.taxes_id or account.tax_ids if product.description_sale: values['name'] += '\n' + product.description_sale values['tax_ids'] = taxes.ids if company and currency: if company.currency_id != currency: if type == 'purchase': values['price_unit'] = price_unit or product.standard_price values['price_unit'] = values['price_unit'] * currency.rate return {'value': values, 'domain': {}}
class TaxAdjustments(models.TransientModel): _name = 'tax.adjustments.wizard' _description = 'Wizard for Tax Adjustments' @api.multi def _get_default_journal(self): return self.env['account.journal'].search([('type', '=', 'general')], limit=1).id reason = fields.Char(string='Justification', required=True) journal_id = fields.Many2one('account.journal', string='Journal', required=True, default=_get_default_journal, domain=[('type', '=', 'general')]) date = fields.Date(required=True, default=fields.Date.context_today) debit_account_id = fields.Many2one('account.account', string='Debit account', required=True, domain=[('deprecated', '=', False)]) credit_account_id = fields.Many2one('account.account', string='Credit account', required=True, domain=[('deprecated', '=', False)]) amount = fields.Monetary(currency_field='company_currency_id', required=True) company_currency_id = fields.Many2one( 'res.currency', readonly=True, default=lambda self: self.env.user.company_id.currency_id) tax_id = fields.Many2one('account.tax', string='Adjustment Tax', ondelete='restrict', domain=[('type_tax_use', '=', 'none'), ('tax_adjustment', '=', True)], required=True) @api.multi def _create_move(self): debit_vals = { 'name': self.reason, 'debit': self.amount, 'credit': 0.0, 'account_id': self.debit_account_id.id, 'tax_line_id': self.tax_id.id, } credit_vals = { 'name': self.reason, 'debit': 0.0, 'credit': self.amount, 'account_id': self.credit_account_id.id, 'tax_line_id': self.tax_id.id, } vals = { 'journal_id': self.journal_id.id, 'date': self.date, 'state': 'draft', 'line_ids': [(0, 0, debit_vals), (0, 0, credit_vals)] } move = self.env['account.move'].create(vals) move.post() return move.id @api.multi def create_move(self): #create the adjustment move move_id = self._create_move() #return an action showing the created move action = self.env.ref( self.env.context.get('action', 'account.action_move_line_form')) result = action.read()[0] result['views'] = [(False, 'form')] result['res_id'] = move_id return result
class SaleOrder(models.Model): _inherit = 'sale.order' amount_delivery = fields.Monetary(compute='_compute_amount_delivery', digits=0, string='Delivery Amount', help="The amount without tax.", store=True, track_visibility='always') has_delivery = fields.Boolean(compute='_compute_has_delivery', string='Has delivery', help="Has an order line set for delivery", store=True) website_order_line = fields.One2many( 'sale.order.line', 'order_id', string='Order Lines displayed on Website', readonly=True, domain=[('is_delivery', '=', False)], help= 'Order Lines to be displayed on the website. They should not be used for computation purpose.' ) @api.depends('order_line.price_unit', 'order_line.tax_id', 'order_line.discount', 'order_line.product_uom_qty') def _compute_amount_delivery(self): for order in self: if self.env.user.has_group('sale.group_show_price_subtotal'): order.amount_delivery = sum( order.order_line.filtered('is_delivery').mapped( 'price_subtotal')) else: order.amount_delivery = sum( order.order_line.filtered('is_delivery').mapped( 'price_total')) @api.depends('order_line.is_delivery') def _compute_has_delivery(self): for order in self: order.has_delivery = any(order.order_line.filtered('is_delivery')) def _check_carrier_quotation(self, force_carrier_id=None): self.ensure_one() DeliveryCarrier = self.env['delivery.carrier'] if self.only_services: self.write({'carrier_id': None}) self._remove_delivery_line() return True else: # attempt to use partner's preferred carrier if not force_carrier_id and self.partner_shipping_id.property_delivery_carrier_id: force_carrier_id = self.partner_shipping_id.property_delivery_carrier_id.id carrier = force_carrier_id and DeliveryCarrier.browse( force_carrier_id) or self.carrier_id available_carriers = self._get_delivery_methods() if carrier: if carrier not in available_carriers: carrier = DeliveryCarrier else: # set the forced carrier at the beginning of the list to be verfied first below available_carriers -= carrier available_carriers = carrier + available_carriers if force_carrier_id or not carrier or carrier not in available_carriers: for delivery in available_carriers: verified_carrier = delivery._match_address( self.partner_shipping_id) if verified_carrier: carrier = delivery break self.write({'carrier_id': carrier.id}) if carrier: self.get_delivery_price() if self.delivery_rating_success: self.set_delivery_line() else: self._remove_delivery_line() return bool(carrier) def _get_delivery_methods(self): address = self.partner_shipping_id website = self.env['website'].get_current_website() return self.env['delivery.carrier'].sudo().search([ ('website_published', '=', True), ('website_ids', 'in', website.id) ]).available_carriers(address) @api.multi def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs): """ Override to update carrier quotation if quantity changed """ self._remove_delivery_line() # When you update a cart, it is not enouf to remove the "delivery cost" line # The carrier might also be invalid, eg: if you bought things that are too heavy # -> this may cause a bug if you go to the checkout screen, choose a carrier, # then update your cart (the cart becomes uneditable) self.write({'carrier_id': False}) values = super(SaleOrder, self)._cart_update(product_id, line_id, add_qty, set_qty, **kwargs) return values
class LunchOrder(models.Model): """ A lunch order contains one or more lunch order line(s). It is associated to a user for a given date. When creating a lunch order, applicable lunch alerts are displayed. """ _name = 'lunch.order' _description = 'Lunch Order' _order = 'date desc' def _default_previous_order_ids(self): prev_order = self.env['lunch.order.line'].search( [('user_id', '=', self.env.uid), ('product_id.active', '!=', False)], limit=20, order='id desc') # If we return return prev_order.ids, we will have duplicates (identical orders). # Therefore, this following part removes duplicates based on product_id and note. return list({(order.product_id, order.note): order.id for order in prev_order}.values()) user_id = fields.Many2one('res.users', 'User', readonly=True, states={'new': [('readonly', False)]}, default=lambda self: self.env.uid) date = fields.Date('Date', required=True, readonly=True, states={'new': [('readonly', False)]}, default=fields.Date.context_today) order_line_ids = fields.One2many('lunch.order.line', 'order_id', 'Products', readonly=True, copy=True, states={ 'new': [('readonly', False)], False: [('readonly', False)] }) total = fields.Float(compute='_compute_total', string="Total", store=True) state = fields.Selection([('new', 'New'), ('confirmed', 'Received'), ('cancelled', 'Cancelled')], 'Status', readonly=True, index=True, copy=False, compute='_compute_order_state', store=True) alerts = fields.Text(compute='_compute_alerts_get', string="Alerts") company_id = fields.Many2one('res.company', related='user_id.company_id', store=True) currency_id = fields.Many2one('res.currency', related='company_id.currency_id', readonly=True, store=True) cash_move_balance = fields.Monetary(compute='_compute_cash_move_balance', multi='cash_move_balance') balance_visible = fields.Boolean(compute='_compute_cash_move_balance', multi='cash_move_balance') previous_order_ids = fields.Many2many('lunch.order.line', compute='_compute_previous_order') previous_order_widget = fields.Text(compute='_compute_previous_order') @api.one @api.depends('order_line_ids') def _compute_total(self): """ get and sum the order lines' price """ self.total = sum(orderline.price for orderline in self.order_line_ids) @api.multi def name_get(self): return [(order.id, '%s %s' % (_('Lunch Order'), '#%d' % order.id)) for order in self] @api.depends('state') def _compute_alerts_get(self): """ get the alerts to display on the order form """ alert_msg = [ alert.message for alert in self.env['lunch.alert'].search([]) if alert.display ] if self.state == 'new': self.alerts = alert_msg and '\n'.join(alert_msg) or False @api.multi @api.depends('user_id', 'state') def _compute_previous_order(self): self.ensure_one() self.previous_order_widget = json.dumps(False) prev_order = self.env['lunch.order.line'].search( [('user_id', '=', self.env.uid), ('product_id.active', '!=', False)], limit=20, order='date desc, id desc') # If we use prev_order.ids, we will have duplicates (identical orders). # Therefore, this following part removes duplicates based on product_id and note. self.previous_order_ids = list({(order.product_id, order.note): order.id for order in prev_order}.values()) if self.previous_order_ids: lunch_data = {} for line in self.previous_order_ids: lunch_data[line.id] = { 'line_id': line.id, 'product_id': line.product_id.id, 'product_name': line.product_id.name, 'supplier': line.supplier.name, 'note': line.note, 'price': line.price, 'date': line.date, 'currency_id': line.currency_id.id, } # sort the old lunch orders by (date, id) lunch_data = OrderedDict( sorted(lunch_data.items(), key=lambda t: (t[1]['date'], t[0]), reverse=True)) self.previous_order_widget = json.dumps(lunch_data) @api.one @api.depends('user_id') def _compute_cash_move_balance(self): domain = [('user_id', '=', self.user_id.id)] lunch_cash = self.env['lunch.cashmove'].read_group( domain, ['amount', 'user_id'], ['user_id']) if len(lunch_cash): self.cash_move_balance = lunch_cash[0]['amount'] self.balance_visible = (self.user_id == self.env.user) or self.user_has_groups( 'lunch.group_lunch_manager') @api.one @api.constrains('date') def _check_date(self): """ Prevents the user to create an order in the past """ date_order = datetime.datetime.strptime(self.date, '%Y-%m-%d') date_today = datetime.datetime.strptime( fields.Date.context_today(self), '%Y-%m-%d') if (date_order < date_today): raise ValidationError(_('The date of your order is in the past.')) @api.one @api.depends('order_line_ids.state') def _compute_order_state(self): """ Update the state of lunch.order based on its orderlines. Here is the logic: - if at least one order line is cancelled, the order is set as cancelled - if no line is cancelled but at least one line is not confirmed, the order is set as new - if all lines are confirmed, the order is set as confirmed """ if not self.order_line_ids: self.state = 'new' else: isConfirmed = True for orderline in self.order_line_ids: if orderline.state == 'cancelled': self.state = 'cancelled' return elif orderline.state == 'confirmed': continue else: isConfirmed = False if isConfirmed: self.state = 'confirmed' else: self.state = 'new' return
class AccountAnalyticLine(models.Model): _inherit = 'account.analytic.line' _description = 'Analytic Line' _order = 'date desc' amount = fields.Monetary(currency_field='company_currency_id') product_uom_id = fields.Many2one('product.uom', string='Unit of Measure') product_id = fields.Many2one('product.product', string='Product') general_account_id = fields.Many2one('account.account', string='Financial Account', ondelete='restrict', readonly=True, related='move_id.account_id', store=True, domain=[('deprecated', '=', False)]) move_id = fields.Many2one('account.move.line', string='Move Line', ondelete='cascade', index=True) code = fields.Char(size=8) ref = fields.Char(string='Ref.') company_currency_id = fields.Many2one( 'res.currency', related='company_id.currency_id', readonly=True, help='Utility field to express amount currency') currency_id = fields.Many2one( 'res.currency', related='move_id.currency_id', string='Account Currency', store=True, help="The related account currency if not equal to the company one.", readonly=True) amount_currency = fields.Monetary( related='move_id.amount_currency', store=True, help= "The amount expressed in the related account currency if not equal to the company one.", readonly=True) analytic_amount_currency = fields.Monetary( string='Amount Currency', compute="_get_analytic_amount_currency", help= "The amount expressed in the related account currency if not equal to the company one.", readonly=True) partner_id = fields.Many2one('res.partner', related='account_id.partner_id', string='Partner', store=True, readonly=True) def _get_analytic_amount_currency(self): for line in self: line.analytic_amount_currency = abs( line.amount_currency) * copysign(1, line.amount) @api.v8 @api.onchange('product_id', 'product_uom_id', 'unit_amount', 'currency_id') def on_change_unit_amount(self): if not self.product_id: return {} result = 0.0 prod_accounts = self.product_id.product_tmpl_id._get_product_accounts() unit = self.product_uom_id account = prod_accounts['expense'] if not unit or self.product_id.uom_po_id.category_id.id != unit.category_id.id: unit = self.product_id.uom_po_id # Compute based on pricetype amount_unit = self.product_id.price_compute( 'standard_price', uom=unit)[self.product_id.id] amount = amount_unit * self.unit_amount or 0.0 result = self.currency_id.round(amount) * -1 self.amount = result self.general_account_id = account self.product_uom_id = unit @api.model def view_header_get(self, view_id, view_type): context = (self._context or {}) header = False if context.get('account_id', False): analytic_account = self.env['account.analytic.account'].search( [('id', '=', context['account_id'])], limit=1) header = _('Entries: ') + (analytic_account.name or '') return header
class ProductWishlist(models.Model): _name = 'product.wishlist' _sql_constrains = [ ("session_or_partner_id", "CHECK(session IS NULL != partner_id IS NULL)", "Need a session or partner, but never both."), ("product_unique_session", "UNIQUE(product_id, session)", "Duplicated wishlisted product for this session."), ("product_unique_partner_id", "UNIQUE(product_id, partner_id)", "Duplicated wishlisted product for this partner."), ] partner_id = fields.Many2one('res.partner', string='Owner') session = fields.Char( help="Website session identifier where this product was wishlisted.") product_id = fields.Many2one('product.product', string='Product', required=True) currency_id = fields.Many2one('res.currency', related='pricelist_id.currency_id', readonly=True) pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', help='Pricelist when added') price = fields.Monetary( digits=0, currency_field='currency_id', string='Price', help='Price of the product when it has been added in the wishlist') price_new = fields.Float( compute='compute_new_price', string='Current price', help='Current price of this product, using same pricelist, ...') website_id = fields.Many2one('website', required=True) create_date = fields.Datetime('Added Date', readonly=True, required=True) active = fields.Boolean(default=True, required=True) @api.multi @api.depends('pricelist_id', 'currency_id', 'product_id') def compute_new_price(self): for wish in self: wish.price_new = wish.product_id.with_context( pricelist=wish.pricelist_id.id).website_price @api.model def current(self): """Get all wishlist items that belong to current user or session.""" return self.search([ "|", ("partner_id", "=", self.env.user.partner_id.id), "&", ("partner_id", "=", False), ("session", "=", self.env.user.current_session), ]) @api.model def _add_to_wishlist(self, pricelist_id, currency_id, website_id, price, product_id, partner_id=False, session=False): wish = self.env['product.wishlist'].create({ 'partner_id': partner_id, 'session': session, 'product_id': product_id, 'currency_id': currency_id, 'pricelist_id': pricelist_id, 'price': price, 'website_id': website_id, }) return wish @api.model def _join_current_user_and_session(self): """Assign all dangling session wishlisted products to user.""" session_wishes = self.search([ ("session", "=", self.env.user.current_session), ("partner_id", "=", False), ]) partner_wishes = self.search([ ("partner_id", "=", self.env.user.partner_id.id), ]) partner_products = partner_wishes.mapped("product_id") # Remove session products already present for the user duplicated_wishes = session_wishes.filtered( lambda wish: wish.product_id <= partner_products) session_wishes -= duplicated_wishes duplicated_wishes.unlink() # Assign the rest to the user session_wishes.write({ "partner_id": self.env.user.partner_id.id, "session": False, }) @api.model def _garbage_collector(self, *args, **kwargs): """Remove wishlists for unexisting sessions.""" self.search([ ("create_date", "<", fields.Datetime.to_string(datetime.now() - timedelta( weeks=kwargs.get('wishlist_week', 5)))), ("partner_id", "=", False), ]).unlink()
class AccountInvoice(models.Model): _inherit = "account.invoice" @api.multi @api.depends('discount_amount', 'discount_per', 'amount_untaxed') def _get_discount(self): total_discount = 0.0 for record in self: for invoice_line_id in record.invoice_line_ids: total_price = ( invoice_line_id.quantity * invoice_line_id.price_unit) total_discount += \ (total_price * invoice_line_id.discount) / 100 record.discount = record.currency_id.round(total_discount) @api.multi @api.depends('invoice_line_ids', 'discount_per', 'discount_amount') def _get_total_amount(self): for invoice_id in self: invoice_id.gross_amount = sum( [line_id.quantity * line_id.price_unit for line_id in invoice_id.invoice_line_ids]) discount_method = fields.Selection( [('fixed', 'Fixed'), ('per', 'Percentage')], string="Discount Method") discount_amount = fields.Float(string="Discount Amount") discount_per = fields.Float(string="Discount (%)") discount = fields.Monetary( string='Discount', readonly=True, compute='_get_discount', track_visibility='always') gross_amount = fields.Float(string="Gross Amount", compute='_get_total_amount', store=True) @api.multi def calculate_discount(self): self._check_constrains() for line in self.invoice_line_ids: line.write({'discount': 0.0}) # amount_untaxed = self.amount_untaxed gross_amount = self.gross_amount if self.discount_method == 'per': for line in self.invoice_line_ids: line.write({'discount': self.discount_per}) self._onchange_invoice_line_ids() else: for line in self.invoice_line_ids: discount_value_ratio = \ (self.discount_amount * line.price_subtotal) / \ gross_amount discount_per_ratio = \ (discount_value_ratio * 100) / line.price_subtotal line.write({'discount': discount_per_ratio}) self._onchange_invoice_line_ids() @api.constrains('discount_per', 'discount_amount', 'invoice_line_ids') def _check_constrains(self): self.onchange_discount_per() self.onchange_discount_amount() @api.onchange('discount_method') def onchange_discount_method(self): self.discount_amount = 0.0 self.discount_per = 0.0 if self.discount_method and not self.invoice_line_ids: raise Warning('No Invoice Line(s) were found!') @api.multi def get_maximum_per_amount(self): account_dis_config_obj = self.env['account.discount.config'] max_percentage = 0 max_amount = 0 check_group = False for groups_id in self.env.user.groups_id: account_dis_config_id = account_dis_config_obj.search( [('group_id', '=', groups_id.id)]) if account_dis_config_id: check_group = True if account_dis_config_id.percentage > max_percentage: max_percentage = account_dis_config_id.percentage if account_dis_config_id.fix_amount > max_amount: max_amount = account_dis_config_id.fix_amount return {'max_percentage': max_percentage, 'max_amount': max_amount, 'check_group': check_group} @api.onchange('discount_per') def onchange_discount_per(self): values = self.get_maximum_per_amount() if self.discount_method == 'per' and ( self.discount_per > 100 or self.discount_per < 0) \ and values.get('check_group', False): raise Warning(_("Percentage should be between 0% to 100%")) if self.discount_per > values.get('max_percentage', False) \ and values.get('check_group', False): raise Warning(_("You are not allowed to apply Discount Percentage " "(%s) more than configured Discount Percentage " "(%s) in configuration setting!") % ( formatLang(self.env, self.discount_per, digits=2), formatLang(self.env, values['max_percentage'], digits=2))) config_id = self.env[ 'res.config.settings'].search([], order='id desc', limit=1) if config_id and config_id.global_discount_invoice_apply: global_percentage = config_id.global_discount_percentage_invoice if global_percentage < self.discount_per: raise Warning(_("You are not allowed to apply Discount " "Percentage(%s) more than configured Discount" " Percentage (%s) in configuration setting!" ) % ( formatLang(self.env, self.discount_per, digits=2), formatLang(self.env, config_id.global_discount_percentage_invoice, digits=2))) @api.onchange('discount_amount') def onchange_discount_amount(self): values = self.get_maximum_per_amount() if self.discount < 0: raise Warning(_("Discount should be less than Gross Amount")) discount = self.discount or self.discount_amount if self.gross_amount and discount > self.gross_amount: raise Warning(_("Discount (%s) should be less than " "Gross Amount (%s).") % ( formatLang(self.env, discount, digits=2), formatLang(self.env, self.gross_amount, digits=2))) if self.discount > values.get('max_amount', False) \ and values.get('check_group', False): raise Warning(_("You're not allowed to apply this amount of " "discount as discount Amount (%s) is greater than" " assign Fix Amount (%s).") % ( formatLang(self.env, self.discount, digits=2), formatLang(self.env, values['max_amount'], digits=2))) config_id = self.env[ 'res.config.settings'].search([], order='id desc', limit=1) if config_id and config_id.global_discount_invoice_apply: fix_amount = config_id.global_discount_fix_invoice_amount if fix_amount < self.discount_amount: raise Warning(_("You're not allowed to apply this amount of" " discount as discount Amount (%s) is greater" " than Configuration Amount (%s).") % ( formatLang(self.env, self.discount, digits=2), formatLang(self.env, config_id.global_discount_fix_invoice_amount, digits=2)))
class AccountAnalyticAccount(models.Model): _name = 'account.analytic.account' _inherit = ['mail.thread', 'ir.branch.company.mixin'] _description = 'Analytic Account' _order = 'code, name asc' @api.multi def _compute_debit_credit_balance(self): analytic_line_obj = self.env['account.analytic.line'] domain = [('account_id', 'in', self.mapped('id'))] if self._context.get('from_date', False): domain.append(('date', '>=', self._context['from_date'])) if self._context.get('to_date', False): domain.append(('date', '<=', self._context['to_date'])) account_amounts = analytic_line_obj.search_read( domain, ['account_id', 'amount']) account_ids = set([line['account_id'][0] for line in account_amounts]) data_debit = {account_id: 0.0 for account_id in account_ids} data_credit = {account_id: 0.0 for account_id in account_ids} for account_amount in account_amounts: if account_amount['amount'] < 0.0: data_debit[account_amount['account_id'] [0]] += account_amount['amount'] else: data_credit[account_amount['account_id'] [0]] += account_amount['amount'] for account in self: account.debit = abs(data_debit.get(account.id, 0.0)) account.credit = data_credit.get(account.id, 0.0) account.balance = account.credit - account.debit name = fields.Char(string='Analytic Account', index=True, required=True, track_visibility='onchange') code = fields.Char(string='Reference', index=True, track_visibility='onchange') active = fields.Boolean( 'Active', help= "If the active field is set to False, it will allow you to hide the account without removing it.", default=True) tag_ids = fields.Many2many('account.analytic.tag', 'account_analytic_account_tag_rel', 'account_id', 'tag_id', string='Tags', copy=True) line_ids = fields.One2many('account.analytic.line', 'account_id', string="Analytic Lines") company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id) # use auto_join to speed up name_search call partner_id = fields.Many2one('res.partner', string='Customer', auto_join=True, track_visibility='onchange') balance = fields.Monetary(compute='_compute_debit_credit_balance', string='Balance') debit = fields.Monetary(compute='_compute_debit_credit_balance', string='Debit') credit = fields.Monetary(compute='_compute_debit_credit_balance', string='Credit') currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True) @api.multi def name_get(self): res = [] for analytic in self: name = analytic.name if analytic.code: name = '[' + analytic.code + '] ' + name if analytic.partner_id: name = name + ' - ' + analytic.partner_id.commercial_partner_id.name res.append((analytic.id, name)) return res @api.model def name_search(self, name='', args=None, operator='ilike', limit=100): if operator not in ('ilike', 'like', '=', '=like', '=ilike'): return super(AccountAnalyticAccount, self).name_search(name, args, operator, limit) args = args or [] domain = ['|', ('code', operator, name), ('name', operator, name)] partners = self.env['res.partner'].search([('name', operator, name)], limit=limit) if partners: domain = ['|'] + domain + [('partner_id', 'in', partners.ids)] recs = self.search(domain + args, limit=limit) return recs.name_get()
class account_abstract_payment(models.AbstractModel): _name = "account.abstract.payment" _description = "Contains the logic shared between models which allows to register payments" payment_type = fields.Selection([('outbound', 'Send Money'), ('inbound', 'Receive Money')], string='Payment Type', required=True) payment_method_id = fields.Many2one('account.payment.method', string='Payment Method Type', required=True, oldname="payment_method", help="Manual: Get paid by cash, check or any other method outside of actpy.\n"\ "Electronic: Get paid automatically through a payment acquirer by requesting a transaction on a card saved by the customer when buying or subscribing online (payment token).\n"\ "Check: Pay bill by check and print it from actpy.\n"\ "Batch Deposit: Encase several customer checks at once by generating a batch deposit to submit to your bank. When encoding the bank statement in actpy, you are suggested to reconcile the transaction with the batch deposit.To enable batch deposit,module account_batch_deposit must be installed.\n"\ "SEPA Credit Transfer: Pay bill from a SEPA Credit Transfer file you submit to your bank. To enable sepa credit transfer, module account_sepa must be installed ") payment_method_code = fields.Char( related='payment_method_id.code', help= "Technical field used to adapt the interface to the payment type selected.", readonly=True) partner_type = fields.Selection([('customer', 'Customer'), ('supplier', 'Vendor')]) partner_id = fields.Many2one('res.partner', string='Partner') amount = fields.Monetary(string='Payment Amount', required=True) currency_id = fields.Many2one( 'res.currency', string='Currency', required=True, default=lambda self: self.env.user.company_id.currency_id) payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True, copy=False) communication = fields.Char(string='Memo') journal_id = fields.Many2one('account.journal', string='Payment Journal', required=True, domain=[('type', 'in', ('bank', 'cash'))]) company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True) branch_id = fields.Many2one(related='journal_id.branch_id', string='Branch', readonly=True) hide_payment_method = fields.Boolean( compute='_compute_hide_payment_method', help= "Technical field used to hide the payment method if the selected journal has only one available which is 'manual'" ) @api.one @api.constrains('amount') def _check_amount(self): if self.amount < 0: raise ValidationError(_('The payment amount cannot be negative.')) @api.multi @api.depends('payment_type', 'journal_id') def _compute_hide_payment_method(self): for payment in self: if not payment.journal_id: payment.hide_payment_method = True continue journal_payment_methods = payment.payment_type == 'inbound'\ and payment.journal_id.inbound_payment_method_ids\ or payment.journal_id.outbound_payment_method_ids payment.hide_payment_method = len( journal_payment_methods ) == 1 and journal_payment_methods[0].code == 'manual' @api.onchange('journal_id') def _onchange_journal(self): if self.journal_id: self.currency_id = self.journal_id.currency_id or self.company_id.currency_id # Set default payment method (we consider the first to be the default one) payment_methods = self.payment_type == 'inbound' and self.journal_id.inbound_payment_method_ids or self.journal_id.outbound_payment_method_ids self.payment_method_id = payment_methods and payment_methods[ 0] or False # Set payment method domain (restrict to methods enabled for the journal and to selected payment type) payment_type = self.payment_type in ( 'outbound', 'transfer') and 'outbound' or 'inbound' return { 'domain': { 'payment_method_id': [('payment_type', '=', payment_type), ('id', 'in', payment_methods.ids)] } } return {} @api.model def _compute_total_invoices_amount(self): """ Compute the sum of the residual of invoices, expressed in the payment currency """ payment_currency = self.currency_id or self.journal_id.currency_id or self.journal_id.company_id.currency_id or self.env.user.company_id.currency_id total = 0 for inv in self.invoice_ids: if inv.currency_id == payment_currency: total += inv.residual_signed else: total += inv.company_currency_id.with_context( date=self.payment_date).compute( inv.residual_company_signed, payment_currency) return abs(total)
class AccountVoucher(models.Model): _name = 'account.voucher' _description = 'Accounting Voucher' _inherit = ['mail.thread'] _order = "date desc, id desc" @api.model def _default_journal(self): voucher_type = self._context.get('voucher_type', 'sale') company_id = self._context.get('company_id', self.env.user.company_id.id) domain = [ ('type', '=', voucher_type), ('company_id', '=', company_id), ] return self.env['account.journal'].search(domain, limit=1) voucher_type = fields.Selection([('sale', 'Sale'), ('purchase', 'Purchase')], string='Type', readonly=True, states={'draft': [('readonly', False)]}, oldname="type") name = fields.Char('Payment Reference', readonly=True, states={'draft': [('readonly', False)]}, default='') date = fields.Date("Bill Date", readonly=True, index=True, states={'draft': [('readonly', False)]}, copy=False, default=fields.Date.context_today) account_date = fields.Date("Accounting Date", readonly=True, index=True, states={'draft': [('readonly', False)]}, help="Effective date for accounting entries", copy=False, default=fields.Date.context_today) journal_id = fields.Many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft': [('readonly', False)]}, default=_default_journal) payment_journal_id = fields.Many2one( 'account.journal', string='Payment Method', readonly=True, store=False, states={'draft': [('readonly', False)]}, domain="[('type', 'in', ['cash', 'bank'])]", compute='_compute_payment_journal_id', inverse='_inverse_payment_journal_id') account_id = fields.Many2one( 'account.account', 'Account', required=True, readonly=True, states={'draft': [('readonly', False)]}, domain= "[('deprecated', '=', False), ('internal_type','=', (pay_now == 'pay_now' and 'liquidity' or voucher_type == 'purchase' and 'payable' or 'receivable'))]" ) line_ids = fields.One2many('account.voucher.line', 'voucher_id', 'Voucher Lines', readonly=True, copy=True, states={'draft': [('readonly', False)]}) narration = fields.Text('Notes', readonly=True, states={'draft': [('readonly', False)]}) currency_id = fields.Many2one('res.currency', compute='_get_journal_currency', string='Currency', readonly=True, required=True, default=lambda self: self._get_currency()) company_id = fields.Many2one('res.company', 'Company', store=True, required=True, readonly=True, states={'draft': [('readonly', False)]}, related='journal_id.company_id', default=lambda self: self._get_company()) state = fields.Selection( [('draft', 'Draft'), ('cancel', 'Cancelled'), ('proforma', 'Pro-forma'), ('posted', 'Posted')], 'Status', readonly=True, track_visibility='onchange', copy=False, default='draft', help= " * The 'Draft' status is used when a user is encoding a new and unconfirmed Voucher.\n" " * The 'Pro-forma' status is used when the voucher does not have a voucher number.\n" " * The 'Posted' status is used when user create voucher,a voucher number is generated and voucher entries are created in account.\n" " * The 'Cancelled' status is used when user cancel voucher.") reference = fields.Char('Bill Reference', readonly=True, states={'draft': [('readonly', False)]}, help="The partner reference of this document.", copy=False) amount = fields.Monetary(string='Total', store=True, readonly=True, compute='_compute_total') tax_amount = fields.Monetary(readonly=True, store=True, compute='_compute_total') tax_correction = fields.Monetary( readonly=True, states={'draft': [('readonly', False)]}, help= 'In case we have a rounding problem in the tax, use this field to correct it' ) number = fields.Char(readonly=True, copy=False) move_id = fields.Many2one('account.move', 'Journal Entry', copy=False) partner_id = fields.Many2one('res.partner', 'Partner', change_default=1, readonly=True, states={'draft': [('readonly', False)]}) paid = fields.Boolean(compute='_check_paid', help="The Voucher has been totally paid.") pay_now = fields.Selection([ ('pay_now', 'Pay Directly'), ('pay_later', 'Pay Later'), ], 'Payment', index=True, readonly=True, states={'draft': [('readonly', False)]}, default='pay_later') date_due = fields.Date('Due Date', readonly=True, index=True, states={'draft': [('readonly', False)]}) branch_id = fields.Many2one( 'res.branch', 'Branch', ondelete="restrict", default=lambda self: self.env['res.users']._get_default_branch()) @api.constrains('company_id', 'branch_id') def _check_company_branch(self): for record in self: if record.branch_id and record.company_id != record.branch_id.company_id: raise ValidationError( _('Configuration Error of Company:\n' 'The Company (%s) in the voucher and ' 'the Company (%s) of Branch must ' 'be the same company!') % (record.company_id.name, record.branch_id.company_id.name)) @api.one @api.depends('move_id.line_ids.reconciled', 'move_id.line_ids.account_id.internal_type') def _check_paid(self): self.paid = any([((line.account_id.internal_type, 'in', ('receivable', 'payable')) and line.reconciled) for line in self.move_id.line_ids]) @api.model def _get_currency(self): journal = self.env['account.journal'].browse( self.env.context.get('default_journal_id', False)) if journal.currency_id: return journal.currency_id.id return self.env.user.company_id.currency_id.id @api.model def _get_company(self): return self._context.get('company_id', self.env.user.company_id.id) @api.multi @api.depends('name', 'number') def name_get(self): return [(r.id, (r.number or _('Voucher'))) for r in self] @api.one @api.depends('journal_id', 'company_id') def _get_journal_currency(self): self.currency_id = self.journal_id.currency_id.id or self.company_id.currency_id.id @api.depends('company_id', 'pay_now', 'account_id') def _compute_payment_journal_id(self): for voucher in self: if voucher.pay_now != 'pay_now': continue domain = [ ('type', 'in', ('bank', 'cash')), ('company_id', '=', voucher.company_id.id), ] if voucher.account_id and voucher.account_id.internal_type == 'liquidity': field = 'default_debit_account_id' if voucher.voucher_type == 'sale' else 'default_credit_account_id' domain.append((field, '=', voucher.account_id.id)) voucher.payment_journal_id = self.env['account.journal'].search( domain, limit=1) def _inverse_payment_journal_id(self): for voucher in self: if voucher.pay_now != 'pay_now': continue if voucher.voucher_type == 'sale': voucher.account_id = voucher.payment_journal_id.default_debit_account_id else: voucher.account_id = voucher.payment_journal_id.default_credit_account_id @api.multi @api.depends('tax_correction', 'line_ids.price_subtotal') def _compute_total(self): for voucher in self: total = 0 tax_amount = 0 for line in voucher.line_ids: tax_info = line.tax_ids.compute_all(line.price_unit, voucher.currency_id, line.quantity, line.product_id, voucher.partner_id) total += tax_info.get('total_included', 0.0) tax_amount += sum([ t.get('amount', 0.0) for t in tax_info.get('taxes', False) ]) voucher.amount = total + voucher.tax_correction voucher.tax_amount = tax_amount @api.one @api.depends('account_pay_now_id', 'account_pay_later_id', 'pay_now') def _get_account(self): self.account_id = self.account_pay_now_id if self.pay_now == 'pay_now' else self.account_pay_later_id @api.onchange('date') def onchange_date(self): self.account_date = self.date @api.onchange('partner_id', 'pay_now') def onchange_partner_id(self): pay_journal_domain = [('type', 'in', ['cash', 'bank'])] if self.pay_now != 'pay_now': if self.partner_id: self.account_id = self.partner_id.property_account_receivable_id \ if self.voucher_type == 'sale' else self.partner_id.property_account_payable_id else: account_type = self.voucher_type == 'purchase' and 'payable' or 'receivable' domain = [('deprecated', '=', False), ('internal_type', '=', account_type)] self.account_id = self.env['account.account'].search(domain, limit=1) else: if self.voucher_type == 'purchase': pay_journal_domain.append( ('outbound_payment_method_ids', '!=', False)) else: pay_journal_domain.append( ('inbound_payment_method_ids', '!=', False)) return {'domain': {'payment_journal_id': pay_journal_domain}} @api.multi def proforma_voucher(self): self.action_move_line_create() @api.multi def action_cancel_draft(self): self.write({'state': 'draft'}) @api.multi def cancel_voucher(self): for voucher in self: voucher.move_id.button_cancel() voucher.move_id.unlink() self.write({'state': 'cancel', 'move_id': False}) @api.multi def unlink(self): for voucher in self: if voucher.state not in ('draft', 'cancel'): raise UserError( _('Cannot delete voucher(s) which are already opened or paid.' )) return super(AccountVoucher, self).unlink() @api.multi def first_move_line_get(self, move_id, company_currency, current_currency): debit = credit = 0.0 if self.voucher_type == 'purchase': credit = self._convert_amount(self.amount) elif self.voucher_type == 'sale': debit = self._convert_amount(self.amount) if debit < 0.0: debit = 0.0 if credit < 0.0: credit = 0.0 sign = debit - credit < 0 and -1 or 1 #set the first line of the voucher move_line = { 'name': self.name or '/', 'debit': debit, 'credit': credit, 'account_id': self.account_id.id, 'move_id': move_id, 'journal_id': self.journal_id.id, 'partner_id': self.partner_id.commercial_partner_id.id, 'currency_id': company_currency != current_currency and current_currency or False, 'amount_currency': ( sign * abs(self.amount) # amount < 0 for refunds if company_currency != current_currency else 0.0), 'date': self.account_date, 'date_maturity': self.date_due, 'payment_id': self._context.get('payment_id'), 'branch_id': self.branch_id.id, } return move_line @api.multi def account_move_get(self): if self.number: name = self.number elif self.journal_id.sequence_id: if not self.journal_id.sequence_id.active: raise UserError( _('Please activate the sequence of selected journal !')) name = self.journal_id.sequence_id.with_context( ir_sequence_date=self.date).next_by_id() else: raise UserError(_('Please define a sequence on the journal.')) move = { 'name': name, 'journal_id': self.journal_id.id, 'narration': self.narration, 'date': self.account_date, 'ref': self.reference, 'branch_id': self.branch_id.id } return move @api.multi def _convert_amount(self, amount): ''' This function convert the amount given in company currency. It takes either the rate in the voucher (if the payment_rate_currency_id is relevant) either the rate encoded in the system. :param amount: float. The amount to convert :param voucher: id of the voucher on which we want the conversion :param context: to context to use for the conversion. It may contain the key 'date' set to the voucher date field in order to select the good rate to use. :return: the amount in the currency of the voucher's company :rtype: float ''' for voucher in self: return voucher.currency_id.compute(amount, voucher.company_id.currency_id) @api.multi def voucher_pay_now_payment_create(self): if self.voucher_type == 'sale': payment_methods = self.journal_id.inbound_payment_method_ids payment_type = 'inbound' partner_type = 'customer' sequence_code = 'account.payment.customer.invoice' else: payment_methods = self.journal_id.outbound_payment_method_ids payment_type = 'outbound' partner_type = 'supplier' sequence_code = 'account.payment.supplier.invoice' name = self.env['ir.sequence'].with_context( ir_sequence_date=self.date).next_by_code(sequence_code) return { 'name': name, 'payment_type': payment_type, 'payment_method_id': payment_methods and payment_methods[0].id or False, 'partner_type': partner_type, 'partner_id': self.partner_id.commercial_partner_id.id, 'amount': self.amount, 'currency_id': self.currency_id.id, 'payment_date': self.date, 'journal_id': self.payment_journal_id.id, 'company_id': self.company_id.id, 'communication': self.name, 'state': 'reconciled', } @api.multi def voucher_move_line_create(self, line_total, move_id, company_currency, current_currency): ''' Create one account move line, on the given account move, per voucher line where amount is not 0.0. It returns Tuple with tot_line what is total of difference between debit and credit and a list of lists with ids to be reconciled with this format (total_deb_cred,list_of_lists). :param voucher_id: Voucher id what we are working with :param line_total: Amount of the first line, which correspond to the amount we should totally split among all voucher lines. :param move_id: Account move wher those lines will be joined. :param company_currency: id of currency of the company to which the voucher belong :param current_currency: id of currency of the voucher :return: Tuple build as (remaining amount not allocated on voucher lines, list of account_move_line created in this method) :rtype: tuple(float, list of int) ''' for line in self.line_ids: #create one move line per voucher line where amount is not 0.0 if not line.price_subtotal: continue # convert the amount set on the voucher line into the currency of the voucher's company # this calls res_curreny.compute() with the right context, # so that it will take either the rate on the voucher if it is relevant or will use the default behaviour amount = self._convert_amount(line.price_unit * line.quantity) move_line = { 'journal_id': self.journal_id.id, 'name': line.name or '/', 'account_id': line.account_id.id, 'move_id': move_id, 'partner_id': self.partner_id.commercial_partner_id.id, 'analytic_account_id': line.account_analytic_id and line.account_analytic_id.id or False, 'quantity': 1, 'credit': abs(amount) if self.voucher_type == 'sale' else 0.0, 'debit': abs(amount) if self.voucher_type == 'purchase' else 0.0, 'date': self.account_date, 'tax_ids': [(4, t.id) for t in line.tax_ids], 'amount_currency': line.price_subtotal if current_currency != company_currency else 0.0, 'currency_id': company_currency != current_currency and current_currency or False, 'payment_id': self._context.get('payment_id'), } self.env['account.move.line'].with_context( apply_taxes=True).create(move_line) return line_total @api.multi def action_move_line_create(self): ''' Confirm the vouchers given in ids and create the journal entries for each of them ''' for voucher in self: local_context = dict( self._context, force_company=voucher.journal_id.company_id.id) if voucher.move_id: continue company_currency = voucher.journal_id.company_id.currency_id.id current_currency = voucher.currency_id.id or company_currency # we select the context to use accordingly if it's a multicurrency case or not # But for the operations made by _convert_amount, we always need to give the date in the context ctx = local_context.copy() ctx['date'] = voucher.account_date ctx['check_move_validity'] = False # Create a payment to allow the reconciliation when pay_now = 'pay_now'. if self.pay_now == 'pay_now' and self.amount > 0: ctx['payment_id'] = self.env['account.payment'].create( self.voucher_pay_now_payment_create()).id # Create the account move record. move = self.env['account.move'].create(voucher.account_move_get()) # Get the name of the account_move just created # Create the first line of the voucher move_line = self.env['account.move.line'].with_context(ctx).create( voucher.with_context(ctx).first_move_line_get( move.id, company_currency, current_currency)) line_total = move_line.debit - move_line.credit if voucher.voucher_type == 'sale': line_total = line_total - voucher._convert_amount( voucher.tax_amount) elif voucher.voucher_type == 'purchase': line_total = line_total + voucher._convert_amount( voucher.tax_amount) # Create one move line per voucher line where amount is not 0.0 line_total = voucher.with_context(ctx).voucher_move_line_create( line_total, move.id, company_currency, current_currency) # Add tax correction to move line if any tax correction specified if voucher.tax_correction != 0.0: tax_move_line = self.env['account.move.line'].search( [('move_id', '=', move.id), ('tax_line_id', '!=', False)], limit=1) if len(tax_move_line): tax_move_line.write({ 'debit': tax_move_line.debit + voucher.tax_correction if tax_move_line.debit > 0 else 0, 'credit': tax_move_line.credit + voucher.tax_correction if tax_move_line.credit > 0 else 0 }) # We post the voucher. voucher.write({ 'move_id': move.id, 'state': 'posted', 'number': move.name }) move.post() return True @api.multi def _track_subtype(self, init_values): if 'state' in init_values: return 'account_voucher.mt_voucher_state_change' return super(AccountVoucher, self)._track_subtype(init_values)
class account_payment(models.Model): _name = "account.payment" _inherit = ['mail.thread', 'account.abstract.payment'] _description = "Payments" _order = "payment_date desc, name desc" @api.one @api.depends('invoice_ids') def _get_has_invoices(self): self.has_invoices = bool(self.invoice_ids) @api.multi @api.depends('move_line_ids.reconciled') def _get_move_reconciled(self): for payment in self: rec = True for aml in payment.move_line_ids.filtered( lambda x: x.account_id.reconcile): if not aml.reconciled: rec = False payment.move_reconciled = rec @api.one @api.depends('invoice_ids', 'amount', 'payment_date', 'currency_id') def _compute_payment_difference(self): if len(self.invoice_ids) == 0: return if self.invoice_ids[0].type in ['in_invoice', 'out_refund']: self.payment_difference = self.amount - self._compute_total_invoices_amount( ) else: self.payment_difference = self._compute_total_invoices_amount( ) - self.amount @api.depends('journal_id') def _compute_branch(self): for payment in self: if payment.journal_id: payment.branch_id = \ payment.journal_id.branch_id company_id = fields.Many2one(store=True) name = fields.Char( readonly=True, copy=False, default="Draft Payment") # The name is attributed upon post() state = fields.Selection([('draft', 'Draft'), ('posted', 'Posted'), ('sent', 'Sent'), ('reconciled', 'Reconciled'), ('cancelled', 'Cancelled')], readonly=True, default='draft', copy=False, string="Status") payment_type = fields.Selection(selection_add=[('transfer', 'Internal Transfer')]) payment_reference = fields.Char( copy=False, readonly=True, help= "Reference of the document used to issue this payment. Eg. check number, file name, etc." ) move_name = fields.Char( string='Journal Entry Name', readonly=True, default=False, copy=False, help= "Technical field holding the number given to the journal entry, automatically set when the statement line is reconciled then stored to set the same number again if the line is cancelled, set to draft and re-processed again." ) # Money flows from the journal_id's default_debit_account_id or default_credit_account_id to the destination_account_id destination_account_id = fields.Many2one( 'account.account', compute='_compute_destination_account_id', readonly=True) # For money transfer, money goes from journal_id to a transfer account, then from the transfer account to destination_journal_id destination_journal_id = fields.Many2one('account.journal', string='Transfer To', domain=[('type', 'in', ('bank', 'cash'))]) invoice_ids = fields.Many2many('account.invoice', 'account_invoice_payment_rel', 'payment_id', 'invoice_id', string="Invoices", copy=False, readonly=True) has_invoices = fields.Boolean( compute="_get_has_invoices", help="Technical field used for usability purposes") payment_difference = fields.Monetary(compute='_compute_payment_difference', readonly=True) payment_difference_handling = fields.Selection( [('open', 'Keep open'), ('reconcile', 'Mark invoice as fully paid')], default='open', string="Payment Difference", copy=False) writeoff_account_id = fields.Many2one('account.account', string="Difference Account", domain=[('deprecated', '=', False)], copy=False) writeoff_label = fields.Char( string='Journal Item Label', help= 'Change label of the counterpart that will hold the payment difference', default='Write-Off') # FIXME: ondelete='restrict' not working (eg. cancel a bank statement reconciliation with a payment) move_line_ids = fields.One2many('account.move.line', 'payment_id', readonly=True, copy=False, ondelete='restrict') move_reconciled = fields.Boolean(compute="_get_move_reconciled", readonly=True) branch_id = fields.Many2one('res.branch', 'Branch', compute='_compute_branch', readonly=True, store=True) def open_payment_matching_screen(self): # Open reconciliation view for customers/suppliers move_line_id = False for move_line in self.move_line_ids: if move_line.account_id.reconcile: move_line_id = move_line.id break action_context = { 'company_ids': [self.company_id.id], 'partner_ids': [self.partner_id.commercial_partner_id.id] } if self.partner_type == 'customer': action_context.update({'mode': 'customers'}) elif self.partner_type == 'supplier': action_context.update({'mode': 'suppliers'}) if move_line_id: action_context.update({'move_line_id': move_line_id}) return { 'type': 'ir.actions.client', 'tag': 'manual_reconciliation_view', 'context': action_context, } def _compute_journal_domain_and_types(self): journal_type = ['bank', 'cash'] domain = [] if self.currency_id.is_zero(self.amount) and self.has_invoices: # In case of payment with 0 amount, allow to select a journal of type 'general' like # 'Miscellaneous Operations' and set this journal by default. journal_type = ['general'] self.payment_difference_handling = 'reconcile' else: if self.payment_type == 'inbound': domain.append(('at_least_one_inbound', '=', True)) elif self.payment_type == 'outbound': domain.append(('at_least_one_outbound', '=', True)) return {'domain': domain, 'journal_types': set(journal_type)} @api.onchange('amount', 'currency_id') def _onchange_amount(self): jrnl_filters = self._compute_journal_domain_and_types() journal_types = jrnl_filters['journal_types'] domain_on_types = [('type', 'in', list(journal_types))] journal_domain = jrnl_filters['domain'] + domain_on_types default_journal_id = self.env.context.get('default_journal_id') if not default_journal_id: if self.journal_id.type not in journal_types: self.journal_id = self.env['account.journal'].search( domain_on_types, limit=1) else: journal_domain = journal_domain.append( ('id', '=', default_journal_id)) return {'domain': {'journal_id': journal_domain}} @api.one @api.depends('invoice_ids', 'payment_type', 'partner_type', 'partner_id') def _compute_destination_account_id(self): if self.invoice_ids: self.destination_account_id = self.invoice_ids[0].account_id.id elif self.payment_type == 'transfer': if not self.company_id.transfer_account_id.id: raise UserError( _('Transfer account not defined on the company.')) self.destination_account_id = self.company_id.transfer_account_id.id elif self.partner_id: if self.partner_type == 'customer': self.destination_account_id = self.partner_id.property_account_receivable_id.id else: self.destination_account_id = self.partner_id.property_account_payable_id.id @api.onchange('partner_type') def _onchange_partner_type(self): # Set partner_id domain if self.partner_type: return {'domain': {'partner_id': [(self.partner_type, '=', True)]}} @api.onchange('payment_type') def _onchange_payment_type(self): if not self.invoice_ids: # Set default partner type for the payment type if self.payment_type == 'inbound': self.partner_type = 'customer' elif self.payment_type == 'outbound': self.partner_type = 'supplier' else: self.partner_type = False # Set payment method domain res = self._onchange_journal() if not res.get('domain', {}): res['domain'] = {} jrnl_filters = self._compute_journal_domain_and_types() journal_types = jrnl_filters['journal_types'] journal_types.update(['bank', 'cash']) res['domain']['journal_id'] = jrnl_filters['domain'] + [ ('type', 'in', list(journal_types)) ] return res @api.model def default_get(self, fields): rec = super(account_payment, self).default_get(fields) invoice_defaults = self.resolve_2many_commands('invoice_ids', rec.get('invoice_ids')) if invoice_defaults and len(invoice_defaults) == 1: invoice = invoice_defaults[0] rec['communication'] = invoice['reference'] or invoice[ 'name'] or invoice['number'] rec['currency_id'] = invoice['currency_id'][0] rec['payment_type'] = invoice['type'] in ( 'out_invoice', 'in_refund') and 'inbound' or 'outbound' rec['partner_type'] = MAP_INVOICE_TYPE_PARTNER_TYPE[ invoice['type']] rec['partner_id'] = invoice['partner_id'][0] rec['amount'] = invoice['residual'] return rec @api.multi def button_journal_entries(self): return { 'name': _('Journal Items'), 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.move.line', 'view_id': False, 'type': 'ir.actions.act_window', 'domain': [('payment_id', 'in', self.ids)], } @api.multi def button_invoices(self): return { 'name': _('Paid Invoices'), 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.invoice', 'view_id': False, 'type': 'ir.actions.act_window', 'domain': [('id', 'in', [x.id for x in self.invoice_ids])], } @api.multi def button_dummy(self): return True @api.multi def unreconcile(self): """ Set back the payments in 'posted' or 'sent' state, without deleting the journal entries. Called when cancelling a bank statement line linked to a pre-registered payment. """ for payment in self: if payment.payment_reference: payment.write({'state': 'sent'}) else: payment.write({'state': 'posted'}) @api.multi def cancel(self): for rec in self: for move in rec.move_line_ids.mapped('move_id'): if rec.invoice_ids: move.line_ids.remove_move_reconcile() move.button_cancel() move.unlink() rec.state = 'cancelled' @api.multi def unlink(self): if any(bool(rec.move_line_ids) for rec in self): raise UserError( _("You can not delete a payment that is already posted")) if any(rec.move_name for rec in self): raise UserError( _('It is not allowed to delete a payment that already created a journal entry since it would create a gap in the numbering. You should create the journal entry again and cancel it thanks to a regular revert.' )) return super(account_payment, self).unlink() @api.multi def post(self): """ Create the journal items for the payment and update the payment's state to 'posted'. A journal entry is created containing an item in the source liquidity account (selected journal's default_debit or default_credit) and another in the destination reconciliable account (see _compute_destination_account_id). If invoice_ids is not empty, there will be one reconciliable move line per invoice to reconcile with. If the payment is a transfer, a second journal entry is created in the destination journal to receive money from the transfer account. """ for rec in self: if rec.state != 'draft': raise UserError(_("Only a draft payment can be posted.")) if any(inv.state != 'open' for inv in rec.invoice_ids): raise ValidationError( _("The payment cannot be processed because the invoice is not open!" )) # Use the right sequence to set the name if rec.payment_type == 'transfer': sequence_code = 'account.payment.transfer' else: if rec.partner_type == 'customer': if rec.payment_type == 'inbound': sequence_code = 'account.payment.customer.invoice' if rec.payment_type == 'outbound': sequence_code = 'account.payment.customer.refund' if rec.partner_type == 'supplier': if rec.payment_type == 'inbound': sequence_code = 'account.payment.supplier.refund' if rec.payment_type == 'outbound': sequence_code = 'account.payment.supplier.invoice' rec.name = self.env['ir.sequence'].with_context( ir_sequence_date=rec.payment_date).next_by_code(sequence_code) if not rec.name and rec.payment_type != 'transfer': raise UserError( _("You have to define a sequence for %s in your company.") % (sequence_code, )) # Create the journal entry amount = rec.amount * (rec.payment_type in ('outbound', 'transfer') and 1 or -1) move = rec._create_payment_entry(amount) # In case of a transfer, the first journal entry created debited the source liquidity account and credited # the transfer account. Now we debit the transfer account and credit the destination liquidity account. if rec.payment_type == 'transfer': transfer_credit_aml = move.line_ids.filtered( lambda r: r.account_id == rec.company_id. transfer_account_id) transfer_debit_aml = rec._create_transfer_entry(amount) (transfer_credit_aml + transfer_debit_aml).reconcile() rec.write({'state': 'posted', 'move_name': move.name}) @api.multi def action_draft(self): return self.write({'state': 'draft'}) def action_validate_invoice_payment(self): """ Posts a payment used to pay an invoice. This function only posts the payment by default but can be overridden to apply specific post or pre-processing. It is called by the "validate" button of the popup window triggered on invoice form by the "Register Payment" button. """ if any(len(record.invoice_ids) != 1 for record in self): # For multiple invoices, there is account.register.payments wizard raise UserError( _("This method should only be called to process a single invoice's payment." )) return self.post() def _create_payment_entry(self, amount): """ Create a journal entry corresponding to a payment, if the payment references invoice(s) they are reconciled. Return the journal entry. """ aml_obj = self.env['account.move.line'].with_context( check_move_validity=False) invoice_currency = False if self.invoice_ids and all([ x.currency_id == self.invoice_ids[0].currency_id for x in self.invoice_ids ]): #if all the invoices selected share the same currency, record the paiement in that currency too invoice_currency = self.invoice_ids[0].currency_id debit, credit, amount_currency, currency_id = aml_obj.with_context( date=self.payment_date).compute_amount_fields( amount, self.currency_id, self.company_id.currency_id, invoice_currency) move = self.env['account.move'].create(self._get_move_vals()) #Write line corresponding to invoice payment counterpart_aml_dict = self._get_shared_move_line_vals( debit, credit, amount_currency, move.id, False) counterpart_aml_dict.update( self._get_counterpart_move_line_vals(self.invoice_ids)) counterpart_aml_dict.update({'currency_id': currency_id}) counterpart_aml = aml_obj.create(counterpart_aml_dict) #Reconcile with the invoices if self.payment_difference_handling == 'reconcile' and self.payment_difference: writeoff_line = self._get_shared_move_line_vals( 0, 0, 0, move.id, False) amount_currency_wo, currency_id = aml_obj.with_context( date=self.payment_date).compute_amount_fields( self.payment_difference, self.currency_id, self.company_id.currency_id, invoice_currency)[2:] # the writeoff debit and credit must be computed from the invoice residual in company currency # minus the payment amount in company currency, and not from the payment difference in the payment currency # to avoid loss of precision during the currency rate computations. See revision 20935462a0cabeb45480ce70114ff2f4e91eaf79 for a detailed example. total_residual_company_signed = sum( invoice.residual_company_signed for invoice in self.invoice_ids) total_payment_company_signed = self.currency_id.with_context( date=self.payment_date).compute(self.amount, self.company_id.currency_id) if self.invoice_ids[0].type in ['in_invoice', 'out_refund']: amount_wo = total_payment_company_signed - total_residual_company_signed else: amount_wo = total_residual_company_signed - total_payment_company_signed # Align the sign of the secondary currency writeoff amount with the sign of the writeoff # amount in the company currency if amount_wo > 0: debit_wo = amount_wo credit_wo = 0.0 amount_currency_wo = abs(amount_currency_wo) else: debit_wo = 0.0 credit_wo = -amount_wo amount_currency_wo = -abs(amount_currency_wo) writeoff_line['name'] = self.writeoff_label writeoff_line['account_id'] = self.writeoff_account_id.id writeoff_line['debit'] = debit_wo writeoff_line['credit'] = credit_wo writeoff_line['amount_currency'] = amount_currency_wo writeoff_line['currency_id'] = currency_id writeoff_line = aml_obj.create(writeoff_line) if counterpart_aml['debit'] or (writeoff_line['credit'] and not counterpart_aml['credit']): counterpart_aml['debit'] += credit_wo - debit_wo if counterpart_aml['credit'] or (writeoff_line['debit'] and not counterpart_aml['debit']): counterpart_aml['credit'] += debit_wo - credit_wo counterpart_aml['amount_currency'] -= amount_currency_wo #Write counterpart lines if not self.currency_id.is_zero(self.amount): if not self.currency_id != self.company_id.currency_id: amount_currency = 0 liquidity_aml_dict = self._get_shared_move_line_vals( credit, debit, -amount_currency, move.id, False) liquidity_aml_dict.update( self._get_liquidity_move_line_vals(-amount)) aml_obj.create(liquidity_aml_dict) #validate the payment move.post() #reconcile the invoice receivable/payable line(s) with the payment self.invoice_ids.register_payment(counterpart_aml) return move def _create_transfer_entry(self, amount): """ Create the journal entry corresponding to the 'incoming money' part of an internal transfer, return the reconciliable move line """ aml_obj = self.env['account.move.line'].with_context( check_move_validity=False) debit, credit, amount_currency, dummy = aml_obj.with_context( date=self.payment_date).compute_amount_fields( amount, self.currency_id, self.company_id.currency_id) amount_currency = self.destination_journal_id.currency_id and self.currency_id.with_context( date=self.payment_date).compute( amount, self.destination_journal_id.currency_id) or 0 dst_move = self.env['account.move'].create( self._get_move_vals(self.destination_journal_id)) dst_liquidity_aml_dict = self._get_shared_move_line_vals( debit, credit, amount_currency, dst_move.id) dst_liquidity_aml_dict.update({ 'name': _('Transfer from %s') % self.journal_id.name, 'account_id': self.destination_journal_id.default_credit_account_id.id, 'branch_id': self.destination_journal_id.branch_id.id or False, 'currency_id': self.destination_journal_id.currency_id.id, 'journal_id': self.destination_journal_id.id }) aml_obj.create(dst_liquidity_aml_dict) transfer_debit_aml_dict = self._get_shared_move_line_vals( credit, debit, 0, dst_move.id) transfer_debit_aml_dict.update({ 'name': self.name, 'account_id': self.company_id.transfer_account_id.id, 'branch_id': self.journal_id.branch_id.id or False, 'journal_id': self.destination_journal_id.id }) if self.currency_id != self.company_id.currency_id: transfer_debit_aml_dict.update({ 'currency_id': self.currency_id.id, 'amount_currency': -self.amount, }) transfer_debit_aml = aml_obj.create(transfer_debit_aml_dict) dst_move.post() return transfer_debit_aml def _get_move_vals(self, journal=None): """ Return dict to create the payment move """ journal = journal or self.journal_id if not journal.sequence_id: raise UserError( _('Configuration Error !'), _('The journal %s does not have a sequence, please specify one.' ) % journal.name) if not journal.sequence_id.active: raise UserError( _('Configuration Error !'), _('The sequence of journal %s is deactivated.') % journal.name) name = self.move_name or journal.with_context( ir_sequence_date=self.payment_date).sequence_id.next_by_id() return { 'name': name, 'date': self.payment_date, 'ref': self.communication or '', 'company_id': self.company_id.id, 'journal_id': journal.id, } def _get_shared_move_line_vals(self, debit, credit, amount_currency, move_id, invoice_id=False): """ Returns values common to both move lines (except for debit, credit and amount_currency which are reversed) """ return { 'partner_id': self.payment_type in ('inbound', 'outbound') and self.env['res.partner']._find_accounting_partner( self.partner_id).id or False, 'invoice_id': invoice_id and invoice_id.id or False, 'move_id': move_id, 'debit': debit, 'credit': credit, 'amount_currency': amount_currency or False, 'payment_id': self.id, } def _get_counterpart_move_line_vals(self, invoice=False): if self.payment_type == 'transfer': name = self.name else: name = '' if self.partner_type == 'customer': if self.payment_type == 'inbound': name += _("Customer Payment") elif self.payment_type == 'outbound': name += _("Customer Credit Note") elif self.partner_type == 'supplier': if self.payment_type == 'inbound': name += _("Vendor Credit Note") elif self.payment_type == 'outbound': name += _("Vendor Payment") if invoice: name += ': ' for inv in invoice: if inv.move_id: name += inv.number + ', ' name = name[:len(name) - 2] if len(invoice) == 1: branch_id = invoice.branch_id.id or False else: branch_id = self.branch_id.id or False return { 'name': name, 'account_id': self.destination_account_id.id, 'branch_id': branch_id, 'journal_id': self.journal_id.id, 'currency_id': self.currency_id != self.company_id.currency_id and self.currency_id.id or False, } def _get_liquidity_move_line_vals(self, amount): name = self.name if self.payment_type == 'transfer': name = _('Transfer to %s') % self.destination_journal_id.name vals = { 'name': name, 'account_id': self.payment_type in ('outbound', 'transfer') and self.journal_id.default_debit_account_id.id or self.journal_id.default_credit_account_id.id, 'journal_id': self.journal_id.id, 'currency_id': self.currency_id != self.company_id.currency_id and self.currency_id.id or False, } # If the journal has a currency specified, the journal item need to be expressed in this currency if self.journal_id.currency_id and self.currency_id != self.journal_id.currency_id: amount = self.currency_id.with_context( date=self.payment_date).compute(amount, self.journal_id.currency_id) debit, credit, amount_currency, dummy = self.env[ 'account.move.line'].with_context( date=self.payment_date).compute_amount_fields( amount, self.journal_id.currency_id, self.company_id.currency_id) vals.update({ 'amount_currency': amount_currency, 'currency_id': self.journal_id.currency_id.id, }) vals['branch_id'] = self.journal_id.branch_id.id or False return vals
class HrContract(models.Model): _inherit = 'hr.contract' transport_mode = fields.Selection( [ ('company_car', 'Company car'), ('public_transport', 'Public Transport'), ('others', 'Other'), ], string="Transport", default='company_car', help="Transport mode the employee uses to go to work.") car_atn = fields.Monetary(string='ATN Company Car') public_transport_employee_amount = fields.Monetary( 'Paid by the employee (Monthly)') thirteen_month = fields.Monetary( compute='_compute_holidays_advantages', string='13th Month', help="Yearly gross amount the employee receives as 13th month bonus.") double_holidays = fields.Monetary( compute='_compute_holidays_advantages', string='Holiday Bonus', help="Yearly gross amount the employee receives as holidays bonus.") warrant_value_employee = fields.Monetary( compute='_compute_warrants_cost', string="Warrant value for the employee") # Employer costs fields final_yearly_costs = fields.Monetary( compute='_compute_final_yearly_costs', readonly=False, string='Total Employee Cost', groups="hr.group_hr_manager", track_visibility="onchange", help="Total yearly cost of the employee for the employer.") monthly_yearly_costs = fields.Monetary( compute='_compute_monthly_yearly_costs', string='Monthly Equivalent Cost', readonly=True, help="Total monthly cost of the employee for the employer.") ucm_insurance = fields.Monetary(compute='_compute_ucm_insurance', string="Social Secretary Costs") social_security_contributions = fields.Monetary( compute='_compute_social_security_contributions', string="Social Security Contributions") yearly_cost_before_charges = fields.Monetary( compute='_compute_yearly_cost_before_charges', string="Yearly Costs Before Charges") meal_voucher_paid_by_employer = fields.Monetary( compute='_compute_meal_voucher_paid_by_employer', string="Meal Voucher Paid by Employer") company_car_total_depreciated_cost = fields.Monetary() public_transport_reimbursed_amount = fields.Monetary( string='Reimbursed amount', compute='_compute_public_transport_reimbursed_amount', readonly=False, store=True) others_reimbursed_amount = fields.Monetary(string='Reimbursed amount') transport_employer_cost = fields.Monetary( compute='_compute_transport_employer_cost', string="Employer cost from employee transports") warrants_cost = fields.Monetary(compute='_compute_warrants_cost') # Advantages commission_on_target = fields.Monetary( string="Commission on Target", default=lambda self: self.get_attribute('commission_on_target', 'default_value'), track_visibility="onchange", help= "Monthly gross amount that the employee receives if the target is reached." ) fuel_card = fields.Monetary( string="Fuel Card", default=lambda self: self.get_attribute('fuel_card', 'default_value'), track_visibility="onchange", help="Monthly amount the employee receives on his fuel card.") internet = fields.Monetary( string="Internet", default=lambda self: self.get_attribute('internet', 'default_value'), track_visibility="onchange", help= "The employee's internet subcription will be paid up to this amount.") representation_fees = fields.Monetary( string="Representation Fees", default=lambda self: self.get_attribute('representation_fees', 'default_value'), track_visibility="onchange", help= "Monthly net amount the employee receives to cover his representation fees." ) mobile = fields.Monetary( string="Mobile", default=lambda self: self.get_attribute('mobile', 'default_value'), track_visibility="onchange", help= "The employee's mobile subscription will be paid up to this amount.") mobile_plus = fields.Monetary( string="International Communication", default=lambda self: self.get_attribute('mobile_plus', 'default_value' ), track_visibility="onchange", help= "The employee's mobile subscription for international communication will be paid up to this amount." ) meal_voucher_amount = fields.Monetary( string="Meal Vouchers", default=lambda self: self.get_attribute('meal_voucher_amount', 'default_value'), track_visibility="onchange", help= "Amount the employee receives in the form of meal vouchers per worked day." ) holidays = fields.Float( string='Legal Leaves', default=lambda self: self.get_attribute('holidays', 'default_value'), help="Number of days of paid leaves the employee gets per year.") holidays_editable = fields.Boolean(string="Editable Leaves", default=True) holidays_compensation = fields.Monetary( compute='_compute_holidays_compensation', string="Holidays Compensation") wage_with_holidays = fields.Monetary( compute='_compute_wage_with_holidays', inverse='_inverse_wage_with_holidays', string="Wage update with holidays retenues") additional_net_amount = fields.Monetary( string="Net Supplements", track_visibility="onchange", help="Monthly net amount the employee receives.") retained_net_amount = fields.Monetary( sting="Net Retained", track_visibility="onchange", help="Monthly net amount that is retained on the employee's salary.") eco_checks = fields.Monetary( "Eco Vouchers", default=lambda self: self.get_attribute('eco_checks', 'default_value'), help="Yearly amount the employee receives in the form of eco vouchers." ) @api.depends('holidays', 'wage', 'final_yearly_costs') def _compute_wage_with_holidays(self): for contract in self: if contract.holidays > 20.0: yearly_cost = contract.final_yearly_costs * ( 1.0 - (contract.holidays - 20.0) / 231.0) contract.wage_with_holidays = contract._get_gross_from_employer_costs( yearly_cost) else: contract.wage_with_holidays = contract.wage def _inverse_wage_with_holidays(self): for contract in self: if contract.holidays > 20.0: remaining_for_gross = contract.wage_with_holidays * ( 13.0 + 13.0 * 0.3507 + 0.92) yearly_cost = remaining_for_gross \ + 12.0 * contract.representation_fees \ + 12.0 * contract.fuel_card \ + 12.0 * contract.internet \ + 12.0 * (contract.mobile + contract.mobile_plus) \ + 12.0 * contract.transport_employer_cost \ + contract.warrants_cost \ + 220.0 * contract.meal_voucher_paid_by_employer contract.final_yearly_costs = yearly_cost / ( 1.0 - (contract.holidays - 20.0) / 231.0) contract.wage = contract._get_gross_from_employer_costs( contract.final_yearly_costs) else: contract.wage = contract.wage_with_holidays @api.depends('transport_mode', 'company_car_total_depreciated_cost', 'public_transport_reimbursed_amount', 'others_reimbursed_amount') def _compute_transport_employer_cost(self): for contract in self: if contract.transport_mode == 'company_car': contract.transport_employer_cost = contract.company_car_total_depreciated_cost elif contract.transport_mode == 'public_transport': contract.transport_employer_cost = contract.public_transport_reimbursed_amount elif contract.transport_mode == 'others': contract.transport_employer_cost = contract.others_reimbursed_amount @api.depends('commission_on_target') def _compute_warrants_cost(self): for contract in self: contract.warrants_cost = contract.commission_on_target * 1.326 * 1.05 * 12.0 contract.warrant_value_employee = contract.commission_on_target * 1.326 * ( 1.00 - 0.535) * 12.0 @api.depends('wage', 'fuel_card', 'representation_fees', 'transport_employer_cost', 'internet', 'mobile', 'mobile_plus') def _compute_yearly_cost_before_charges(self): for contract in self: contract.yearly_cost_before_charges = 12.0 * ( contract.wage * (1.0 + 1.0 / 12.0) + contract.fuel_card + contract.representation_fees + contract.internet + contract.mobile + contract.mobile_plus + contract.transport_employer_cost) @api.depends('yearly_cost_before_charges', 'social_security_contributions', 'wage', 'social_security_contributions', 'double_holidays', 'warrants_cost', 'meal_voucher_paid_by_employer') def _compute_final_yearly_costs(self): for contract in self: contract.final_yearly_costs = ( contract.yearly_cost_before_charges + contract.social_security_contributions + contract.double_holidays + contract.warrants_cost + (220.0 * contract.meal_voucher_paid_by_employer)) @api.depends('holidays', 'final_yearly_costs') def _compute_holidays_compensation(self): for contract in self: if contract.holidays < 20: decrease_amount = contract.final_yearly_costs * ( 20.0 - contract.holidays) / 231.0 contract.holidays_compensation = decrease_amount else: contract.holidays_compensation = 0.0 @api.onchange('final_yearly_costs') def _onchange_final_yearly_costs(self): self.wage = self._get_gross_from_employer_costs( self.final_yearly_costs) @api.depends('meal_voucher_amount') def _compute_meal_voucher_paid_by_employer(self): for contract in self: contract.meal_voucher_paid_by_employer = contract.meal_voucher_amount * ( 1 - 0.1463) @api.depends('wage') def _compute_social_security_contributions(self): for contract in self: total_wage = contract.wage * 13.0 contract.social_security_contributions = (total_wage) * 0.3507 @api.depends('wage') def _compute_ucm_insurance(self): for contract in self: contract.ucm_insurance = (contract.wage * 12.0) * 0.05 @api.depends('public_transport_employee_amount') def _compute_public_transport_reimbursed_amount(self): for contract in self: contract.public_transport_reimbursed_amount = contract._get_public_transport_reimbursed_amount( contract.public_transport_employee_amount) def _get_public_transport_reimbursed_amount(self, amount): return amount * 0.68 @api.depends('final_yearly_costs') def _compute_monthly_yearly_costs(self): for contract in self: contract.monthly_yearly_costs = contract.final_yearly_costs / 12.0 @api.depends('wage') def _compute_holidays_advantages(self): for contract in self: contract.double_holidays = contract.wage * 0.92 contract.thirteen_month = contract.wage @api.onchange('transport_mode') def _onchange_transport_mode(self): if self.transport_mode != 'company_car': self.fuel_card = 0 self.company_car_total_depreciated_cost = 0 if self.transport_mode != 'others': self.others_reimbursed_amount = 0 if self.transport_mode != 'public_transports': self.public_transport_reimbursed_amount = 0 @api.onchange('mobile', 'mobile_plus') def _onchange_mobile(self): if self.mobile_plus and not self.mobile: raise ValidationError( _('You should have a mobile subscription to select an international communication amount!' )) def _get_internet_amount(self, has_internet): if has_internet: return self.get_attribute('internet', 'default_value') else: return 0.0 def _get_mobile_amount(self, has_mobile, international_communication): if has_mobile and international_communication: return self.get_attribute('mobile', 'default_value') + self.get_attribute( 'mobile_plus', 'default_value') elif has_mobile: return self.get_attribute('mobile', 'default_value') else: return 0.0 def _get_gross_from_employer_costs(self, yearly_cost): contract = self remaining_for_gross = yearly_cost \ - 12.0 * contract.representation_fees \ - 12.0 * contract.fuel_card \ - 12.0 * contract.internet \ - 12.0 * (contract.mobile + contract.mobile_plus) \ - 12.0 * contract.transport_employer_cost \ - contract.warrants_cost \ - 220.0 * contract.meal_voucher_paid_by_employer gross = remaining_for_gross / (13.0 + 13.0 * 0.3507 + 0.92) return gross
class HrExpenseSheetRegisterPaymentWizard(models.TransientModel): _name = "hr.expense.sheet.register.payment.wizard" _description = "Expense Report Register Payment wizard" @api.model def _default_partner_id(self): context = dict(self._context or {}) active_ids = context.get('active_ids', []) expense_sheet = self.env['hr.expense.sheet'].browse(active_ids) return expense_sheet.address_id.id or expense_sheet.employee_id.id and expense_sheet.employee_id.address_home_id.id partner_id = fields.Many2one('res.partner', string='Partner', required=True, default=_default_partner_id) journal_id = fields.Many2one('account.journal', string='Payment Method', required=True, domain=[('type', 'in', ('bank', 'cash'))]) company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True, required=True) payment_method_id = fields.Many2one('account.payment.method', string='Payment Type', required=True) amount = fields.Monetary(string='Payment Amount', required=True) currency_id = fields.Many2one( 'res.currency', string='Currency', required=True, default=lambda self: self.env.user.company_id.currency_id) payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True) communication = fields.Char(string='Memo') hide_payment_method = fields.Boolean( compute='_compute_hide_payment_method', help= "Technical field used to hide the payment method if the selected journal has only one available which is 'manual'" ) @api.one @api.constrains('amount') def _check_amount(self): if not self.amount > 0.0: raise ValidationError( _('The payment amount must be strictly positive.')) @api.one @api.depends('journal_id') def _compute_hide_payment_method(self): if not self.journal_id: self.hide_payment_method = True return journal_payment_methods = self.journal_id.outbound_payment_method_ids self.hide_payment_method = len( journal_payment_methods ) == 1 and journal_payment_methods[0].code == 'manual' @api.onchange('journal_id') def _onchange_journal(self): if self.journal_id: # Set default payment method (we consider the first to be the default one) payment_methods = self.journal_id.outbound_payment_method_ids self.payment_method_id = payment_methods and payment_methods[ 0] or False # Set payment method domain (restrict to methods enabled for the journal and to selected payment type) return { 'domain': { 'payment_method_id': [('payment_type', '=', 'outbound'), ('id', 'in', payment_methods.ids)] } } return {} def _get_payment_vals(self): """ Hook for extension """ return { 'partner_type': 'supplier', 'payment_type': 'outbound', 'partner_id': self.partner_id.id, 'journal_id': self.journal_id.id, 'company_id': self.company_id.id, 'payment_method_id': self.payment_method_id.id, 'amount': self.amount, 'currency_id': self.currency_id.id, 'payment_date': self.payment_date, 'communication': self.communication } @api.multi def expense_post_payment(self): self.ensure_one() context = dict(self._context or {}) active_ids = context.get('active_ids', []) expense_sheet = self.env['hr.expense.sheet'].browse(active_ids) # Create payment and post it payment = self.env['account.payment'].create(self._get_payment_vals()) payment.post() # Log the payment in the chatter body = (_( "A payment of %s %s with the reference <a href='/mail/view?%s'>%s</a> related to your expense %s has been made." ) % (payment.amount, payment.currency_id.symbol, url_encode({ 'model': 'account.payment', 'res_id': payment.id }), payment.name, expense_sheet.name)) expense_sheet.message_post(body=body) # Reconcile the payment and the expense, i.e. lookup on the payable account move lines account_move_lines_to_reconcile = self.env['account.move.line'] for line in payment.move_line_ids + expense_sheet.account_move_id.line_ids: if line.account_id.internal_type == 'payable': account_move_lines_to_reconcile |= line account_move_lines_to_reconcile.reconcile() return {'type': 'ir.actions.act_window_close'}
class SaleOrder(models.Model): _inherit = "sale.order" @api.multi @api.depends('discount_amount', 'discount_per', 'amount_untaxed', 'order_line') def _get_discount(self): total_discount = 0.0 for record in self: for so_line_id in record.order_line: total_price = \ (so_line_id.product_uom_qty * so_line_id.price_unit) total_discount += (total_price * so_line_id.discount) / 100 record.discount = record.pricelist_id.currency_id.round(total_discount) @api.multi @api.depends('order_line', 'discount_per', 'discount_amount', 'order_line.product_uom_qty', 'order_line.price_unit') def _get_total_amount(self): for order_id in self: order_id.gross_amount = sum( [line_id.product_uom_qty * line_id.price_unit for line_id in order_id.order_line]) discount_method = fields.Selection( [('fixed', 'Fixed'), ('per', 'Percentage')], string="Discount Method") discount_amount = fields.Float(string="Discount Amount") discount_per = fields.Float(string="Discount (%)") discount = fields.Monetary( string='Discount', store=True, readonly=True, compute='_get_discount', track_visibility='always') gross_amount = fields.Float(string="Gross Amount", compute='_get_total_amount', store=True) @api.multi def calculate_discount(self): self._check_constrains() for line in self.order_line: line.write({'discount': 0.0}) # amount_untaxed = self.amount_untaxed gross_amount = self.gross_amount if self.discount_method == 'per': for line in self.order_line: line.write({'discount': self.discount_per}) else: for line in self.order_line: discount_value_ratio = \ (self.discount_amount * line.price_subtotal) / gross_amount discount_per_ratio = \ (discount_value_ratio * 100) / line.price_subtotal line.write({'discount': discount_per_ratio}) @api.onchange('discount_method') def onchange_discount_method(self): self.discount_amount = 0.0 self.discount_per = 0.0 if self.discount_method and not self.order_line: raise Warning('No Sale Order Line(s) were found!') @api.constrains('discount_per', 'discount_amount', 'order_line') def _check_constrains(self): self.onchange_discount_per() self.onchange_discount_amount() @api.multi def get_maximum_per_amount(self): sale_dis_config_obj = self.env['sale.discount.config'] max_percentage = 0 max_amount = 0 check_group = False for groups_id in self.env.user.groups_id: sale_dis_config_id = \ sale_dis_config_obj.search([('group_id', '=', groups_id.id)]) if sale_dis_config_id: check_group = True if sale_dis_config_id.percentage > max_percentage: max_percentage = sale_dis_config_id.percentage if sale_dis_config_id.fix_amount > max_amount: max_amount = sale_dis_config_id.fix_amount return {'max_percentage': max_percentage, 'max_amount': max_amount, 'check_group': check_group} @api.onchange('discount_per') def onchange_discount_per(self): values = self.get_maximum_per_amount() if self.discount_method == 'per' and ( self.discount_per > 100 or self.discount_per < 0) and \ values.get('check_group', False): raise Warning(_("Percentage should be between 0% to 100%")) if self.discount_per > values.get('max_percentage', False) and \ values.get('check_group', False): raise Warning(_("You are not allowed to apply Discount Percentage" " (%s) more than configured Discount Percentage " "(%s) in configuration setting!") % ( formatLang(self.env, self.discount_per, digits=2), formatLang(self.env, values['max_percentage'], digits=2))) config_id = self.env['res.config.settings'].search( [], order='id desc', limit=1) if config_id and config_id.global_discount_apply: if config_id.global_discount_percentage < self.discount_per: raise Warning(_("You are not allowed to apply Discount " "Percentage (%s) more than configured " "Discount Percentage (%s) in configuration " "setting!") % ( formatLang(self.env, self.discount_per, digits=2), formatLang(self.env, config_id.global_discount_percentage, digits=2))) @api.onchange('discount_amount') def onchange_discount_amount(self): values = self.get_maximum_per_amount() if self.discount < 0: raise Warning(_("Discount should be less than Gross Amount")) discount = self.discount or self.discount_amount if discount > self.gross_amount: raise Warning(_("Discount (%s) should be less than " "Gross Amount (%s).") % ( formatLang(self.env, discount, digits=2), formatLang(self.env, self.gross_amount, digits=2))) if self.discount_amount > values.get('max_amount', False) \ and values.get('check_group', False): raise Warning(_("You're not allowed to apply Discount Amount " "(%s) more than configured amount (%s) in " "configuration setting!") % ( formatLang(self.env, self.discount_amount, digits=2), formatLang(self.env, values['max_amount'], digits=2))) config_id = self.env['res.config.settings'].search( [], order='id desc', limit=1) if config_id and config_id.global_discount_apply: if config_id.global_discount_fix_amount < self.discount_amount: raise Warning(_("You're not allowed to apply Discount " "Amount (%s) more than configured amount " "(%s) in configuration setting!") % ( formatLang(self.env, self.discount_amount, digits=2), formatLang(self.env, config_id.global_discount_fix_amount, digits=2))) @api.multi def _prepare_invoice(self): sale_order = self.env['sale.order'].browse( self._context.get('active_ids', [])) invoice_vals = super(SaleOrder, self)._prepare_invoice() invoice_vals.update({ 'discount_method': sale_order.discount_method, 'discount_amount': sale_order.discount_amount, 'discount_per': sale_order.discount_per, 'discount': sale_order.discount, }) return invoice_vals
class Contract(models.Model): _name = 'hr.contract' _description = 'Contract' _inherit = ['mail.thread'] name = fields.Char('Contract Reference', required=True) employee_id = fields.Many2one('hr.employee', string='Employee') department_id = fields.Many2one('hr.department', string="Department") type_id = fields.Many2one( 'hr.contract.type', string="Contract Type", required=True, default=lambda self: self.env['hr.contract.type'].search([], limit=1)) job_id = fields.Many2one('hr.job', string='Job Position') date_start = fields.Date('Start Date', required=True, default=fields.Date.today, help="Start date of the contract.") date_end = fields.Date( 'End Date', help="End date of the contract (if it's a fixed-term contract).") trial_date_end = fields.Date( 'End of Trial Period', help="End date of the trial period (if there is one).") resource_calendar_id = fields.Many2one( 'resource.calendar', 'Working Schedule', default=lambda self: self.env['res.company']._company_default_get( ).resource_calendar_id.id) wage = fields.Monetary('Wage', digits=(16, 2), required=True, help="Employee's monthly gross wage.") advantages = fields.Text('Advantages') notes = fields.Text('Notes') state = fields.Selection([('draft', 'New'), ('open', 'Running'), ('pending', 'To Renew'), ('close', 'Expired'), ('cancel', 'Cancelled')], string='Status', group_expand='_expand_states', track_visibility='onchange', help='Status of the contract', default='draft') company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id) currency_id = fields.Many2one(string="Currency", related='company_id.currency_id', readonly=True) permit_no = fields.Char('Work Permit No', related="employee_id.permit_no") visa_no = fields.Char('Visa No', related="employee_id.visa_no") visa_expire = fields.Date('Visa Expire Date', related="employee_id.visa_expire") def _expand_states(self, states, domain, order): return [key for key, val in type(self).state.selection] @api.onchange('employee_id') def _onchange_employee_id(self): if self.employee_id: self.job_id = self.employee_id.job_id self.department_id = self.employee_id.department_id self.resource_calendar_id = self.employee_id.resource_calendar_id @api.constrains('date_start', 'date_end') def _check_dates(self): if self.filtered(lambda c: c.date_end and c.date_start > c.date_end): raise ValidationError( _('Contract start date must be less than contract end date.')) @api.model def update_state(self): self.search([ ('state', '=', 'open'), '|', '&', ('date_end', '<=', fields.Date.to_string(date.today() + relativedelta(days=7))), ('date_end', '>=', fields.Date.to_string(date.today() + relativedelta(days=1))), '&', ('visa_expire', '<=', fields.Date.to_string(date.today() + relativedelta(days=60))), ('visa_expire', '>=', fields.Date.to_string(date.today() + relativedelta(days=1))), ]).write({'state': 'pending'}) self.search([ ('state', 'in', ('open', 'pending')), '|', ('date_end', '<=', fields.Date.to_string(date.today() + relativedelta(days=1))), ('visa_expire', '<=', fields.Date.to_string(date.today() + relativedelta(days=1))), ]).write({'state': 'close'}) return True @api.multi def _track_subtype(self, init_values): self.ensure_one() if 'state' in init_values and self.state == 'pending': return 'hr_contract.mt_contract_pending' elif 'state' in init_values and self.state == 'close': return 'hr_contract.mt_contract_close' return super(Contract, self)._track_subtype(init_values)