size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
1,580
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError, UserError class PosCategory(models.Model): _name = "pos.category" _description = "Point of Sale Category" _order = "sequence, name" @api.constrains('parent_id') def _check_category_recursion(self): if not self._check_recursion(): raise ValidationError(_('Error ! You cannot create recursive categories.')) name = fields.Char(string='Category Name', required=True, translate=True) parent_id = fields.Many2one('pos.category', string='Parent Category', index=True) child_id = fields.One2many('pos.category', 'parent_id', string='Children Categories') sequence = fields.Integer(help="Gives the sequence order when displaying a list of product categories.") image_128 = fields.Image("Image", max_width=128, max_height=128) def name_get(self): def get_names(cat): res = [] while cat: res.append(cat.name) cat = cat.parent_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self] @api.ondelete(at_uninstall=False) def _unlink_except_session_open(self): if self.search_count([('id', 'in', self.ids)]): if self.env['pos.session'].sudo().search_count([('state', '!=', 'closed')]): raise UserError(_('You cannot delete a point of sale category while a session is still opened.'))
43.888889
1,580
2,020
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ class Warehouse(models.Model): _inherit = "stock.warehouse" pos_type_id = fields.Many2one('stock.picking.type', string="Point of Sale Operation Type") def _get_sequence_values(self): sequence_values = super(Warehouse, self)._get_sequence_values() sequence_values.update({ 'pos_type_id': { 'name': self.name + ' ' + _('Picking POS'), 'prefix': self.code + '/POS/', 'padding': 5, 'company_id': self.company_id.id, } }) return sequence_values def _get_picking_type_update_values(self): picking_type_update_values = super(Warehouse, self)._get_picking_type_update_values() picking_type_update_values.update({ 'pos_type_id': {'default_location_src_id': self.lot_stock_id.id} }) return picking_type_update_values def _get_picking_type_create_values(self, max_sequence): picking_type_create_values, max_sequence = super(Warehouse, self)._get_picking_type_create_values(max_sequence) picking_type_create_values.update({ 'pos_type_id': { 'name': _('PoS Orders'), 'code': 'outgoing', 'default_location_src_id': self.lot_stock_id.id, 'default_location_dest_id': self.env.ref('stock.stock_location_customers').id, 'sequence': max_sequence + 1, 'sequence_code': 'POS', 'company_id': self.company_id.id, 'show_operations': False, } }) return picking_type_create_values, max_sequence + 2 @api.model def _create_missing_pos_picking_types(self): warehouses = self.env['stock.warehouse'].search([('pos_type_id', '=', False)]) for warehouse in warehouses: new_vals = warehouse._create_or_update_sequences_and_picking_types() warehouse.write(new_vals)
39.607843
2,020
1,182
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2004-2008 PC Solutions (<http://pcsol.be>). All Rights Reserved from odoo import fields, models, api, _ from odoo.exceptions import ValidationError class AccountJournal(models.Model): _inherit = 'account.journal' pos_payment_method_ids = fields.One2many('pos.payment.method', 'journal_id', string='Point of Sale Payment Methods') @api.constrains('type') def _check_type(self): methods = self.env['pos.payment.method'].sudo().search([("journal_id", "in", self.ids)]) if methods: raise ValidationError(_("This journal is associated with a payment method. You cannot modify its type")) def _get_journal_inbound_outstanding_payment_accounts(self): res = super()._get_journal_inbound_outstanding_payment_accounts() account_ids = set(res.ids) for payment_method in self.sudo().pos_payment_method_ids: account_ids.add(payment_method.outstanding_account_id.id or self.company_id.account_journal_payment_debit_account_id.id) return self.env['account.account'].browse(account_ids)
51.391304
1,182
89,740
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict from datetime import timedelta from odoo import api, fields, models, _, Command from odoo.exceptions import AccessError, UserError, ValidationError from odoo.tools import float_is_zero, float_compare class PosSession(models.Model): _name = 'pos.session' _order = 'id desc' _description = 'Point of Sale Session' _inherit = ['mail.thread', 'mail.activity.mixin'] POS_SESSION_STATE = [ ('opening_control', 'Opening Control'), # method action_pos_session_open ('opened', 'In Progress'), # method action_pos_session_closing_control ('closing_control', 'Closing Control'), # method action_pos_session_close ('closed', 'Closed & Posted'), ] company_id = fields.Many2one('res.company', related='config_id.company_id', string="Company", readonly=True) config_id = fields.Many2one( 'pos.config', string='Point of Sale', help="The physical point of sale you will use.", required=True, index=True) name = fields.Char(string='Session ID', required=True, readonly=True, default='/') user_id = fields.Many2one( 'res.users', string='Opened By', required=True, index=True, readonly=True, states={'opening_control': [('readonly', False)]}, default=lambda self: self.env.uid, ondelete='restrict') currency_id = fields.Many2one('res.currency', related='config_id.currency_id', string="Currency", readonly=False) start_at = fields.Datetime(string='Opening Date', readonly=True) stop_at = fields.Datetime(string='Closing Date', readonly=True, copy=False) state = fields.Selection( POS_SESSION_STATE, string='Status', required=True, readonly=True, index=True, copy=False, default='opening_control') sequence_number = fields.Integer(string='Order Sequence Number', help='A sequence number that is incremented with each order', default=1) login_number = fields.Integer(string='Login Sequence Number', help='A sequence number that is incremented each time a user resumes the pos session', default=0) opening_notes = fields.Text(string="Opening Notes") cash_control = fields.Boolean(compute='_compute_cash_all', string='Has Cash Control', compute_sudo=True) cash_journal_id = fields.Many2one('account.journal', compute='_compute_cash_all', string='Cash Journal', store=True) cash_register_id = fields.Many2one('account.bank.statement', compute='_compute_cash_all', string='Cash Register', store=True) cash_register_balance_end_real = fields.Monetary( related='cash_register_id.balance_end_real', string="Ending Balance", help="Total of closing cash control lines.", readonly=True) cash_register_balance_start = fields.Monetary( related='cash_register_id.balance_start', string="Starting Balance", help="Total of opening cash control lines.", readonly=True) cash_register_total_entry_encoding = fields.Monetary( compute='_compute_cash_balance', string='Total Cash Transaction', readonly=True, help="Total of all paid sales orders") cash_register_balance_end = fields.Monetary( compute='_compute_cash_balance', string="Theoretical Closing Balance", help="Sum of opening balance and transactions.", readonly=True) cash_register_difference = fields.Monetary( compute='_compute_cash_balance', string='Before Closing Difference', help="Difference between the theoretical closing balance and the real closing balance.", readonly=True) cash_real_difference = fields.Monetary(string='Difference', readonly=True) cash_real_transaction = fields.Monetary(string='Transaction', readonly=True) cash_real_expected = fields.Monetary(string="Expected", readonly=True) order_ids = fields.One2many('pos.order', 'session_id', string='Orders') order_count = fields.Integer(compute='_compute_order_count') statement_ids = fields.One2many('account.bank.statement', 'pos_session_id', string='Cash Statements', readonly=True) failed_pickings = fields.Boolean(compute='_compute_picking_count') picking_count = fields.Integer(compute='_compute_picking_count') picking_ids = fields.One2many('stock.picking', 'pos_session_id') rescue = fields.Boolean(string='Recovery Session', help="Auto-generated session for orphan orders, ignored in constraints", readonly=True, copy=False) move_id = fields.Many2one('account.move', string='Journal Entry', index=True) payment_method_ids = fields.Many2many('pos.payment.method', related='config_id.payment_method_ids', string='Payment Methods') total_payments_amount = fields.Float(compute='_compute_total_payments_amount', string='Total Payments Amount') is_in_company_currency = fields.Boolean('Is Using Company Currency', compute='_compute_is_in_company_currency') update_stock_at_closing = fields.Boolean('Stock should be updated at closing') bank_payment_ids = fields.One2many('account.payment', 'pos_session_id', 'Bank Payments', help='Account payments representing aggregated and bank split payments.') _sql_constraints = [('uniq_name', 'unique(name)', "The name of this POS Session must be unique !")] @api.depends('currency_id', 'company_id.currency_id') def _compute_is_in_company_currency(self): for session in self: session.is_in_company_currency = session.currency_id == session.company_id.currency_id @api.depends('payment_method_ids', 'order_ids', 'cash_register_balance_start', 'cash_register_id') def _compute_cash_balance(self): for session in self: cash_payment_method = session.payment_method_ids.filtered('is_cash_count')[:1] if cash_payment_method: total_cash_payment = 0.0 result = self.env['pos.payment'].read_group([('session_id', '=', session.id), ('payment_method_id', '=', cash_payment_method.id)], ['amount'], ['session_id']) if result: total_cash_payment = result[0]['amount'] session.cash_register_total_entry_encoding = session.cash_register_id.total_entry_encoding + ( 0.0 if session.state == 'closed' else total_cash_payment ) session.cash_register_balance_end = session.cash_register_balance_start + session.cash_register_total_entry_encoding session.cash_register_difference = session.cash_register_balance_end_real - session.cash_register_balance_end else: session.cash_register_total_entry_encoding = 0.0 session.cash_register_balance_end = 0.0 session.cash_register_difference = 0.0 @api.depends('order_ids.payment_ids.amount') def _compute_total_payments_amount(self): result = self.env['pos.payment'].read_group([('session_id', 'in', self.ids)], ['amount'], ['session_id']) session_amount_map = dict((data['session_id'][0], data['amount']) for data in result) for session in self: session.total_payments_amount = session_amount_map.get(session.id) or 0 def _compute_order_count(self): orders_data = self.env['pos.order'].read_group([('session_id', 'in', self.ids)], ['session_id'], ['session_id']) sessions_data = {order_data['session_id'][0]: order_data['session_id_count'] for order_data in orders_data} for session in self: session.order_count = sessions_data.get(session.id, 0) @api.depends('picking_ids', 'picking_ids.state') def _compute_picking_count(self): for session in self: session.picking_count = self.env['stock.picking'].search_count([('pos_session_id', '=', session.id)]) session.failed_pickings = bool(self.env['stock.picking'].search([('pos_session_id', '=', session.id), ('state', '!=', 'done')], limit=1)) def action_stock_picking(self): self.ensure_one() action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_ready') action['display_name'] = _('Pickings') action['context'] = {} action['domain'] = [('id', 'in', self.picking_ids.ids)] return action @api.depends('config_id', 'statement_ids', 'payment_method_ids') def _compute_cash_all(self): # Only one cash register is supported by point_of_sale. for session in self: session.cash_journal_id = session.cash_register_id = session.cash_control = False cash_payment_methods = session.payment_method_ids.filtered('is_cash_count') if not cash_payment_methods: continue for statement in session.statement_ids: if statement.journal_id == cash_payment_methods[0].journal_id: session.cash_control = session.config_id.cash_control session.cash_journal_id = statement.journal_id.id session.cash_register_id = statement.id break # stop iteration after finding the cash journal @api.constrains('config_id') def _check_pos_config(self): if self.search_count([ ('state', '!=', 'closed'), ('config_id', '=', self.config_id.id), ('rescue', '=', False) ]) > 1: raise ValidationError(_("Another session is already opened for this point of sale.")) @api.constrains('start_at') def _check_start_date(self): for record in self: company = record.config_id.journal_id.company_id start_date = record.start_at.date() if (company.period_lock_date and start_date <= company.period_lock_date) or (company.fiscalyear_lock_date and start_date <= company.fiscalyear_lock_date): raise ValidationError(_("You cannot create a session before the accounting lock date.")) def _check_bank_statement_state(self): for session in self: closed_statement_ids = session.statement_ids.filtered(lambda x: x.state != "open") if closed_statement_ids: raise UserError(_("Some Cash Registers are already posted. Please reset them to new in order to close the session.\n" "Cash Registers: %r", list(statement.name for statement in closed_statement_ids))) def _check_invoices_are_posted(self): unposted_invoices = self.order_ids.sudo().with_company(self.company_id).account_move.filtered(lambda x: x.state != 'posted') if unposted_invoices: raise UserError(_('You cannot close the POS when invoices are not posted.\n' 'Invoices: %s') % str.join('\n', ['%s - %s' % (invoice.name, invoice.state) for invoice in unposted_invoices])) @api.model def create(self, values): config_id = values.get('config_id') or self.env.context.get('default_config_id') if not config_id: raise UserError(_("You should assign a Point of Sale to your session.")) # journal_id is not required on the pos_config because it does not # exists at the installation. If nothing is configured at the # installation we do the minimal configuration. Impossible to do in # the .xml files as the CoA is not yet installed. pos_config = self.env['pos.config'].browse(config_id) ctx = dict(self.env.context, company_id=pos_config.company_id.id) pos_name = self.env['ir.sequence'].with_context(ctx).next_by_code('pos.session') if values.get('name'): pos_name += ' ' + values['name'] cash_payment_methods = pos_config.payment_method_ids.filtered(lambda pm: pm.is_cash_count) statement_ids = self.env['account.bank.statement'] if self.user_has_groups('point_of_sale.group_pos_user'): statement_ids = statement_ids.sudo() for cash_journal in cash_payment_methods.mapped('journal_id'): ctx['journal_id'] = cash_journal.id if pos_config.cash_control and cash_journal.type == 'cash' else False st_values = { 'journal_id': cash_journal.id, 'user_id': self.env.user.id, 'name': pos_name, } statement_ids |= statement_ids.with_context(ctx).create(st_values) update_stock_at_closing = pos_config.company_id.point_of_sale_update_stock_quantities == "closing" values.update({ 'name': pos_name, 'statement_ids': [(6, 0, statement_ids.ids)], 'config_id': config_id, 'update_stock_at_closing': update_stock_at_closing, }) if self.user_has_groups('point_of_sale.group_pos_user'): res = super(PosSession, self.with_context(ctx).sudo()).create(values) else: res = super(PosSession, self.with_context(ctx)).create(values) res.action_pos_session_open() return res def unlink(self): for session in self.filtered(lambda s: s.statement_ids): session.statement_ids.unlink() return super(PosSession, self).unlink() def login(self): self.ensure_one() login_number = self.login_number + 1 self.write({ 'login_number': login_number, }) return login_number def action_pos_session_open(self): # second browse because we need to refetch the data from the DB for cash_register_id # we only open sessions that haven't already been opened for session in self.filtered(lambda session: session.state == 'opening_control'): values = {} if not session.start_at: values['start_at'] = fields.Datetime.now() if session.config_id.cash_control and not session.rescue: last_session = self.search([('config_id', '=', session.config_id.id), ('id', '!=', session.id)], limit=1) session.cash_register_id.balance_start = last_session.cash_register_id.balance_end_real if last_session else 0 values['state'] = 'opening_control' else: values['state'] = 'opened' session.write(values) return True def action_pos_session_closing_control(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): bank_payment_method_diffs = bank_payment_method_diffs or {} self._check_pos_session_balance() for session in self: if any(order.state == 'draft' for order in session.order_ids): raise UserError(_("You cannot close the POS when orders are still in draft")) if session.state == 'closed': raise UserError(_('This session is already closed.')) session.write({'state': 'closing_control', 'stop_at': fields.Datetime.now()}) if not session.config_id.cash_control: return session.action_pos_session_close(balancing_account, amount_to_balance, bank_payment_method_diffs) # If the session is in rescue, we only compute the payments in the cash register # It is not yet possible to close a rescue session through the front end, see `close_session_from_ui` if session.rescue and session.config_id.cash_control: default_cash_payment_method_id = self.payment_method_ids.filtered(lambda pm: pm.type == 'cash')[0] orders = self.order_ids.filtered(lambda o: o.state == 'paid' or o.state == 'invoiced') total_cash = sum( orders.payment_ids.filtered(lambda p: p.payment_method_id == default_cash_payment_method_id).mapped('amount') ) + self.cash_register_balance_start session.cash_register_id.balance_end_real = total_cash return session.action_pos_session_validate(balancing_account, amount_to_balance, bank_payment_method_diffs) def _check_pos_session_balance(self): for session in self: for statement in session.statement_ids: if (statement != session.cash_register_id) and (statement.balance_end != statement.balance_end_real): statement.write({'balance_end_real': statement.balance_end}) def action_pos_session_validate(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): bank_payment_method_diffs = bank_payment_method_diffs or {} self._check_pos_session_balance() return self.action_pos_session_close(balancing_account, amount_to_balance, bank_payment_method_diffs) def action_pos_session_close(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): bank_payment_method_diffs = bank_payment_method_diffs or {} # Session without cash payment method will not have a cash register. # However, there could be other payment methods, thus, session still # needs to be validated. self._check_bank_statement_state() return self._validate_session(balancing_account, amount_to_balance, bank_payment_method_diffs) def _validate_session(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): bank_payment_method_diffs = bank_payment_method_diffs or {} self.ensure_one() sudo = self.user_has_groups('point_of_sale.group_pos_user') if self.order_ids or self.sudo().statement_ids.line_ids: self.cash_real_transaction = self.cash_register_total_entry_encoding self.cash_real_expected = self.cash_register_balance_end self.cash_real_difference = self.cash_register_difference if self.state == 'closed': raise UserError(_('This session is already closed.')) self._check_if_no_draft_orders() self._check_invoices_are_posted() if self.update_stock_at_closing: self._create_picking_at_end_of_session() self.order_ids.filtered(lambda o: not o.is_total_cost_computed)._compute_total_cost_at_session_closing(self.picking_ids.move_lines) try: with self.env.cr.savepoint(): data = self.with_company(self.company_id)._create_account_move(balancing_account, amount_to_balance, bank_payment_method_diffs) except AccessError as e: if sudo: data = self.sudo().with_company(self.company_id)._create_account_move(balancing_account, amount_to_balance, bank_payment_method_diffs) else: raise e try: balance = sum(self.move_id.line_ids.mapped('balance')) self.move_id._check_balanced() except UserError: # Creating the account move is just part of a big database transaction # when closing a session. There are other database changes that will happen # before attempting to create the account move, such as, creating the picking # records. # We don't, however, want them to be committed when the account move creation # failed; therefore, we need to roll back this transaction before showing the # close session wizard. self.env.cr.rollback() return self._close_session_action(balance) if self.move_id.line_ids: self.move_id.sudo().with_company(self.company_id)._post() # Set the uninvoiced orders' state to 'done' self.env['pos.order'].search([('session_id', '=', self.id), ('state', '=', 'paid')]).write({'state': 'done'}) else: self.move_id.sudo().unlink() self.sudo().with_company(self.company_id)._reconcile_account_move_lines(data) else: statement = self.cash_register_id if not self.config_id.cash_control: statement.write({'balance_end_real': statement.balance_end}) statement.sudo().button_post() statement.button_validate() self.write({'state': 'closed'}) return True def _close_session_action(self, amount_to_balance): # NOTE This can't handle `bank_payment_method_diffs` because there is no field in the wizard that can carry it. default_account = self._get_balancing_account() wizard = self.env['pos.close.session.wizard'].create({ 'amount_to_balance': amount_to_balance, 'account_id': default_account.id, 'account_readonly': not self.env.user.has_group('account.group_account_readonly'), 'message': _("There is a difference between the amounts to post and the amounts of the orders, it is probably caused by taxes or accounting configurations changes.") }) return { 'name': _("Force Close Session"), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'pos.close.session.wizard', 'res_id': wizard.id, 'target': 'new', 'context': {**self.env.context, 'active_ids': self.ids, 'active_model': 'pos.session'}, } def close_session_from_ui(self, bank_payment_method_diff_pairs=None): """Calling this method will try to close the session. param bank_payment_method_diff_pairs: list[(int, float)] Pairs of payment_method_id and diff_amount which will be used to post loss/profit when closing the session. If successful, it returns {'successful': True} Otherwise, it returns {'successful': False, 'message': str, 'redirect': bool}. 'redirect' is a boolean used to know whether we redirect the user to the back end or not. When necessary, error (i.e. UserError, AccessError) is raised which should redirect the user to the back end. """ bank_payment_method_diffs = dict(bank_payment_method_diff_pairs or []) self.ensure_one() # Even if this is called in `post_closing_cash_details`, we need to call this here too for case # where cash_control = False check_closing_session = self._cannot_close_session(bank_payment_method_diffs) if check_closing_session: return check_closing_session # For now we won't simply do # self._check_pos_session_balance() # self._check_bank_statement_state() # validate_result = self._validate_session() # because some functions are being used and overridden in other modules... # so we'll try to use the original flow as of now for the moment validate_result = self.action_pos_session_closing_control(bank_payment_method_diffs=bank_payment_method_diffs) # If an error is raised, the user will still be redirected to the back end to manually close the session. # If the return result is a dict, this means that normally we have a redirection or a wizard => we redirect the user if isinstance(validate_result, dict): # imbalance accounting entry return { 'successful': False, 'message': validate_result.get('name'), 'redirect': True } self.message_post(body='Point of Sale Session ended') return {'successful': True} def update_closing_control_state_session(self, notes): # Prevent closing the session again if it was already closed if self.state == 'closed': raise UserError(_('This session is already closed.')) # Prevent the session to be opened again. self.write({'state': 'closing_control', 'stop_at': fields.Datetime.now()}) self._post_cash_details_message('Closing', self.cash_register_difference, notes) def post_closing_cash_details(self, counted_cash): """ Calling this method will try store the cash details during the session closing. :param counted_cash: float, the total cash the user counted from its cash register If successful, it returns {'successful': True} Otherwise, it returns {'successful': False, 'message': str, 'redirect': bool}. 'redirect' is a boolean used to know whether we redirect the user to the back end or not. When necessary, error (i.e. UserError, AccessError) is raised which should redirect the user to the back end. """ self.ensure_one() check_closing_session = self._cannot_close_session() if check_closing_session: return check_closing_session if not self.cash_register_id: # The user is blocked anyway, this user error is mostly for developers that try to call this function raise UserError(_("There is no cash register in this session.")) self.cash_register_id.balance_end_real = counted_cash return {'successful': True} def _create_diff_account_move_for_split_payment_method(self, payment_method, diff_amount): self.ensure_one() get_diff_vals_result = self._get_diff_vals(payment_method.id, diff_amount) if not get_diff_vals_result: return source_vals, dest_vals = get_diff_vals_result diff_move = self.env['account.move'].create({ 'journal_id': payment_method.journal_id.id, 'date': fields.Date.context_today(self), 'ref': self._get_diff_account_move_ref(payment_method), 'line_ids': [Command.create(source_vals), Command.create(dest_vals)] }) diff_move._post() def _get_diff_account_move_ref(self, payment_method): return _('Closing difference in %s (%s)', payment_method.name, self.name) def _get_diff_vals(self, payment_method_id, diff_amount): payment_method = self.env['pos.payment.method'].browse(payment_method_id) diff_compare_to_zero = self.currency_id.compare_amounts(diff_amount, 0) source_account = payment_method.outstanding_account_id or self.company_id.account_journal_payment_debit_account_id destination_account = self.env['account.account'] if (diff_compare_to_zero > 0): destination_account = payment_method.journal_id.profit_account_id elif (diff_compare_to_zero < 0): destination_account = payment_method.journal_id.loss_account_id if (diff_compare_to_zero == 0 or not source_account): return False amounts = self._update_amounts({'amount': 0, 'amount_converted': 0}, {'amount': diff_amount}, self.stop_at) source_vals = self._debit_amounts({'account_id': source_account.id}, amounts['amount'], amounts['amount_converted']) dest_vals = self._credit_amounts({'account_id': destination_account.id}, amounts['amount'], amounts['amount_converted']) return [source_vals, dest_vals] def _cannot_close_session(self, bank_payment_method_diffs=None): """ Add check in this method if you want to return or raise an error when trying to either post cash details or close the session. Raising an error will always redirect the user to the back end. It should return {'successful': False, 'message': str, 'redirect': bool} if we can't close the session """ bank_payment_method_diffs = bank_payment_method_diffs or {} if any(order.state == 'draft' for order in self.order_ids): return {'successful': False, 'message': _("You cannot close the POS when orders are still in draft"), 'redirect': False} if self.state == 'closed': return {'successful': False, 'message': _("This session is already closed."), 'redirect': True} if bank_payment_method_diffs: no_loss_account = self.env['account.journal'] no_profit_account = self.env['account.journal'] for payment_method in self.env['pos.payment.method'].browse(bank_payment_method_diffs.keys()): journal = payment_method.journal_id compare_to_zero = self.currency_id.compare_amounts(bank_payment_method_diffs.get(payment_method.id), 0) if compare_to_zero == -1 and not journal.loss_account_id: no_loss_account |= journal elif compare_to_zero == 1 and not journal.profit_account_id: no_profit_account |= journal message = '' if no_loss_account: message += _("Need loss account for the following journals to post the lost amount: %s\n", ', '.join(no_loss_account.mapped('name'))) if no_profit_account: message += _("Need profit account for the following journals to post the gained amount: %s", ', '.join(no_profit_account.mapped('name'))) if message: return {'successful': False, 'message': message, 'redirect': False} def get_closing_control_data(self): if not self.env.user.has_group('point_of_sale.group_pos_user'): raise AccessError(_("You don't have the access rights to get the point of sale closing control data.")) self.ensure_one() orders = self.order_ids.filtered(lambda o: o.state == 'paid' or o.state == 'invoiced') payments = orders.payment_ids.filtered(lambda p: p.payment_method_id.type != "pay_later") pay_later_payments = orders.payment_ids - payments cash_payment_method_ids = self.payment_method_ids.filtered(lambda pm: pm.type == 'cash') default_cash_payment_method_id = cash_payment_method_ids[0] if cash_payment_method_ids else None total_default_cash_payment_amount = sum(payments.filtered(lambda p: p.payment_method_id == default_cash_payment_method_id).mapped('amount')) if default_cash_payment_method_id else 0 other_payment_method_ids = self.payment_method_ids - default_cash_payment_method_id if default_cash_payment_method_id else self.payment_method_ids cash_in_count = 0 cash_out_count = 0 cash_in_out_list = [] for cash_move in self.sudo().cash_register_id.line_ids.sorted('create_date'): if cash_move.amount > 0: cash_in_count += 1 name = f'Cash in {cash_in_count}' else: cash_out_count += 1 name = f'Cash out {cash_out_count}' cash_in_out_list.append({ 'name': cash_move.payment_ref if cash_move.payment_ref else name, 'amount': cash_move.amount }) return { 'orders_details': { 'quantity': len(orders), 'amount': sum(orders.mapped('amount_total')) }, 'payments_amount': sum(payments.mapped('amount')), 'pay_later_amount': sum(pay_later_payments.mapped('amount')), 'opening_notes': self.opening_notes, 'default_cash_details': { 'name': default_cash_payment_method_id.name, 'amount': self.cash_register_id.balance_start + total_default_cash_payment_amount + sum(self.sudo().cash_register_id.line_ids.mapped('amount')), 'opening': self.cash_register_id.balance_start, 'payment_amount': total_default_cash_payment_amount, 'moves': cash_in_out_list, 'id': default_cash_payment_method_id.id } if default_cash_payment_method_id else None, 'other_payment_methods': [{ 'name': pm.name, 'amount': sum(orders.payment_ids.filtered(lambda p: p.payment_method_id == pm).mapped('amount')), 'number': len(orders.payment_ids.filtered(lambda p: p.payment_method_id == pm)), 'id': pm.id, 'type': pm.type, } for pm in other_payment_method_ids], 'is_manager': self.user_has_groups("point_of_sale.group_pos_manager"), 'amount_authorized_diff': self.config_id.amount_authorized_diff if self.config_id.set_maximum_difference else None } def _create_picking_at_end_of_session(self): self.ensure_one() lines_grouped_by_dest_location = {} picking_type = self.config_id.picking_type_id if not picking_type or not picking_type.default_location_dest_id: session_destination_id = self.env['stock.warehouse']._get_partner_locations()[0].id else: session_destination_id = picking_type.default_location_dest_id.id for order in self.order_ids: if order.company_id.anglo_saxon_accounting and order.is_invoiced or order.to_ship: continue destination_id = order.partner_id.property_stock_customer.id or session_destination_id if destination_id in lines_grouped_by_dest_location: lines_grouped_by_dest_location[destination_id] |= order.lines else: lines_grouped_by_dest_location[destination_id] = order.lines for location_dest_id, lines in lines_grouped_by_dest_location.items(): pickings = self.env['stock.picking']._create_picking_from_pos_order_lines(location_dest_id, lines, picking_type) pickings.write({'pos_session_id': self.id, 'origin': self.name}) def _create_balancing_line(self, data, balancing_account, amount_to_balance): if (not float_is_zero(amount_to_balance, precision_rounding=self.currency_id.rounding)): balancing_vals = self._prepare_balancing_line_vals(amount_to_balance, self.move_id, balancing_account) MoveLine = data.get('MoveLine') MoveLine.create(balancing_vals) return data def _prepare_balancing_line_vals(self, imbalance_amount, move, balancing_account): partial_vals = { 'name': _('Difference at closing PoS session'), 'account_id': balancing_account.id, 'move_id': move.id, 'partner_id': False, } # `imbalance_amount` is already in terms of company currency so it is the amount_converted # param when calling `_credit_amounts`. amount param will be the converted value of # `imbalance_amount` from company currency to the session currency. imbalance_amount_session = 0 if (not self.is_in_company_currency): imbalance_amount_session = self.company_id.currency_id._convert(imbalance_amount, self.currency_id, self.company_id, fields.Date.context_today(self)) return self._credit_amounts(partial_vals, imbalance_amount_session, imbalance_amount) def _get_balancing_account(self): propoerty_account = self.env['ir.property']._get('property_account_receivable_id', 'res.partner') return self.company_id.account_default_pos_receivable_account_id or propoerty_account or self.env['account.account'] def _create_account_move(self, balancing_account=False, amount_to_balance=0, bank_payment_method_diffs=None): """ Create account.move and account.move.line records for this session. Side-effects include: - setting self.move_id to the created account.move record - creating and validating account.bank.statement for cash payments - reconciling cash receivable lines, invoice receivable lines and stock output lines """ journal = self.config_id.journal_id # Passing default_journal_id for the calculation of default currency of account move # See _get_default_currency in the account/account_move.py. account_move = self.env['account.move'].with_context(default_journal_id=journal.id).create({ 'journal_id': journal.id, 'date': fields.Date.context_today(self), 'ref': self.name, }) self.write({'move_id': account_move.id}) data = {'bank_payment_method_diffs': bank_payment_method_diffs or {}} data = self._accumulate_amounts(data) data = self._create_non_reconciliable_move_lines(data) data = self._create_bank_payment_moves(data) data = self._create_pay_later_receivable_lines(data) data = self._create_cash_statement_lines_and_cash_move_lines(data) data = self._create_invoice_receivable_lines(data) data = self._create_stock_output_lines(data) if balancing_account and amount_to_balance: data = self._create_balancing_line(data, balancing_account, amount_to_balance) return data def _accumulate_amounts(self, data): # Accumulate the amounts for each accounting lines group # Each dict maps `key` -> `amounts`, where `key` is the group key. # E.g. `combine_receivables_bank` is derived from pos.payment records # in the self.order_ids with group key of the `payment_method_id` # field of the pos.payment record. amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0} tax_amounts = lambda: {'amount': 0.0, 'amount_converted': 0.0, 'base_amount': 0.0, 'base_amount_converted': 0.0} split_receivables_bank = defaultdict(amounts) split_receivables_cash = defaultdict(amounts) split_receivables_pay_later = defaultdict(amounts) combine_receivables_bank = defaultdict(amounts) combine_receivables_cash = defaultdict(amounts) combine_receivables_pay_later = defaultdict(amounts) combine_invoice_receivables = defaultdict(amounts) split_invoice_receivables = defaultdict(amounts) sales = defaultdict(amounts) taxes = defaultdict(tax_amounts) stock_expense = defaultdict(amounts) stock_return = defaultdict(amounts) stock_output = defaultdict(amounts) rounding_difference = {'amount': 0.0, 'amount_converted': 0.0} # Track the receivable lines of the order's invoice payment moves for reconciliation # These receivable lines are reconciled to the corresponding invoice receivable lines # of this session's move_id. combine_inv_payment_receivable_lines = defaultdict(lambda: self.env['account.move.line']) split_inv_payment_receivable_lines = defaultdict(lambda: self.env['account.move.line']) rounded_globally = self.company_id.tax_calculation_rounding_method == 'round_globally' pos_receivable_account = self.company_id.account_default_pos_receivable_account_id currency_rounding = self.currency_id.rounding for order in self.order_ids: order_is_invoiced = order.is_invoiced for payment in order.payment_ids: amount = payment.amount if float_is_zero(amount, precision_rounding=currency_rounding): continue date = payment.payment_date payment_method = payment.payment_method_id is_split_payment = payment.payment_method_id.split_transactions payment_type = payment_method.type # If not pay_later, we create the receivable vals for both invoiced and uninvoiced orders. # Separate the split and aggregated payments. # Moreover, if the order is invoiced, we create the pos receivable vals that will balance the # pos receivable lines from the invoice payments. if payment_type != 'pay_later': if is_split_payment and payment_type == 'cash': split_receivables_cash[payment] = self._update_amounts(split_receivables_cash[payment], {'amount': amount}, date) elif not is_split_payment and payment_type == 'cash': combine_receivables_cash[payment_method] = self._update_amounts(combine_receivables_cash[payment_method], {'amount': amount}, date) elif is_split_payment and payment_type == 'bank': split_receivables_bank[payment] = self._update_amounts(split_receivables_bank[payment], {'amount': amount}, date) elif not is_split_payment and payment_type == 'bank': combine_receivables_bank[payment_method] = self._update_amounts(combine_receivables_bank[payment_method], {'amount': amount}, date) # Create the vals to create the pos receivables that will balance the pos receivables from invoice payment moves. if order_is_invoiced: if is_split_payment: split_inv_payment_receivable_lines[payment] |= payment.account_move_id.line_ids.filtered(lambda line: line.account_id == pos_receivable_account) split_invoice_receivables[payment] = self._update_amounts(split_invoice_receivables[payment], {'amount': payment.amount}, order.date_order) else: combine_inv_payment_receivable_lines[payment_method] |= payment.account_move_id.line_ids.filtered(lambda line: line.account_id == pos_receivable_account) combine_invoice_receivables[payment_method] = self._update_amounts(combine_invoice_receivables[payment_method], {'amount': payment.amount}, order.date_order) # If pay_later, we create the receivable lines. # if split, with partner # Otherwise, it's aggregated (combined) # But only do if order is *not* invoiced because no account move is created for pay later invoice payments. if payment_type == 'pay_later' and not order_is_invoiced: if is_split_payment: split_receivables_pay_later[payment] = self._update_amounts(split_receivables_pay_later[payment], {'amount': amount}, date) elif not is_split_payment: combine_receivables_pay_later[payment_method] = self._update_amounts(combine_receivables_pay_later[payment_method], {'amount': amount}, date) if not order_is_invoiced: order_taxes = defaultdict(tax_amounts) for order_line in order.lines: line = self._prepare_line(order_line) # Combine sales/refund lines sale_key = ( # account line['income_account_id'], # sign -1 if line['amount'] < 0 else 1, # for taxes tuple((tax['id'], tax['account_id'], tax['tax_repartition_line_id']) for tax in line['taxes']), line['base_tags'], ) sales[sale_key] = self._update_amounts(sales[sale_key], {'amount': line['amount']}, line['date_order']) # Combine tax lines for tax in line['taxes']: tax_key = (tax['account_id'] or line['income_account_id'], tax['tax_repartition_line_id'], tax['id'], tuple(tax['tag_ids'])) order_taxes[tax_key] = self._update_amounts( order_taxes[tax_key], {'amount': tax['amount'], 'base_amount': tax['base']}, tax['date_order'], round=not rounded_globally ) for tax_key, amounts in order_taxes.items(): if rounded_globally: amounts = self._round_amounts(amounts) for amount_key, amount in amounts.items(): taxes[tax_key][amount_key] += amount if self.company_id.anglo_saxon_accounting and order.picking_ids.ids: # Combine stock lines stock_moves = self.env['stock.move'].sudo().search([ ('picking_id', 'in', order.picking_ids.ids), ('company_id.anglo_saxon_accounting', '=', True), ('product_id.categ_id.property_valuation', '=', 'real_time') ]) for move in stock_moves: exp_key = move.product_id._get_product_accounts()['expense'] out_key = move.product_id.categ_id.property_stock_account_output_categ_id signed_product_qty = move.product_qty if move._is_in(): signed_product_qty *= -1 amount = signed_product_qty * move.product_id._compute_average_price(0, move.quantity_done, move) stock_expense[exp_key] = self._update_amounts(stock_expense[exp_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) if move._is_in(): stock_return[out_key] = self._update_amounts(stock_return[out_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) else: stock_output[out_key] = self._update_amounts(stock_output[out_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) if self.config_id.cash_rounding: diff = order.amount_paid - order.amount_total rounding_difference = self._update_amounts(rounding_difference, {'amount': diff}, order.date_order) # Increasing current partner's customer_rank partners = (order.partner_id | order.partner_id.commercial_partner_id) partners._increase_rank('customer_rank') if self.company_id.anglo_saxon_accounting: global_session_pickings = self.picking_ids.filtered(lambda p: not p.pos_order_id) if global_session_pickings: stock_moves = self.env['stock.move'].sudo().search([ ('picking_id', 'in', global_session_pickings.ids), ('company_id.anglo_saxon_accounting', '=', True), ('product_id.categ_id.property_valuation', '=', 'real_time'), ]) for move in stock_moves: exp_key = move.product_id._get_product_accounts()['expense'] out_key = move.product_id.categ_id.property_stock_account_output_categ_id signed_product_qty = move.product_qty if move._is_in(): signed_product_qty *= -1 amount = signed_product_qty * move.product_id._compute_average_price(0, move.quantity_done, move) stock_expense[exp_key] = self._update_amounts(stock_expense[exp_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) if move._is_in(): stock_return[out_key] = self._update_amounts(stock_return[out_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) else: stock_output[out_key] = self._update_amounts(stock_output[out_key], {'amount': amount}, move.picking_id.date, force_company_currency=True) MoveLine = self.env['account.move.line'].with_context(check_move_validity=False) data.update({ 'taxes': taxes, 'sales': sales, 'stock_expense': stock_expense, 'split_receivables_bank': split_receivables_bank, 'combine_receivables_bank': combine_receivables_bank, 'split_receivables_cash': split_receivables_cash, 'combine_receivables_cash': combine_receivables_cash, 'combine_invoice_receivables': combine_invoice_receivables, 'split_receivables_pay_later': split_receivables_pay_later, 'combine_receivables_pay_later': combine_receivables_pay_later, 'stock_return': stock_return, 'stock_output': stock_output, 'combine_inv_payment_receivable_lines': combine_inv_payment_receivable_lines, 'rounding_difference': rounding_difference, 'MoveLine': MoveLine, 'split_invoice_receivables': split_invoice_receivables, 'split_inv_payment_receivable_lines': split_inv_payment_receivable_lines, }) return data def _create_non_reconciliable_move_lines(self, data): # Create account.move.line records for # - sales # - taxes # - stock expense # - non-cash split receivables (not for automatic reconciliation) # - non-cash combine receivables (not for automatic reconciliation) taxes = data.get('taxes') sales = data.get('sales') stock_expense = data.get('stock_expense') rounding_difference = data.get('rounding_difference') MoveLine = data.get('MoveLine') tax_vals = [self._get_tax_vals(key, amounts['amount'], amounts['amount_converted'], amounts['base_amount_converted']) for key, amounts in taxes.items()] # Check if all taxes lines have account_id assigned. If not, there are repartition lines of the tax that have no account_id. tax_names_no_account = [line['name'] for line in tax_vals if line['account_id'] == False] if len(tax_names_no_account) > 0: error_message = _( 'Unable to close and validate the session.\n' 'Please set corresponding tax account in each repartition line of the following taxes: \n%s' ) % ', '.join(tax_names_no_account) raise UserError(error_message) rounding_vals = [] if not float_is_zero(rounding_difference['amount'], precision_rounding=self.currency_id.rounding) or not float_is_zero(rounding_difference['amount_converted'], precision_rounding=self.currency_id.rounding): rounding_vals = [self._get_rounding_difference_vals(rounding_difference['amount'], rounding_difference['amount_converted'])] MoveLine.create( tax_vals + [self._get_sale_vals(key, amounts['amount'], amounts['amount_converted']) for key, amounts in sales.items()] + [self._get_stock_expense_vals(key, amounts['amount'], amounts['amount_converted']) for key, amounts in stock_expense.items()] + rounding_vals ) return data def _create_bank_payment_moves(self, data): combine_receivables_bank = data.get('combine_receivables_bank') split_receivables_bank = data.get('split_receivables_bank') bank_payment_method_diffs = data.get('bank_payment_method_diffs') MoveLine = data.get('MoveLine') payment_method_to_receivable_lines = {} payment_to_receivable_lines = {} for payment_method, amounts in combine_receivables_bank.items(): combine_receivable_line = MoveLine.create(self._get_combine_receivable_vals(payment_method, amounts['amount'], amounts['amount_converted'])) payment_receivable_line = self._create_combine_account_payment(payment_method, amounts, diff_amount=bank_payment_method_diffs.get(payment_method.id) or 0) payment_method_to_receivable_lines[payment_method] = combine_receivable_line | payment_receivable_line for payment, amounts in split_receivables_bank.items(): split_receivable_line = MoveLine.create(self._get_split_receivable_vals(payment, amounts['amount'], amounts['amount_converted'])) payment_receivable_line = self._create_split_account_payment(payment, amounts) payment_to_receivable_lines[payment] = split_receivable_line | payment_receivable_line for bank_payment_method in self.payment_method_ids.filtered(lambda pm: pm.type == 'bank' and pm.split_transactions): self._create_diff_account_move_for_split_payment_method(bank_payment_method, bank_payment_method_diffs.get(bank_payment_method.id) or 0) data['payment_method_to_receivable_lines'] = payment_method_to_receivable_lines data['payment_to_receivable_lines'] = payment_to_receivable_lines return data def _create_pay_later_receivable_lines(self, data): MoveLine = data.get('MoveLine') combine_receivables_pay_later = data.get('combine_receivables_pay_later') split_receivables_pay_later = data.get('split_receivables_pay_later') vals = [] for payment_method, amounts in combine_receivables_pay_later.items(): vals.append(self._get_combine_receivable_vals(payment_method, amounts['amount'], amounts['amount_converted'])) for payment, amounts in split_receivables_pay_later.items(): vals.append(self._get_split_receivable_vals(payment, amounts['amount'], amounts['amount_converted'])) MoveLine.create(vals) return data def _create_combine_account_payment(self, payment_method, amounts, diff_amount): outstanding_account = payment_method.outstanding_account_id or self.company_id.account_journal_payment_debit_account_id destination_account = self._get_receivable_account(payment_method) if float_compare(amounts['amount'], 0, precision_rounding=self.currency_id.rounding) < 0: # revert the accounts because account.payment doesn't accept negative amount. outstanding_account, destination_account = destination_account, outstanding_account account_payment = self.env['account.payment'].create({ 'amount': abs(amounts['amount']), 'journal_id': payment_method.journal_id.id, 'force_outstanding_account_id': outstanding_account.id, 'destination_account_id': destination_account.id, 'ref': _('Combine %s POS payments from %s') % (payment_method.name, self.name), 'pos_payment_method_id': payment_method.id, 'pos_session_id': self.id, }) diff_amount_compare_to_zero = self.currency_id.compare_amounts(diff_amount, 0) if diff_amount_compare_to_zero != 0: self._apply_diff_on_account_payment_move(account_payment, payment_method, diff_amount) account_payment.action_post() return account_payment.move_id.line_ids.filtered(lambda line: line.account_id == account_payment.destination_account_id) def _apply_diff_on_account_payment_move(self, account_payment, payment_method, diff_amount): source_vals, dest_vals = self._get_diff_vals(payment_method.id, diff_amount) outstanding_line = account_payment.move_id.line_ids.filtered(lambda line: line.account_id.id == source_vals['account_id']) new_balance = outstanding_line.balance + diff_amount new_balance_compare_to_zero = self.currency_id.compare_amounts(new_balance, 0) account_payment.move_id.write({ 'line_ids': [ Command.create(dest_vals), Command.update(outstanding_line.id, { 'debit': new_balance_compare_to_zero > 0 and new_balance or 0.0, 'credit': new_balance_compare_to_zero < 0 and -new_balance or 0.0 }) ] }) def _create_split_account_payment(self, payment, amounts): payment_method = payment.payment_method_id if not payment_method.journal_id: return self.env['account.move.line'] outstanding_account = payment_method.outstanding_account_id or self.company_id.account_journal_payment_debit_account_id accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) destination_account = accounting_partner.property_account_receivable_id if float_compare(amounts['amount'], 0, precision_rounding=self.currency_id.rounding) < 0: # revert the accounts because account.payment doesn't accept negative amount. outstanding_account, destination_account = destination_account, outstanding_account account_payment = self.env['account.payment'].create({ 'amount': abs(amounts['amount']), 'partner_id': payment.partner_id.id, 'journal_id': payment_method.journal_id.id, 'force_outstanding_account_id': outstanding_account.id, 'destination_account_id': destination_account.id, 'ref': _('%s POS payment of %s in %s') % (payment_method.name, payment.partner_id.display_name, self.name), 'pos_payment_method_id': payment_method.id, 'pos_session_id': self.id, }) account_payment.action_post() return account_payment.move_id.line_ids.filtered(lambda line: line.account_id == account_payment.destination_account_id) def _create_cash_statement_lines_and_cash_move_lines(self, data): # Create the split and combine cash statement lines and account move lines. # Keep the reference by statement for reconciliation. # `split_cash_statement_lines` maps `statement` -> split cash statement lines # `combine_cash_statement_lines` maps `statement` -> combine cash statement lines # `split_cash_receivable_lines` maps `statement` -> split cash receivable lines # `combine_cash_receivable_lines` maps `statement` -> combine cash receivable lines MoveLine = data.get('MoveLine') split_receivables_cash = data.get('split_receivables_cash') combine_receivables_cash = data.get('combine_receivables_cash') statements_by_journal_id = {statement.journal_id.id: statement for statement in self.statement_ids} # handle split cash payments split_cash_statement_line_vals = defaultdict(list) split_cash_receivable_vals = defaultdict(list) for payment, amounts in split_receivables_cash.items(): statement = statements_by_journal_id[payment.payment_method_id.journal_id.id] split_cash_statement_line_vals[statement].append(self._get_split_statement_line_vals(statement, amounts['amount'], payment)) split_cash_receivable_vals[statement].append(self._get_split_receivable_vals(payment, amounts['amount'], amounts['amount_converted'])) # handle combine cash payments combine_cash_statement_line_vals = defaultdict(list) combine_cash_receivable_vals = defaultdict(list) for payment_method, amounts in combine_receivables_cash.items(): if not float_is_zero(amounts['amount'] , precision_rounding=self.currency_id.rounding): statement = statements_by_journal_id[payment_method.journal_id.id] combine_cash_statement_line_vals[statement].append(self._get_combine_statement_line_vals(statement, amounts['amount'], payment_method)) combine_cash_receivable_vals[statement].append(self._get_combine_receivable_vals(payment_method, amounts['amount'], amounts['amount_converted'])) # create the statement lines and account move lines BankStatementLine = self.env['account.bank.statement.line'] split_cash_statement_lines = {} combine_cash_statement_lines = {} split_cash_receivable_lines = {} combine_cash_receivable_lines = {} for statement in self.statement_ids: split_cash_statement_lines[statement] = BankStatementLine.create(split_cash_statement_line_vals[statement]).mapped('move_id.line_ids').filtered(lambda line: line.account_id.internal_type == 'receivable') combine_cash_statement_lines[statement] = BankStatementLine.create(combine_cash_statement_line_vals[statement]).mapped('move_id.line_ids').filtered(lambda line: line.account_id.internal_type == 'receivable') split_cash_receivable_lines[statement] = MoveLine.create(split_cash_receivable_vals[statement]) combine_cash_receivable_lines[statement] = MoveLine.create(combine_cash_receivable_vals[statement]) data.update( {'split_cash_statement_lines': split_cash_statement_lines, 'combine_cash_statement_lines': combine_cash_statement_lines, 'split_cash_receivable_lines': split_cash_receivable_lines, 'combine_cash_receivable_lines': combine_cash_receivable_lines }) return data def _create_invoice_receivable_lines(self, data): # Create invoice receivable lines for this session's move_id. # Keep reference of the invoice receivable lines because # they are reconciled with the lines in combine_inv_payment_receivable_lines MoveLine = data.get('MoveLine') combine_invoice_receivables = data.get('combine_invoice_receivables') split_invoice_receivables = data.get('split_invoice_receivables') combine_invoice_receivable_vals = defaultdict(list) split_invoice_receivable_vals = defaultdict(list) combine_invoice_receivable_lines = {} split_invoice_receivable_lines = {} for payment_method, amounts in combine_invoice_receivables.items(): combine_invoice_receivable_vals[payment_method].append(self._get_invoice_receivable_vals(amounts['amount'], amounts['amount_converted'])) for payment, amounts in split_invoice_receivables.items(): split_invoice_receivable_vals[payment].append(self._get_invoice_receivable_vals(amounts['amount'], amounts['amount_converted'])) for payment_method, vals in combine_invoice_receivable_vals.items(): receivable_lines = MoveLine.create(vals) combine_invoice_receivable_lines[payment_method] = receivable_lines for payment, vals in split_invoice_receivable_vals.items(): receivable_lines = MoveLine.create(vals) split_invoice_receivable_lines[payment] = receivable_lines data.update({'combine_invoice_receivable_lines': combine_invoice_receivable_lines}) data.update({'split_invoice_receivable_lines': split_invoice_receivable_lines}) return data def _create_stock_output_lines(self, data): # Keep reference to the stock output lines because # they are reconciled with output lines in the stock.move's account.move.line MoveLine = data.get('MoveLine') stock_output = data.get('stock_output') stock_return = data.get('stock_return') stock_output_vals = defaultdict(list) stock_output_lines = {} for stock_moves in [stock_output, stock_return]: for account, amounts in stock_moves.items(): stock_output_vals[account].append(self._get_stock_output_vals(account, amounts['amount'], amounts['amount_converted'])) for output_account, vals in stock_output_vals.items(): stock_output_lines[output_account] = MoveLine.create(vals) data.update({'stock_output_lines': stock_output_lines}) return data def _reconcile_account_move_lines(self, data): # reconcile cash receivable lines split_cash_statement_lines = data.get('split_cash_statement_lines') combine_cash_statement_lines = data.get('combine_cash_statement_lines') split_cash_receivable_lines = data.get('split_cash_receivable_lines') combine_cash_receivable_lines = data.get('combine_cash_receivable_lines') combine_inv_payment_receivable_lines = data.get('combine_inv_payment_receivable_lines') split_inv_payment_receivable_lines = data.get('split_inv_payment_receivable_lines') combine_invoice_receivable_lines = data.get('combine_invoice_receivable_lines') split_invoice_receivable_lines = data.get('split_invoice_receivable_lines') stock_output_lines = data.get('stock_output_lines') payment_method_to_receivable_lines = data.get('payment_method_to_receivable_lines') payment_to_receivable_lines = data.get('payment_to_receivable_lines') for statement in self.statement_ids: if not self.config_id.cash_control: statement.write({'balance_end_real': statement.balance_end}) statement.button_post() all_lines = ( split_cash_statement_lines[statement] | combine_cash_statement_lines[statement] | split_cash_receivable_lines[statement] | combine_cash_receivable_lines[statement] ) accounts = all_lines.mapped('account_id') lines_by_account = [all_lines.filtered(lambda l: l.account_id == account and not l.reconciled) for account in accounts if account.reconcile] for lines in lines_by_account: lines.reconcile() # We try to validate the statement after the reconciliation is done # because validating the statement requires each statement line to be # reconciled. # Furthermore, if the validation failed, which is caused by unreconciled # cash difference statement line, we just ignore that. Leaving the statement # not yet validated. Manual reconciliation and validation should be made # by the user in the accounting app. try: statement.button_validate() except UserError: pass for payment_method, lines in payment_method_to_receivable_lines.items(): receivable_account = self._get_receivable_account(payment_method) if receivable_account.reconcile: lines.filtered(lambda line: not line.reconciled).reconcile() for payment, lines in payment_to_receivable_lines.items(): if payment.partner_id.property_account_receivable_id.reconcile: lines.filtered(lambda line: not line.reconciled).reconcile() # Reconcile invoice payments' receivable lines. But we only do when the account is reconcilable. # Though `account_default_pos_receivable_account_id` should be of type receivable, there is currently # no constraint for it. Therefore, it is possible to put set a non-reconcilable account to it. if self.company_id.account_default_pos_receivable_account_id.reconcile: for payment_method in combine_inv_payment_receivable_lines: lines = combine_inv_payment_receivable_lines[payment_method] | combine_invoice_receivable_lines.get(payment_method, self.env['account.move.line']) lines.filtered(lambda line: not line.reconciled).reconcile() for payment in split_inv_payment_receivable_lines: lines = split_inv_payment_receivable_lines[payment] | split_invoice_receivable_lines.get(payment, self.env['account.move.line']) lines.filtered(lambda line: not line.reconciled).reconcile() # reconcile stock output lines pickings = self.picking_ids.filtered(lambda p: not p.pos_order_id) pickings |= self.order_ids.filtered(lambda o: not o.is_invoiced).mapped('picking_ids') stock_moves = self.env['stock.move'].search([('picking_id', 'in', pickings.ids)]) stock_account_move_lines = self.env['account.move'].search([('stock_move_id', 'in', stock_moves.ids)]).mapped('line_ids') for account_id in stock_output_lines: ( stock_output_lines[account_id] | stock_account_move_lines.filtered(lambda aml: aml.account_id == account_id) ).filtered(lambda aml: not aml.reconciled).reconcile() return data def _prepare_line(self, order_line): """ Derive from order_line the order date, income account, amount and taxes information. These information will be used in accumulating the amounts for sales and tax lines. """ def get_income_account(order_line): product = order_line.product_id income_account = product.with_company(order_line.company_id)._get_product_accounts()['income'] or self.config_id.journal_id.default_account_id if not income_account: raise UserError(_('Please define income account for this product: "%s" (id:%d).') % (product.name, product.id)) return order_line.order_id.fiscal_position_id.map_account(income_account) tax_ids = order_line.tax_ids_after_fiscal_position\ .filtered(lambda t: t.company_id.id == order_line.order_id.company_id.id) sign = -1 if order_line.qty >= 0 else 1 price = sign * order_line.price_unit * (1 - (order_line.discount or 0.0) / 100.0) # The 'is_refund' parameter is used to compute the tax tags. Ultimately, the tags are part # of the key used for summing taxes. Since the POS UI doesn't support the tags, inconsistencies # may arise in 'Round Globally'. check_refund = lambda x: x.qty * x.price_unit < 0 is_refund = check_refund(order_line) tax_data = tax_ids.with_context(force_sign=sign).compute_all(price_unit=price, quantity=abs(order_line.qty), currency=self.currency_id, is_refund=is_refund) taxes = tax_data['taxes'] # For Cash based taxes, use the account from the repartition line immediately as it has been paid already for tax in taxes: tax_rep = self.env['account.tax.repartition.line'].browse(tax['tax_repartition_line_id']) tax['account_id'] = tax_rep.account_id.id date_order = order_line.order_id.date_order taxes = [{'date_order': date_order, **tax} for tax in taxes] return { 'date_order': order_line.order_id.date_order, 'income_account_id': get_income_account(order_line).id, 'amount': order_line.price_subtotal, 'taxes': taxes, 'base_tags': tuple(tax_data['base_tags']), } def _get_rounding_difference_vals(self, amount, amount_converted): if self.config_id.cash_rounding: partial_args = { 'name': 'Rounding line', 'move_id': self.move_id.id, } if float_compare(0.0, amount, precision_rounding=self.currency_id.rounding) > 0: # loss partial_args['account_id'] = self.config_id.rounding_method.loss_account_id.id return self._debit_amounts(partial_args, -amount, -amount_converted) if float_compare(0.0, amount, precision_rounding=self.currency_id.rounding) < 0: # profit partial_args['account_id'] = self.config_id.rounding_method.profit_account_id.id return self._credit_amounts(partial_args, amount, amount_converted) def _get_split_receivable_vals(self, payment, amount, amount_converted): accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) if not accounting_partner: raise UserError(_("You have enabled the \"Identify Customer\" option for %s payment method," "but the order %s does not contain a customer.") % (payment.payment_method_id.name, payment.pos_order_id.name)) partial_vals = { 'account_id': accounting_partner.property_account_receivable_id.id, 'move_id': self.move_id.id, 'partner_id': accounting_partner.id, 'name': '%s - %s' % (self.name, payment.payment_method_id.name), } return self._debit_amounts(partial_vals, amount, amount_converted) def _get_combine_receivable_vals(self, payment_method, amount, amount_converted): partial_vals = { 'account_id': self._get_receivable_account(payment_method).id, 'move_id': self.move_id.id, 'name': '%s - %s' % (self.name, payment_method.name) } return self._debit_amounts(partial_vals, amount, amount_converted) def _get_invoice_receivable_vals(self, amount, amount_converted): partial_vals = { 'account_id': self.company_id.account_default_pos_receivable_account_id.id, 'move_id': self.move_id.id, 'name': _('From invoice payments'), } return self._credit_amounts(partial_vals, amount, amount_converted) def _get_sale_vals(self, key, amount, amount_converted): account_id, sign, tax_keys, base_tag_ids = key tax_ids = set(tax[0] for tax in tax_keys) applied_taxes = self.env['account.tax'].browse(tax_ids) title = 'Sales' if sign == 1 else 'Refund' name = '%s untaxed' % title if applied_taxes: name = '%s with %s' % (title, ', '.join([tax.name for tax in applied_taxes])) partial_vals = { 'name': name, 'account_id': account_id, 'move_id': self.move_id.id, 'tax_ids': [(6, 0, tax_ids)], 'tax_tag_ids': [(6, 0, base_tag_ids)], } return self._credit_amounts(partial_vals, amount, amount_converted) def _get_tax_vals(self, key, amount, amount_converted, base_amount_converted): account_id, repartition_line_id, tax_id, tag_ids = key tax = self.env['account.tax'].browse(tax_id) partial_args = { 'name': tax.name, 'account_id': account_id, 'move_id': self.move_id.id, 'tax_base_amount': abs(base_amount_converted), 'tax_repartition_line_id': repartition_line_id, 'tax_tag_ids': [(6, 0, tag_ids)], } return self._debit_amounts(partial_args, amount, amount_converted) def _get_stock_expense_vals(self, exp_account, amount, amount_converted): partial_args = {'account_id': exp_account.id, 'move_id': self.move_id.id} return self._debit_amounts(partial_args, amount, amount_converted, force_company_currency=True) def _get_stock_output_vals(self, out_account, amount, amount_converted): partial_args = {'account_id': out_account.id, 'move_id': self.move_id.id} return self._credit_amounts(partial_args, amount, amount_converted, force_company_currency=True) def _get_combine_statement_line_vals(self, statement, amount, payment_method): return { 'date': fields.Date.context_today(self), 'amount': amount, 'payment_ref': self.name, 'statement_id': statement.id, 'journal_id': statement.journal_id.id, 'counterpart_account_id': self._get_receivable_account(payment_method).id, } def _get_split_statement_line_vals(self, statement, amount, payment): accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) return { 'date': fields.Date.context_today(self, timestamp=payment.payment_date), 'amount': amount, 'payment_ref': self.name, 'statement_id': statement.id, 'journal_id': statement.journal_id.id, 'counterpart_account_id': accounting_partner.property_account_receivable_id.id, 'partner_id': accounting_partner.id, } def _update_amounts(self, old_amounts, amounts_to_add, date, round=True, force_company_currency=False): """Responsible for adding `amounts_to_add` to `old_amounts` considering the currency of the session. old_amounts { new_amounts { amount amounts_to_add { amount amount_converted + amount -> amount_converted [base_amount [base_amount] [base_amount base_amount_converted] } base_amount_converted] } } NOTE: - Notice that `amounts_to_add` does not have `amount_converted` field. This function is responsible in calculating the `amount_converted` from the `amount` of `amounts_to_add` which is used to update the values of `old_amounts`. - Values of `amount` and/or `base_amount` should always be in session's currency [1]. - Value of `amount_converted` should be in company's currency [1] Except when `force_company_currency` = True. It means that values in `amounts_to_add` is in company currency. :params old_amounts dict: Amounts to update :params amounts_to_add dict: Amounts used to update the old_amounts :params date date: Date used for conversion :params round bool: Same as round parameter of `res.currency._convert`. Defaults to True because that is the default of `res.currency._convert`. We put it to False if we want to round globally. :params force_company_currency bool: If True, the values in amounts_to_add are in company's currency. Defaults to False because it is only used to anglo-saxon lines. :return dict: new amounts combining the values of `old_amounts` and `amounts_to_add`. """ # make a copy of the old amounts new_amounts = { **old_amounts } amount = amounts_to_add.get('amount') if self.is_in_company_currency or force_company_currency: amount_converted = amount else: amount_converted = self._amount_converter(amount, date, round) # update amount and amount converted new_amounts['amount'] += amount new_amounts['amount_converted'] += amount_converted # consider base_amount if present if not amounts_to_add.get('base_amount') == None: base_amount = amounts_to_add.get('base_amount') if self.is_in_company_currency or force_company_currency: base_amount_converted = base_amount else: base_amount_converted = self._amount_converter(base_amount, date, round) # update base_amount and base_amount_converted new_amounts['base_amount'] += base_amount new_amounts['base_amount_converted'] += base_amount_converted return new_amounts def _round_amounts(self, amounts): new_amounts = {} for key, amount in amounts.items(): if key == 'amount_converted': # round the amount_converted using the company currency. new_amounts[key] = self.company_id.currency_id.round(amount) else: new_amounts[key] = self.currency_id.round(amount) return new_amounts def _credit_amounts(self, partial_move_line_vals, amount, amount_converted, force_company_currency=False): """ `partial_move_line_vals` is completed by `credit`ing the given amounts. NOTE Amounts in PoS are in the currency of journal_id in the session.config_id. This means that amount fields in any pos record are actually equivalent to amount_currency in account module. Understanding this basic is important in correctly assigning values for 'amount' and 'amount_currency' in the account.move.line record. :param partial_move_line_vals dict: initial values in creating account.move.line :param amount float: amount derived from pos.payment, pos.order, or pos.order.line records :param amount_converted float: converted value of `amount` from the given `session_currency` to company currency :return dict: complete values for creating 'amount.move.line' record """ if self.is_in_company_currency or force_company_currency: additional_field = {} else: additional_field = { 'amount_currency': -amount, 'currency_id': self.currency_id.id, } return { 'debit': -amount_converted if amount_converted < 0.0 else 0.0, 'credit': amount_converted if amount_converted > 0.0 else 0.0, **partial_move_line_vals, **additional_field, } def _debit_amounts(self, partial_move_line_vals, amount, amount_converted, force_company_currency=False): """ `partial_move_line_vals` is completed by `debit`ing the given amounts. See _credit_amounts docs for more details. """ if self.is_in_company_currency or force_company_currency: additional_field = {} else: additional_field = { 'amount_currency': amount, 'currency_id': self.currency_id.id, } return { 'debit': amount_converted if amount_converted > 0.0 else 0.0, 'credit': -amount_converted if amount_converted < 0.0 else 0.0, **partial_move_line_vals, **additional_field, } def _amount_converter(self, amount, date, round): # self should be single record as this method is only called in the subfunctions of self._validate_session return self.currency_id._convert(amount, self.company_id.currency_id, self.company_id, date, round=round) def show_cash_register(self): return { 'name': _('Cash register for %s') % (self.cash_register_id.name, ), 'type': 'ir.actions.act_window', 'res_model': 'account.bank.statement', 'view_mode': 'form', 'res_id': self.cash_register_id.id, } def show_journal_items(self): self.ensure_one() all_related_moves = self._get_related_account_moves() return { 'name': _('Journal Items'), 'type': 'ir.actions.act_window', 'res_model': 'account.move.line', 'view_mode': 'tree', 'view_id':self.env.ref('account.view_move_line_tree_grouped').id, 'domain': [('id', 'in', all_related_moves.mapped('line_ids').ids)], 'context': { 'journal_type':'general', 'search_default_group_by_move': 1, 'group_by':'move_id', 'search_default_posted':1, 'name_groupby':1, }, } def _get_other_related_moves(self): # TODO This is not an ideal way to get the diff account.move's for # the session. It would be better if there is a relation field where # these moves are saved. # Unfortunately, the 'ref' of account.move is not indexed, so # we are querying over the account.move.line because its 'ref' is indexed. # And yes, we are only concern for split bank payment methods. diff_lines_ref = [self._get_diff_account_move_ref(pm) for pm in self.payment_method_ids if pm.type == 'bank' and pm.split_transactions] diff_lines_ref.append("Opening Balance difference for %s" % (self.name)) return self.env['account.move.line'].search([('ref', 'in', diff_lines_ref)]).mapped('move_id') def _get_related_account_moves(self): pickings = self.picking_ids | self.order_ids.mapped('picking_ids') invoices = self.mapped('order_ids.account_move') invoice_payments = self.mapped('order_ids.payment_ids.account_move_id') stock_account_moves = pickings.mapped('move_lines.account_move_ids') cash_moves = self.cash_register_id.line_ids.mapped('move_id') bank_payment_moves = self.bank_payment_ids.mapped('move_id') other_related_moves = self._get_other_related_moves() return invoices | invoice_payments | self.move_id | stock_account_moves | cash_moves | bank_payment_moves | other_related_moves def _get_receivable_account(self, payment_method): """Returns the default pos receivable account if no receivable_account_id is set on the payment method.""" return payment_method.receivable_account_id or self.company_id.account_default_pos_receivable_account_id def action_show_payments_list(self): return { 'name': _('Payments'), 'type': 'ir.actions.act_window', 'res_model': 'pos.payment', 'view_mode': 'tree,form', 'domain': [('session_id', '=', self.id)], 'context': {'search_default_group_by_payment_method': 1} } def open_frontend_cb(self): """Open the pos interface with config_id as an extra argument. In vanilla PoS each user can only have one active session, therefore it was not needed to pass the config_id on opening a session. It is also possible to login to sessions created by other users. :returns: dict """ if not self.ids: return {} return { 'type': 'ir.actions.act_url', 'target': 'self', 'url': self.config_id._get_pos_base_url() + '?config_id=%d' % self.config_id.id, } def set_cashbox_pos(self, cashbox_value, notes): if not self.env.user.has_group('point_of_sale.group_pos_user'): raise AccessError(_("You don't have the access rights to set the point of sale cash box.")) self.state = 'opened' self.opening_notes = notes difference = cashbox_value - self.cash_register_id.balance_start self._post_cash_details_message('Opening', difference, notes) #if there is a difference create an account move to register the loss if difference: self.env['account.bank.statement.line'].sudo().create({ 'payment_ref': 'Opening Balance difference for %s' % (self.name), 'journal_id': self.cash_register_id.journal_id.id, 'date': self.start_at, 'amount': difference, 'statement_id': self.cash_register_id.id, }) def _post_cash_details_message(self, state, difference, notes): message = "" if difference: message = f"{state} difference: " \ f"{self.currency_id.symbol + ' ' if self.currency_id.position == 'before' else ''}" \ f"{self.currency_id.round(difference)} " \ f"{self.currency_id.symbol if self.currency_id.position == 'after' else ''}<br/>" if notes: message += notes.replace('\n', '<br/>') if message: self.env['mail.message'].create({ 'body': message, 'model': 'account.bank.statement', 'res_id': self.cash_register_id.id, }) self.message_post(body=message) def action_view_order(self): return { 'name': _('Orders'), 'res_model': 'pos.order', 'view_mode': 'tree,form', 'views': [ (self.env.ref('point_of_sale.view_pos_order_tree_no_session_id').id, 'tree'), (self.env.ref('point_of_sale.view_pos_pos_form').id, 'form'), ], 'type': 'ir.actions.act_window', 'domain': [('session_id', 'in', self.ids)], } @api.model def _alert_old_session(self): # If the session is open for more then one week, # log a next activity to close the session. sessions = self.sudo().search([('start_at', '<=', (fields.datetime.now() - timedelta(days=7))), ('state', '!=', 'closed')]) for session in sessions: if self.env['mail.activity'].search_count([('res_id', '=', session.id), ('res_model', '=', 'pos.session')]) == 0: session.activity_schedule( 'point_of_sale.mail_activity_old_session', user_id=session.user_id.id, note=_( "Your PoS Session is open since %(date)s, we advise you to close it and to create a new one.", date=session.start_at, ) ) def _check_if_no_draft_orders(self): draft_orders = self.order_ids.filtered(lambda order: order.state == 'draft') if draft_orders: raise UserError(_( 'There are still orders in draft state in the session. ' 'Pay or cancel the following orders to validate the session:\n%s' ) % ', '.join(draft_orders.mapped('name')) ) return True def try_cash_in_out(self, _type, amount, reason, extras): sign = 1 if _type == 'in' else -1 self.env['cash.box.out']\ .with_context({'active_model': 'pos.session', 'active_ids': self.ids})\ .create({'amount': sign * amount, 'name': reason})\ .run() message_content = [f"Cash {extras['translatedType']}", f'- Amount: {extras["formattedAmount"]}'] if reason: message_content.append(f'- Reason: {reason}') self.message_post(body='<br/>\n'.join(message_content)) class ProcurementGroup(models.Model): _inherit = 'procurement.group' @api.model def _run_scheduler_tasks(self, use_new_cursor=False, company_id=False): super(ProcurementGroup, self)._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) self.env['pos.session']._alert_old_session() if use_new_cursor: self.env.cr.commit()
56.546944
89,740
41,219
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from uuid import uuid4 import pytz from odoo import api, fields, models, tools, _ from odoo.exceptions import ValidationError, UserError class PosConfig(models.Model): _name = 'pos.config' _description = 'Point of Sale Configuration' def _default_warehouse_id(self): return self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1).id def _default_picking_type_id(self): return self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1).pos_type_id.id def _default_sale_journal(self): return self.env['account.journal'].search([('type', 'in', ('sale', 'general')), ('company_id', '=', self.env.company.id), ('code', '=', 'POSS')], limit=1) def _default_invoice_journal(self): return self.env['account.journal'].search([('type', '=', 'sale'), ('company_id', '=', self.env.company.id)], limit=1) def _default_payment_methods(self): domain = [('split_transactions', '=', False), ('company_id', '=', self.env.company.id)] non_cash_pm = self.env['pos.payment.method'].search(domain + [('is_cash_count', '=', False)]) available_cash_pm = self.env['pos.payment.method'].search(domain + [('is_cash_count', '=', True), ('config_ids', '=', False)], limit=1) return non_cash_pm | available_cash_pm def _default_pricelist(self): return self.env['product.pricelist'].search([('company_id', 'in', (False, self.env.company.id)), ('currency_id', '=', self.env.company.currency_id.id)], limit=1) def _get_group_pos_manager(self): return self.env.ref('point_of_sale.group_pos_manager') def _get_group_pos_user(self): return self.env.ref('point_of_sale.group_pos_user') name = fields.Char(string='Point of Sale', index=True, required=True, help="An internal identification of the point of sale.") is_installed_account_accountant = fields.Boolean(string="Is the Full Accounting Installed", compute="_compute_is_installed_account_accountant") picking_type_id = fields.Many2one( 'stock.picking.type', string='Operation Type', default=_default_picking_type_id, required=True, domain="[('code', '=', 'outgoing'), ('warehouse_id.company_id', '=', company_id)]", ondelete='restrict') journal_id = fields.Many2one( 'account.journal', string='Point of Sale Journal', domain=[('type', 'in', ('general', 'sale'))], help="Accounting journal used to post POS session journal entries and POS invoice payments.", default=_default_sale_journal, ondelete='restrict') invoice_journal_id = fields.Many2one( 'account.journal', string='Invoice Journal', domain=[('type', '=', 'sale')], help="Accounting journal used to create invoices.", default=_default_invoice_journal) currency_id = fields.Many2one('res.currency', compute='_compute_currency', string="Currency") iface_cashdrawer = fields.Boolean(string='Cashdrawer', help="Automatically open the cashdrawer.") iface_electronic_scale = fields.Boolean(string='Electronic Scale', help="Enables Electronic Scale integration.") iface_customer_facing_display = fields.Boolean(compute='_compute_customer_facing_display') iface_customer_facing_display_via_proxy = fields.Boolean(string='Customer Facing Display', help="Show checkout to customers with a remotely-connected screen.") iface_customer_facing_display_local = fields.Boolean(string='Local Customer Facing Display', help="Show customers checkout in a pop-up window. Recommend to be moved to a second screen visible to the client.") iface_print_via_proxy = fields.Boolean(string='Print via Proxy', help="Bypass browser printing and prints via the hardware proxy.") iface_scan_via_proxy = fields.Boolean(string='Scan via Proxy', help="Enable barcode scanning with a remotely connected barcode scanner and card swiping with a Vantiv card reader.") iface_big_scrollbars = fields.Boolean('Large Scrollbars', help='For imprecise industrial touchscreens.') iface_orderline_customer_notes = fields.Boolean(string='Customer Notes', help='Allow to write notes for customer on Orderlines. This will be shown in the receipt.') iface_print_auto = fields.Boolean(string='Automatic Receipt Printing', default=False, help='The receipt will automatically be printed at the end of each order.') iface_print_skip_screen = fields.Boolean(string='Skip Preview Screen', default=True, help='The receipt screen will be skipped if the receipt can be printed automatically.') iface_tax_included = fields.Selection([('subtotal', 'Tax-Excluded Price'), ('total', 'Tax-Included Price')], string="Tax Display", default='subtotal', required=True) iface_start_categ_id = fields.Many2one('pos.category', string='Initial Category', help='The point of sale will display this product category by default. If no category is specified, all available products will be shown.') iface_available_categ_ids = fields.Many2many('pos.category', string='Available PoS Product Categories', help='The point of sale will only display products which are within one of the selected category trees. If no category is specified, all available products will be shown') selectable_categ_ids = fields.Many2many('pos.category', compute='_compute_selectable_categories') iface_display_categ_images = fields.Boolean(string='Display Category Pictures', help="The product categories will be displayed with pictures.") restrict_price_control = fields.Boolean(string='Restrict Price Modifications to Managers', help="Only users with Manager access rights for PoS app can modify the product prices on orders.") cash_control = fields.Boolean(string='Advanced Cash Control', compute='_compute_cash_control', help="Check the amount of the cashbox at opening and closing.") set_maximum_difference = fields.Boolean('Set Maximum Difference', help="Set a maximum difference allowed between the expected and counted money during the closing of the session.") receipt_header = fields.Text(string='Receipt Header', help="A short text that will be inserted as a header in the printed receipt.") receipt_footer = fields.Text(string='Receipt Footer', help="A short text that will be inserted as a footer in the printed receipt.") proxy_ip = fields.Char(string='IP Address', size=45, help='The hostname or ip address of the hardware proxy, Will be autodetected if left empty.') active = fields.Boolean(default=True) uuid = fields.Char(readonly=True, default=lambda self: str(uuid4()), copy=False, help='A globally unique identifier for this pos configuration, used to prevent conflicts in client-generated data.') sequence_id = fields.Many2one('ir.sequence', string='Order IDs Sequence', readonly=True, help="This sequence is automatically created by Odoo but you can change it " "to customize the reference numbers of your orders.", copy=False, ondelete='restrict') sequence_line_id = fields.Many2one('ir.sequence', string='Order Line IDs Sequence', readonly=True, help="This sequence is automatically created by Odoo but you can change it " "to customize the reference numbers of your orders lines.", copy=False) session_ids = fields.One2many('pos.session', 'config_id', string='Sessions') current_session_id = fields.Many2one('pos.session', compute='_compute_current_session', string="Current Session") current_session_state = fields.Char(compute='_compute_current_session') number_of_opened_session = fields.Integer(string="Number of Opened Session", compute='_compute_current_session') last_session_closing_cash = fields.Float(compute='_compute_last_session') last_session_closing_date = fields.Date(compute='_compute_last_session') pos_session_username = fields.Char(compute='_compute_current_session_user') pos_session_state = fields.Char(compute='_compute_current_session_user') pos_session_duration = fields.Char(compute='_compute_current_session_user') pricelist_id = fields.Many2one('product.pricelist', string='Default Pricelist', required=True, default=_default_pricelist, help="The pricelist used if no customer is selected or if the customer has no Sale Pricelist configured.") available_pricelist_ids = fields.Many2many('product.pricelist', string='Available Pricelists', default=_default_pricelist, help="Make several pricelists available in the Point of Sale. You can also apply a pricelist to specific customers from their contact form (in Sales tab). To be valid, this pricelist must be listed here as an available pricelist. Otherwise the default pricelist will apply.") allowed_pricelist_ids = fields.Many2many( 'product.pricelist', string='Allowed Pricelists', compute='_compute_allowed_pricelist_ids', help='This is a technical field used for the domain of pricelist_id.', ) company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company) barcode_nomenclature_id = fields.Many2one('barcode.nomenclature', string='Barcode Nomenclature', help='Defines what kind of barcodes are available and how they are assigned to products, customers and cashiers.', default=lambda self: self.env.company.nomenclature_id, required=True) group_pos_manager_id = fields.Many2one('res.groups', string='Point of Sale Manager Group', default=_get_group_pos_manager, help='This field is there to pass the id of the pos manager group to the point of sale client.') group_pos_user_id = fields.Many2one('res.groups', string='Point of Sale User Group', default=_get_group_pos_user, help='This field is there to pass the id of the pos user group to the point of sale client.') iface_tipproduct = fields.Boolean(string="Product tips") tip_product_id = fields.Many2one('product.product', string='Tip Product', help="This product is used as reference on customer receipts.") fiscal_position_ids = fields.Many2many('account.fiscal.position', string='Fiscal Positions', help='This is useful for restaurants with onsite and take-away services that imply specific tax rates.') default_fiscal_position_id = fields.Many2one('account.fiscal.position', string='Default Fiscal Position') default_bill_ids = fields.Many2many('pos.bill', string="Coins/Bills") use_pricelist = fields.Boolean("Use a pricelist.") tax_regime = fields.Boolean("Tax Regime") tax_regime_selection = fields.Boolean("Tax Regime Selection value") start_category = fields.Boolean("Start Category", default=False) limit_categories = fields.Boolean("Restrict Product Categories") module_account = fields.Boolean(string='Invoicing', default=True, help='Enables invoice generation from the Point of Sale.') module_pos_restaurant = fields.Boolean("Is a Bar/Restaurant") module_pos_discount = fields.Boolean("Global Discounts") module_pos_loyalty = fields.Boolean("Loyalty Program") module_pos_mercury = fields.Boolean(string="Integrated Card Payments") product_configurator = fields.Boolean(string="Product Configurator") is_posbox = fields.Boolean("PosBox") is_header_or_footer = fields.Boolean("Header & Footer") module_pos_hr = fields.Boolean(help="Show employee login screen") amount_authorized_diff = fields.Float('Amount Authorized Difference', help="This field depicts the maximum difference allowed between the ending balance and the theoretical cash when " "closing a session, for non-POS managers. If this maximum is reached, the user will have an error message at " "the closing of his session saying that he needs to contact his manager.") payment_method_ids = fields.Many2many('pos.payment.method', string='Payment Methods', default=lambda self: self._default_payment_methods()) company_has_template = fields.Boolean(string="Company has chart of accounts", compute="_compute_company_has_template") current_user_id = fields.Many2one('res.users', string='Current Session Responsible', compute='_compute_current_session_user') other_devices = fields.Boolean(string="Other Devices", help="Connect devices to your PoS without an IoT Box.") rounding_method = fields.Many2one('account.cash.rounding', string="Cash rounding") cash_rounding = fields.Boolean(string="Cash Rounding") only_round_cash_method = fields.Boolean(string="Only apply rounding on cash") has_active_session = fields.Boolean(compute='_compute_current_session') manual_discount = fields.Boolean(string="Manual Discounts", default=True) ship_later = fields.Boolean(string="Ship Later") warehouse_id = fields.Many2one('stock.warehouse', default=_default_warehouse_id, ondelete='restrict') route_id = fields.Many2one('stock.location.route', string="Spefic route for products delivered later.") picking_policy = fields.Selection([ ('direct', 'As soon as possible'), ('one', 'When all products are ready')], string='Shipping Policy', required=True, default='direct', help="If you deliver all products at once, the delivery order will be scheduled based on the greatest " "product lead time. Otherwise, it will be based on the shortest.") limited_products_loading = fields.Boolean('Limited Product Loading', help="we load all starred products (favorite), all services, recent inventory movements of products, and the most recently updated products.\n" "When the session is open, we keep on loading all remaining products in the background.\n" "In the meantime, you can click on the 'database icon' in the searchbar to load products from database.") limited_products_amount = fields.Integer(default=20000) product_load_background = fields.Boolean() limited_partners_loading = fields.Boolean('Limited Partners Loading', help="By default, 100 partners are loaded.\n" "When the session is open, we keep on loading all remaining partners in the background.\n" "In the meantime, you can use the 'Load Customers' button to load partners from database.") limited_partners_amount = fields.Integer(default=100) partner_load_background = fields.Boolean() @api.depends('payment_method_ids') def _compute_cash_control(self): for config in self: config.cash_control = bool(config.payment_method_ids.filtered('is_cash_count')) @api.depends('use_pricelist', 'available_pricelist_ids') def _compute_allowed_pricelist_ids(self): for config in self: if config.use_pricelist: config.allowed_pricelist_ids = config.available_pricelist_ids.ids else: config.allowed_pricelist_ids = self.env['product.pricelist'].search([]).ids @api.depends('company_id') def _compute_company_has_template(self): for config in self: config.company_has_template = self.env['account.chart.template'].existing_accounting(config.company_id) or config.company_id.chart_template_id def _compute_is_installed_account_accountant(self): account_accountant = self.env['ir.module.module'].sudo().search([('name', '=', 'account_accountant'), ('state', '=', 'installed')]) for pos_config in self: pos_config.is_installed_account_accountant = account_accountant and account_accountant.id @api.depends('journal_id.currency_id', 'journal_id.company_id.currency_id', 'company_id', 'company_id.currency_id') def _compute_currency(self): for pos_config in self: if pos_config.journal_id: pos_config.currency_id = pos_config.journal_id.currency_id.id or pos_config.journal_id.company_id.currency_id.id else: pos_config.currency_id = pos_config.company_id.currency_id.id @api.depends('session_ids', 'session_ids.state') def _compute_current_session(self): """If there is an open session, store it to current_session_id / current_session_State. """ for pos_config in self: opened_sessions = pos_config.session_ids.filtered(lambda s: not s.state == 'closed') session = pos_config.session_ids.filtered(lambda s: not s.state == 'closed' and not s.rescue) # sessions ordered by id desc pos_config.number_of_opened_session = len(opened_sessions) pos_config.has_active_session = opened_sessions and True or False pos_config.current_session_id = session and session[0].id or False pos_config.current_session_state = session and session[0].state or False @api.depends('session_ids') def _compute_last_session(self): PosSession = self.env['pos.session'] for pos_config in self: session = PosSession.search_read( [('config_id', '=', pos_config.id), ('state', '=', 'closed')], ['cash_register_balance_end_real', 'stop_at', 'cash_register_id'], order="stop_at desc", limit=1) if session: timezone = pytz.timezone(self._context.get('tz') or self.env.user.tz or 'UTC') pos_config.last_session_closing_date = session[0]['stop_at'].astimezone(timezone).date() if session[0]['cash_register_id']: pos_config.last_session_closing_cash = session[0]['cash_register_balance_end_real'] else: pos_config.last_session_closing_cash = 0 else: pos_config.last_session_closing_cash = 0 pos_config.last_session_closing_date = False @api.depends('session_ids') def _compute_current_session_user(self): for pos_config in self: session = pos_config.session_ids.filtered(lambda s: s.state in ['opening_control', 'opened', 'closing_control'] and not s.rescue) if session: pos_config.pos_session_username = session[0].user_id.sudo().name pos_config.pos_session_state = session[0].state pos_config.pos_session_duration = ( datetime.now() - session[0].start_at ).days if session[0].start_at else 0 pos_config.current_user_id = session[0].user_id else: pos_config.pos_session_username = False pos_config.pos_session_state = False pos_config.pos_session_duration = 0 pos_config.current_user_id = False @api.depends('iface_available_categ_ids') def _compute_selectable_categories(self): for config in self: if config.iface_available_categ_ids: config.selectable_categ_ids = config.iface_available_categ_ids else: config.selectable_categ_ids = self.env['pos.category'].search([]) @api.depends('iface_customer_facing_display_via_proxy', 'iface_customer_facing_display_local') def _compute_customer_facing_display(self): for config in self: config.iface_customer_facing_display = config.iface_customer_facing_display_via_proxy or config.iface_customer_facing_display_local @api.constrains('rounding_method') def _check_rounding_method_strategy(self): for config in self: if config.cash_rounding and config.rounding_method.strategy != 'add_invoice_line': selection_value = "Add a rounding line" for key, val in self.env["account.cash.rounding"]._fields["strategy"]._description_selection(config.env): if key == "add_invoice_line": selection_value = val break raise ValidationError(_( "The cash rounding strategy of the point of sale %(pos)s must be: '%(value)s'", pos=config.name, value=selection_value, )) @api.constrains('company_id', 'journal_id') def _check_company_journal(self): for config in self: if config.journal_id and config.journal_id.company_id.id != config.company_id.id: raise ValidationError(_("The sales journal of the point of sale %s must belong to its company.", config.name)) def _check_profit_loss_cash_journal(self): if self.cash_control and self.payment_method_ids: for method in self.payment_method_ids: if method.is_cash_count and (not method.journal_id.loss_account_id or not method.journal_id.profit_account_id): raise ValidationError(_("You need a loss and profit account on your cash journal.")) @api.constrains('company_id', 'invoice_journal_id') def _check_company_invoice_journal(self): for config in self: if config.invoice_journal_id and config.invoice_journal_id.company_id.id != config.company_id.id: raise ValidationError(_("The invoice journal of the point of sale %s must belong to the same company.", config.name)) @api.constrains('company_id', 'payment_method_ids') def _check_company_payment(self): for config in self: if self.env['pos.payment.method'].search_count([('id', 'in', config.payment_method_ids.ids), ('company_id', '!=', config.company_id.id)]): raise ValidationError(_("The payment methods for the point of sale %s must belong to its company.", self.name)) @api.constrains('pricelist_id', 'use_pricelist', 'available_pricelist_ids', 'journal_id', 'invoice_journal_id', 'payment_method_ids') def _check_currencies(self): for config in self: if config.use_pricelist and config.pricelist_id not in config.available_pricelist_ids: raise ValidationError(_("The default pricelist must be included in the available pricelists.")) if any(self.available_pricelist_ids.mapped(lambda pricelist: pricelist.currency_id != self.currency_id)): raise ValidationError(_("All available pricelists must be in the same currency as the company or" " as the Sales Journal set on this point of sale if you use" " the Accounting application.")) if self.invoice_journal_id.currency_id and self.invoice_journal_id.currency_id != self.currency_id: raise ValidationError(_("The invoice journal must be in the same currency as the Sales Journal or the company currency if that is not set.")) if any( self.payment_method_ids\ .filtered(lambda pm: pm.is_cash_count)\ .mapped(lambda pm: self.currency_id not in (self.company_id.currency_id | pm.journal_id.currency_id)) ): raise ValidationError(_("All payment methods must be in the same currency as the Sales Journal or the company currency if that is not set.")) def _check_payment_method_ids(self): self.ensure_one() if not self.payment_method_ids: raise ValidationError( _("You must have at least one payment method configured to launch a session.") ) @api.constrains('limited_partners_amount', 'limited_partners_loading') def _check_limited_partners(self): for rec in self: if rec.limited_partners_loading and not self.limited_partners_amount: raise ValidationError( _("Number of partners loaded can not be 0")) @api.constrains('limited_products_amount', 'limited_products_loading') def _check_limited_products(self): for rec in self: if rec.limited_products_loading and not self.limited_products_amount: raise ValidationError( _("Number of product loaded can not be 0")) @api.constrains('pricelist_id', 'available_pricelist_ids') def _check_pricelists(self): self._check_companies() self = self.sudo() if self.pricelist_id.company_id and self.pricelist_id.company_id != self.company_id: raise ValidationError( _("The default pricelist must belong to no company or the company of the point of sale.")) @api.constrains('company_id', 'available_pricelist_ids') def _check_companies(self): for config in self: if any(pricelist.company_id.id not in [False, config.company_id.id] for pricelist in config.available_pricelist_ids): raise ValidationError(_("The selected pricelists must belong to no company or the company of the point of sale.")) @api.onchange('iface_tipproduct') def _onchange_tipproduct(self): if self.iface_tipproduct: self.tip_product_id = self.env.ref('point_of_sale.product_product_tip', False) else: self.tip_product_id = False @api.onchange('iface_print_via_proxy') def _onchange_iface_print_via_proxy(self): self.iface_print_auto = self.iface_print_via_proxy if not self.iface_print_via_proxy: self.iface_cashdrawer = False @api.onchange('module_account') def _onchange_module_account(self): if self.module_account and not self.invoice_journal_id: self.invoice_journal_id = self._default_invoice_journal() @api.onchange('use_pricelist') def _onchange_use_pricelist(self): """ If the 'pricelist' box is unchecked, we reset the pricelist_id to stop using a pricelist for this iotbox. """ if not self.use_pricelist: self.pricelist_id = self._default_pricelist() @api.onchange('available_pricelist_ids') def _onchange_available_pricelist_ids(self): if self.pricelist_id not in self.available_pricelist_ids._origin: self.pricelist_id = False @api.onchange('is_posbox') def _onchange_is_posbox(self): if not self.is_posbox: self.proxy_ip = False self.iface_scan_via_proxy = False self.iface_electronic_scale = False self.iface_cashdrawer = False self.iface_print_via_proxy = False self.iface_customer_facing_display_via_proxy = False @api.onchange('tax_regime') def _onchange_tax_regime(self): if not self.tax_regime: self.default_fiscal_position_id = False @api.onchange('tax_regime_selection') def _onchange_tax_regime_selection(self): if not self.tax_regime_selection: self.fiscal_position_ids = [(5, 0, 0)] @api.onchange('start_category') def _onchange_start_category(self): if not self.start_category: self.iface_start_categ_id = False @api.onchange('limit_categories', 'iface_available_categ_ids', 'iface_start_categ_id') def _onchange_limit_categories(self): res = {} if not self.limit_categories: self.iface_available_categ_ids = False if self.iface_available_categ_ids and self.iface_start_categ_id.id not in self.iface_available_categ_ids.ids: self.iface_start_categ_id = False return res @api.onchange('is_header_or_footer') def _onchange_header_footer(self): if not self.is_header_or_footer: self.receipt_header = False self.receipt_footer = False def name_get(self): result = [] for config in self: last_session = self.env['pos.session'].search([('config_id', '=', config.id)], limit=1) if (not last_session) or (last_session.state == 'closed'): result.append((config.id, _("%(pos_name)s (not used)", pos_name=config.name))) else: result.append((config.id, "%s (%s)" % (config.name, last_session.user_id.name))) return result @api.model def create(self, values): IrSequence = self.env['ir.sequence'].sudo() val = { 'name': _('POS Order %s', values['name']), 'padding': 4, 'prefix': "%s/" % values['name'], 'code': "pos.order", 'company_id': values.get('company_id', False), } # force sequence_id field to new pos.order sequence values['sequence_id'] = IrSequence.create(val).id val.update(name=_('POS order line %s', values['name']), code='pos.order.line') values['sequence_line_id'] = IrSequence.create(val).id pos_config = super(PosConfig, self).create(values) pos_config.sudo()._check_modules_to_install() pos_config.sudo()._check_groups_implied() # If you plan to add something after this, use a new environment. The one above is no longer valid after the modules install. return pos_config def write(self, vals): opened_session = self.mapped('session_ids').filtered(lambda s: s.state != 'closed') if opened_session: forbidden_fields = [] for key in self._get_forbidden_change_fields(): if key in vals.keys(): field_name = self._fields[key].get_description(self.env)["string"] forbidden_fields.append(field_name) if len(forbidden_fields) > 0: raise UserError(_( "Unable to modify this PoS Configuration because you can't modify %s while a session is open.", ", ".join(forbidden_fields) )) result = super(PosConfig, self).write(vals) self.sudo()._set_fiscal_position() self.sudo()._check_modules_to_install() self.sudo()._check_groups_implied() return result def _get_forbidden_change_fields(self): forbidden_keys = ['module_pos_hr', 'module_pos_restaurant', 'available_pricelist_ids', 'limit_categories', 'iface_available_categ_ids', 'use_pricelist', 'module_pos_discount', 'payment_method_ids', 'iface_tipproduc'] return forbidden_keys def unlink(self): # Delete the pos.config records first then delete the sequences linked to them sequences_to_delete = self.sequence_id | self.sequence_line_id res = super(PosConfig, self).unlink() sequences_to_delete.unlink() return res def _set_fiscal_position(self): for config in self: if config.tax_regime and config.default_fiscal_position_id.id not in config.fiscal_position_ids.ids: config.fiscal_position_ids = [(4, config.default_fiscal_position_id.id)] elif not config.tax_regime_selection and not config.tax_regime and config.fiscal_position_ids.ids: config.fiscal_position_ids = [(5, 0, 0)] def _check_modules_to_install(self): # determine modules to install expected = [ fname[7:] # 'module_account' -> 'account' for fname in self.fields_get_keys() if fname.startswith('module_') if any(pos_config[fname] for pos_config in self) ] if expected: STATES = ('installed', 'to install', 'to upgrade') modules = self.env['ir.module.module'].sudo().search([('name', 'in', expected)]) modules = modules.filtered(lambda module: module.state not in STATES) if modules: modules.button_immediate_install() # just in case we want to do something if we install a module. (like a refresh ...) return True return False def _check_groups_implied(self): for pos_config in self: for field_name in [f for f in pos_config.fields_get_keys() if f.startswith('group_')]: field = pos_config._fields[field_name] if field.type in ('boolean', 'selection') and hasattr(field, 'implied_group'): field_group_xmlids = getattr(field, 'group', 'base.group_user').split(',') field_groups = self.env['res.groups'].concat(*(self.env.ref(it) for it in field_group_xmlids)) field_groups.write({'implied_ids': [(4, self.env.ref(field.implied_group).id)]}) def execute(self): return { 'type': 'ir.actions.client', 'tag': 'reload', 'params': {'wait': True} } def _force_http(self): enforce_https = self.env['ir.config_parameter'].sudo().get_param('point_of_sale.enforce_https') if not enforce_https and self.other_devices: return True return False def _get_pos_base_url(self): return '/pos/web' if self._force_http() else '/pos/ui' # Methods to open the POS def open_ui(self): """Open the pos interface with config_id as an extra argument. In vanilla PoS each user can only have one active session, therefore it was not needed to pass the config_id on opening a session. It is also possible to login to sessions created by other users. :returns: dict """ self.ensure_one() # check all constraints, raises if any is not met self._validate_fields(self._fields) return { 'type': 'ir.actions.act_url', 'url': self._get_pos_base_url() + '?config_id=%d' % self.id, 'target': 'self', } def open_session_cb(self, check_coa=True): """ new session button create one if none exist access cash control interface if enabled or start a session """ self.ensure_one() if not self.current_session_id: self._check_pricelists() self._check_company_journal() self._check_company_invoice_journal() self._check_company_payment() self._check_currencies() self._check_profit_loss_cash_journal() self._check_payment_method_ids() self.env['pos.session'].create({ 'user_id': self.env.uid, 'config_id': self.id }) return self.open_ui() def open_existing_session_cb(self): """ close session button access session form to validate entries """ self.ensure_one() return self._open_session(self.current_session_id.id) def _open_session(self, session_id): self._check_pricelists() # The pricelist company might have changed after the first opening of the session return { 'name': _('Session'), 'view_mode': 'form,tree', 'res_model': 'pos.session', 'res_id': session_id, 'view_id': False, 'type': 'ir.actions.act_window', } def open_opened_session_list(self): return { 'name': _('Opened Sessions'), 'res_model': 'pos.session', 'view_mode': 'tree,kanban,form', 'type': 'ir.actions.act_window', 'domain': [('state', '!=', 'closed'), ('config_id', '=', self.id)] } # All following methods are made to create data needed in POS, when a localisation # is installed, or if POS is installed on database having companies that already have # a localisation installed @api.model def post_install_pos_localisation(self, companies=False): self = self.sudo() if not companies: companies = self.env['res.company'].search([]) for company in companies.filtered('chart_template_id'): pos_configs = self.search([('company_id', '=', company.id)]) pos_configs.setup_defaults(company) def setup_defaults(self, company): """Extend this method to customize the existing pos.config of the company during the installation of a localisation. :param self pos.config: pos.config records present in the company during the installation of localisation. :param company res.company: the single company where the pos.config defaults will be setup. """ self.assign_payment_journals(company) self.generate_pos_journal(company) self.setup_invoice_journal(company) def assign_payment_journals(self, company): for pos_config in self: if pos_config.payment_method_ids or pos_config.has_active_session: continue cash_journal = self.env['account.journal'].search([('company_id', '=', company.id), ('type', '=', 'cash')], limit=1) bank_journal = self.env['account.journal'].search([('company_id', '=', company.id), ('type', '=', 'bank')], limit=1) payment_methods = self.env['pos.payment.method'] if cash_journal: payment_methods |= payment_methods.create({ 'name': _('Cash'), 'journal_id': cash_journal.id, 'company_id': company.id, }) if bank_journal: payment_methods |= payment_methods.create({ 'name': _('Bank'), 'journal_id': bank_journal.id, 'company_id': company.id, }) payment_methods |= payment_methods.create({ 'name': _('Customer Account'), 'company_id': company.id, 'split_transactions': True, }) pos_config.write({'payment_method_ids': [(6, 0, payment_methods.ids)]}) def generate_pos_journal(self, company): for pos_config in self: if pos_config.journal_id: continue pos_journal = self.env['account.journal'].search([('company_id', '=', company.id), ('code', '=', 'POSS')]) if not pos_journal: pos_journal = self.env['account.journal'].create({ 'type': 'general', 'name': 'Point of Sale', 'code': 'POSS', 'company_id': company.id, 'sequence': 20 }) pos_config.write({'journal_id': pos_journal.id}) def setup_invoice_journal(self, company): for pos_config in self: invoice_journal_id = pos_config.invoice_journal_id or self.env['account.journal'].search([('type', '=', 'sale'), ('company_id', '=', company.id)], limit=1) if invoice_journal_id: pos_config.write({'invoice_journal_id': invoice_journal_id.id}) else: pos_config.write({'module_account': False}) def get_limited_products_loading(self, fields): query = """ WITH pm AS ( SELECT product_id, Max(write_date) date FROM stock_quant GROUP BY product_id ) SELECT p.id FROM product_product p LEFT JOIN product_template t ON product_tmpl_id=t.id LEFT JOIN pm ON p.id=pm.product_id WHERE ( t.available_in_pos AND t.sale_ok AND (t.company_id=%(company_id)s OR t.company_id IS NULL) AND %(available_categ_ids)s IS NULL OR t.pos_categ_id=ANY(%(available_categ_ids)s) ) OR p.id=%(tip_product_id)s ORDER BY t.priority DESC, t.detailed_type DESC, COALESCE(pm.date,p.write_date) DESC LIMIT %(limit)s """ params = { 'company_id': self.company_id.id, 'available_categ_ids': self.iface_available_categ_ids.mapped('id') if self.iface_available_categ_ids else None, 'tip_product_id': self.tip_product_id.id if self.tip_product_id else None, 'limit': self.limited_products_amount } self.env.cr.execute(query, params) product_ids = self.env.cr.fetchall() products = self.env['product.product'].search_read([('id', 'in', product_ids)], fields=fields) return products def get_limited_partners_loading(self): self.env.cr.execute(""" WITH pm AS ( SELECT partner_id, Count(partner_id) order_count FROM pos_order GROUP BY partner_id) SELECT id FROM res_partner AS partner LEFT JOIN pm ON ( partner.id = pm.partner_id) ORDER BY COALESCE(pm.order_count, 0) DESC, NAME limit %s; """, [str(self.limited_partners_amount)]) result = self.env.cr.fetchall() return result
55.105615
41,219
453
py
PYTHON
15.0
from odoo import api, fields, models, _ class Bill(models.Model): _name = "pos.bill" _order = "value" _description = "Coins/Bills" name = fields.Char("Name") value = fields.Float("Coin/Bill Value", required=True, digits=0) pos_config_ids = fields.Many2many("pos.config") @api.model def name_create(self, name): result = super().create({"name": name, "value": float(name)}) return result.name_get()[0]
28.3125
453
1,076
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class AccountPayment(models.Model): _inherit = 'account.payment' pos_payment_method_id = fields.Many2one('pos.payment.method', "POS Payment Method") force_outstanding_account_id = fields.Many2one("account.account", "Forced Outstanding Account", check_company=True) pos_session_id = fields.Many2one('pos.session', "POS Session") def _get_valid_liquidity_accounts(self): result = super()._get_valid_liquidity_accounts() return result + (self.pos_payment_method_id.outstanding_account_id,) @api.depends("force_outstanding_account_id") def _compute_outstanding_account_id(self): """When force_outstanding_account_id is set, we use it as the outstanding_account_id.""" super()._compute_outstanding_account_id() for payment in self: if payment.force_outstanding_account_id: payment.outstanding_account_id = payment.force_outstanding_account_id
44.833333
1,076
1,752
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models, fields, _ from odoo.exceptions import ValidationError class ResCompany(models.Model): _inherit = 'res.company' point_of_sale_update_stock_quantities = fields.Selection([ ('closing', 'At the session closing (recommended)'), ('real', 'In real time'), ], default='closing', string="Update quantities in stock", help="At the session closing: A picking is created for the entire session when it's closed\n In real time: Each order sent to the server create its own picking") @api.constrains('period_lock_date', 'fiscalyear_lock_date') def validate_period_lock_date(self): """ This constrains makes it impossible to change the period lock date if some open POS session exists into it. Without that, these POS sessions would trigger an error message saying that the period has been locked when trying to close them. """ pos_session_model = self.env['pos.session'].sudo() for record in self: sessions_in_period = pos_session_model.search( [ "&", "&", ("company_id", "=", record.id), ("state", "!=", "closed"), "|", ("start_at", "<=", record.period_lock_date), ("start_at", "<=", record.fiscalyear_lock_date), ] ) if sessions_in_period: sessions_str = ', '.join(sessions_in_period.mapped('name')) raise ValidationError(_("Please close all the point of sale sessions in this period before closing it. Open sessions are: %s ") % (sessions_str))
47.351351
1,752
15,539
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api,fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import float_is_zero, float_compare from itertools import groupby from collections import defaultdict class StockPicking(models.Model): _inherit='stock.picking' pos_session_id = fields.Many2one('pos.session', index=True) pos_order_id = fields.Many2one('pos.order', index=True) def _prepare_picking_vals(self, partner, picking_type, location_id, location_dest_id): return { 'partner_id': partner.id if partner else False, 'user_id': False, 'picking_type_id': picking_type.id, 'move_type': 'direct', 'location_id': location_id, 'location_dest_id': location_dest_id, } @api.model def _create_picking_from_pos_order_lines(self, location_dest_id, lines, picking_type, partner=False): """We'll create some picking based on order_lines""" pickings = self.env['stock.picking'] stockable_lines = lines.filtered(lambda l: l.product_id.type in ['product', 'consu'] and not float_is_zero(l.qty, precision_rounding=l.product_id.uom_id.rounding)) if not stockable_lines: return pickings positive_lines = stockable_lines.filtered(lambda l: l.qty > 0) negative_lines = stockable_lines - positive_lines if positive_lines: location_id = picking_type.default_location_src_id.id positive_picking = self.env['stock.picking'].create( self._prepare_picking_vals(partner, picking_type, location_id, location_dest_id) ) positive_picking._create_move_from_pos_order_lines(positive_lines) self.env['base'].flush() try: with self.env.cr.savepoint(): positive_picking._action_done() except (UserError, ValidationError): pass pickings |= positive_picking if negative_lines: if picking_type.return_picking_type_id: return_picking_type = picking_type.return_picking_type_id return_location_id = return_picking_type.default_location_dest_id.id else: return_picking_type = picking_type return_location_id = picking_type.default_location_src_id.id negative_picking = self.env['stock.picking'].create( self._prepare_picking_vals(partner, return_picking_type, location_dest_id, return_location_id) ) negative_picking._create_move_from_pos_order_lines(negative_lines) self.env['base'].flush() try: with self.env.cr.savepoint(): negative_picking._action_done() except (UserError, ValidationError): pass pickings |= negative_picking return pickings def _prepare_stock_move_vals(self, first_line, order_lines): return { 'name': first_line.name, 'product_uom': first_line.product_id.uom_id.id, 'picking_id': self.id, 'picking_type_id': self.picking_type_id.id, 'product_id': first_line.product_id.id, 'product_uom_qty': abs(sum(order_lines.mapped('qty'))), 'state': 'draft', 'location_id': self.location_id.id, 'location_dest_id': self.location_dest_id.id, 'company_id': self.company_id.id, } def _create_move_from_pos_order_lines(self, lines): self.ensure_one() lines_by_product = groupby(sorted(lines, key=lambda l: l.product_id.id), key=lambda l: l.product_id.id) move_vals = [] for dummy, olines in lines_by_product: order_lines = self.env['pos.order.line'].concat(*olines) move_vals.append(self._prepare_stock_move_vals(order_lines[0], order_lines)) moves = self.env['stock.move'].create(move_vals) confirmed_moves = moves._action_confirm() confirmed_moves._add_mls_related_to_order(lines, are_qties_done=True) self._link_owner_on_return_picking(lines) def _link_owner_on_return_picking(self, lines): """This method tries to retrieve the owner of the returned product""" if lines[0].order_id.refunded_order_ids.picking_ids: returned_lines_picking = lines[0].order_id.refunded_order_ids.picking_ids returnable_qty_by_product = {} for move_line in returned_lines_picking.move_line_ids: returnable_qty_by_product[(move_line.product_id.id, move_line.owner_id.id or 0)] = move_line.qty_done for move in self.move_line_ids: for keys in returnable_qty_by_product: if move.product_id.id == keys[0] and keys[1] and returnable_qty_by_product[keys] > 0: move.write({'owner_id': keys[1]}) returnable_qty_by_product[keys] -= move.product_uom_qty def _send_confirmation_email(self): # Avoid sending Mail/SMS for POS deliveries pickings = self.filtered(lambda p: p.picking_type_id != p.picking_type_id.warehouse_id.pos_type_id) return super(StockPicking, pickings)._send_confirmation_email() def _action_done(self): res = super()._action_done() for rec in self: if rec.picking_type_id.code != 'outgoing': continue if rec.pos_order_id.to_ship and not rec.pos_order_id.to_invoice: cost_per_account = defaultdict(lambda: 0.0) for line in rec.pos_order_id.lines: if line.product_id.type != 'product': continue out = line.product_id.categ_id.property_stock_account_output_categ_id exp = line.product_id._get_product_accounts()['expense'] cost_per_account[(out, exp)] += line.total_cost move_vals = [] for (out_acc, exp_acc), cost in cost_per_account.items(): move_vals.append({ 'journal_id': rec.pos_order_id.sale_journal.id, 'date': rec.pos_order_id.date_order, 'ref': rec.pos_order_id.name, 'line_ids': [ (0, 0, { 'name': rec.pos_order_id.name, 'account_id': exp_acc.id, 'debit': cost, 'credit': 0.0, }), (0, 0, { 'name': rec.pos_order_id.name, 'account_id': out_acc.id, 'debit': 0.0, 'credit': cost, }), ], }) move = self.env['account.move'].create(move_vals) rec.pos_order_id.write({'account_move': move.id}) move.action_post() return res class ProcurementGroup(models.Model): _inherit = 'procurement.group' pos_order_id = fields.Many2one('pos.order', 'POS Order') class StockMove(models.Model): _inherit = 'stock.move' def _get_new_picking_values(self): vals = super(StockMove, self)._get_new_picking_values() vals['pos_session_id'] = self.mapped('group_id.pos_order_id.session_id').id vals['pos_order_id'] = self.mapped('group_id.pos_order_id').id return vals def _key_assign_picking(self): keys = super(StockMove, self)._key_assign_picking() return keys + (self.group_id.pos_order_id,) @api.model def _prepare_lines_data_dict(self, order_lines): lines_data = defaultdict(dict) for product_id, olines in groupby(sorted(order_lines, key=lambda l: l.product_id.id), key=lambda l: l.product_id.id): lines_data[product_id].update({'order_lines': self.env['pos.order.line'].concat(*olines)}) return lines_data def _complete_done_qties(self, set_quantity_done_on_move=False): self._action_assign() for move_line in self.move_line_ids: move_line.qty_done = move_line.product_uom_qty mls_vals = [] moves_to_set = set() for move in self: if float_compare(move.product_uom_qty, move.quantity_done, precision_rounding=move.product_uom.rounding) > 0: remaining_qty = move.product_uom_qty - move.quantity_done mls_vals.append(dict(move._prepare_move_line_vals(), qty_done=remaining_qty)) moves_to_set.add(move.id) self.env['stock.move.line'].create(mls_vals) if set_quantity_done_on_move: for move in self.env['stock.move'].browse(moves_to_set): move.quantity_done = move.product_uom_qty def _create_production_lots_for_pos_order(self, lines): ''' Search for existing lots and create missing ones. :param lines: pos order lines with pack lot ids. :type lines: pos.order.line recordset. :return stock.product.lot recordset. ''' valid_lots = self.env['stock.production.lot'] moves = self.filtered(lambda m: m.picking_type_id.use_existing_lots) # Already called in self._action_confirm() but just to be safe when coming from _launch_stock_rule_from_pos_order_lines. self._check_company() if moves: moves_product_ids = set(moves.mapped('product_id').ids) lots = lines.pack_lot_ids.filtered(lambda l: l.lot_name and l.product_id.id in moves_product_ids) lots_data = set(lots.mapped(lambda l: (l.product_id.id, l.lot_name))) existing_lots = self.env['stock.production.lot'].search([ ('company_id', '=', moves[0].picking_type_id.company_id.id), ('product_id', 'in', lines.product_id.ids), ('name', 'in', lots.mapped('lot_name')), ]) #The previous search may return (product_id.id, lot_name) combinations that have no matching in lines.pack_lot_ids. for lot in existing_lots: if (lot.product_id.id, lot.name) in lots_data: valid_lots |= lot lots_data.remove((lot.product_id.id, lot.name)) moves = moves.filtered(lambda m: m.picking_type_id.use_create_lots) if moves: moves_product_ids = set(moves.mapped('product_id').ids) missing_lot_values = [] for lot_product_id, lot_name in filter(lambda l: l[0] in moves_product_ids, lots_data): missing_lot_values.append({'company_id': self.company_id.id, 'product_id': lot_product_id, 'name': lot_name}) valid_lots |= self.env['stock.production.lot'].create(missing_lot_values) return valid_lots def _add_mls_related_to_order(self, related_order_lines, are_qties_done=True): lines_data = self._prepare_lines_data_dict(related_order_lines) qty_fname = 'qty_done' if are_qties_done else 'product_uom_qty' # Moves with product_id not in related_order_lines. This can happend e.g. when product_id has a phantom-type bom. moves_to_assign = self.filtered(lambda m: m.product_id.id not in lines_data or m.product_id.tracking == 'none' or (not m.picking_type_id.use_existing_lots and not m.picking_type_id.use_create_lots)) moves_to_assign._complete_done_qties(set_quantity_done_on_move=True) moves_remaining = self - moves_to_assign existing_lots = moves_remaining._create_production_lots_for_pos_order(related_order_lines) move_lines_to_create = [] mls_qties = [] if are_qties_done: for move in moves_remaining: for line in lines_data[move.product_id.id]['order_lines']: sum_of_lots = 0 for lot in line.pack_lot_ids.filtered(lambda l: l.lot_name): if line.product_id.tracking == 'serial': qty = 1 else: qty = abs(line.qty) ml_vals = dict(move._prepare_move_line_vals()) if existing_lots: existing_lot = existing_lots.filtered_domain([('product_id', '=', line.product_id.id), ('name', '=', lot.lot_name)]) quant = self.env['stock.quant'] if existing_lot: quant = self.env['stock.quant'].search( [('lot_id', '=', existing_lot.id), ('quantity', '>', '0.0'), ('location_id', 'child_of', move.location_id.id)], order='id desc', limit=1 ) ml_vals.update({ 'lot_id': existing_lot.id, 'location_id': quant.location_id.id or move.location_id.id, 'owner_id': quant.owner_id.id or False, }) else: ml_vals.update({'lot_name': lot.lot_name}) move_lines_to_create.append(ml_vals) mls_qties.append(qty) sum_of_lots += qty if abs(line.qty) != sum_of_lots: difference_qty = abs(line.qty) - sum_of_lots ml_vals = move._prepare_move_line_vals() if line.product_id.tracking == 'serial': move_lines_to_create.extend([ml_vals for i in range(int(difference_qty))]) mls_qties.extend([1]*int(difference_qty)) else: move_lines_to_create.append(ml_vals) mls_qties.append(difference_qty) move_lines = self.env['stock.move.line'].create(move_lines_to_create) for move_line, qty in zip(move_lines, mls_qties): move_line.write({qty_fname: qty}) else: for move in moves_remaining: for line in lines_data[move.product_id.id]['order_lines']: for lot in line.pack_lot_ids.filtered(lambda l: l.lot_name): if line.product_id.tracking == 'serial': qty = 1 else: qty = abs(line.qty) if existing_lots: existing_lot = existing_lots.filtered_domain([('product_id', '=', line.product_id.id), ('name', '=', lot.lot_name)]) if existing_lot: available_quantity = move._get_available_quantity(move.location_id, lot_id=existing_lot, strict=True) if not float_is_zero(available_quantity, precision_rounding=line.product_id.uom_id.rounding): move._update_reserved_quantity(qty, min(qty, available_quantity), move.location_id, existing_lot) continue
51.624585
15,539
5,041
py
PYTHON
15.0
from odoo import api, fields, models, _ from odoo.exceptions import UserError class PosPaymentMethod(models.Model): _name = "pos.payment.method" _description = "Point of Sale Payment Methods" _order = "id asc" def _get_payment_terminal_selection(self): return [] name = fields.Char(string="Method", required=True, translate=True, help='Defines the name of the payment method that will be displayed in the Point of Sale when the payments are selected.') outstanding_account_id = fields.Many2one('account.account', string='Outstanding Account', ondelete='restrict', help='Leave empty to use the default account from the company setting.\n' 'Account used as outstanding account when creating accounting payment records for bank payments.') receivable_account_id = fields.Many2one('account.account', string='Intermediary Account', ondelete='restrict', domain=[('reconcile', '=', True), ('user_type_id.type', '=', 'receivable')], help="Leave empty to use the default account from the company setting.\n" "Overrides the company's receivable account (for Point of Sale) used in the journal entries.") is_cash_count = fields.Boolean(string='Cash', compute="_compute_is_cash_count", store=True) journal_id = fields.Many2one('account.journal', string='Journal', domain=[('type', 'in', ('cash', 'bank'))], ondelete='restrict', help='Leave empty to use the receivable account of customer.\n' 'Defines the journal where to book the accumulated payments (or individual payment if Identify Customer is true) after closing the session.\n' 'For cash journal, we directly write to the default account in the journal via statement lines.\n' 'For bank journal, we write to the outstanding account specified in this payment method.\n' 'Only cash and bank journals are allowed.') split_transactions = fields.Boolean( string='Identify Customer', default=False, help='Forces to set a customer when using this payment method and splits the journal entries for each customer. It could slow down the closing process.') open_session_ids = fields.Many2many('pos.session', string='Pos Sessions', compute='_compute_open_session_ids', help='Open PoS sessions that are using this payment method.') config_ids = fields.Many2many('pos.config', string='Point of Sale Configurations') company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) use_payment_terminal = fields.Selection(selection=lambda self: self._get_payment_terminal_selection(), string='Use a Payment Terminal', help='Record payments with a terminal on this journal.') hide_use_payment_terminal = fields.Boolean(compute='_compute_hide_use_payment_terminal', help='Technical field which is used to ' 'hide use_payment_terminal when no payment interfaces are installed.') active = fields.Boolean(default=True) type = fields.Selection(selection=[('cash', 'Cash'), ('bank', 'Bank'), ('pay_later', 'Customer Account')], compute="_compute_type") @api.depends('type') def _compute_hide_use_payment_terminal(self): no_terminals = not bool(self._fields['use_payment_terminal'].selection(self)) for payment_method in self: payment_method.hide_use_payment_terminal = no_terminals or payment_method.type in ('cash', 'pay_later') @api.onchange('use_payment_terminal') def _onchange_use_payment_terminal(self): """Used by inheriting model to unset the value of the field related to the unselected payment terminal.""" pass @api.depends('config_ids') def _compute_open_session_ids(self): for payment_method in self: payment_method.open_session_ids = self.env['pos.session'].search([('config_id', 'in', payment_method.config_ids.ids), ('state', '!=', 'closed')]) @api.depends('journal_id', 'split_transactions') def _compute_type(self): for pm in self: if pm.journal_id.type in {'cash', 'bank'}: pm.type = pm.journal_id.type else: pm.type = 'pay_later' @api.onchange('journal_id') def _onchange_journal_id(self): if self.is_cash_count: self.use_payment_terminal = False @api.depends('type') def _compute_is_cash_count(self): for pm in self: pm.is_cash_count = pm.type == 'cash' def _is_write_forbidden(self, fields): return bool(fields and self.open_session_ids) def write(self, vals): if self._is_write_forbidden(set(vals.keys())): raise UserError('Please close and validate the following open PoS Sessions before modifying this payment method.\n' 'Open sessions: %s' % (' '.join(self.open_session_ids.mapped('name')),)) return super(PosPaymentMethod, self).write(vals)
56.640449
5,041
5,079
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError from itertools import groupby from operator import itemgetter from datetime import date class ProductTemplate(models.Model): _inherit = 'product.template' available_in_pos = fields.Boolean(string='Available in POS', help='Check if you want this product to appear in the Point of Sale.', default=False) to_weight = fields.Boolean(string='To Weigh With Scale', help="Check if the product should be weighted using the hardware scale integration.") pos_categ_id = fields.Many2one( 'pos.category', string='Point of Sale Category', help="Category used in the Point of Sale.") @api.ondelete(at_uninstall=False) def _unlink_except_open_session(self): product_ctx = dict(self.env.context or {}, active_test=False) if self.with_context(product_ctx).search_count([('id', 'in', self.ids), ('available_in_pos', '=', True)]): if self.env['pos.session'].sudo().search_count([('state', '!=', 'closed')]): raise UserError(_('You cannot delete a product saleable in point of sale while a session is still opened.')) @api.onchange('sale_ok') def _onchange_sale_ok(self): if not self.sale_ok: self.available_in_pos = False class ProductProduct(models.Model): _inherit = 'product.product' @api.ondelete(at_uninstall=False) def _unlink_except_active_pos_session(self): product_ctx = dict(self.env.context or {}, active_test=False) if self.env['pos.session'].sudo().search_count([('state', '!=', 'closed')]): if self.with_context(product_ctx).search_count([('id', 'in', self.ids), ('product_tmpl_id.available_in_pos', '=', True)]): raise UserError(_('You cannot delete a product saleable in point of sale while a session is still opened.')) def get_product_info_pos(self, price, quantity, pos_config_id): self.ensure_one() config = self.env['pos.config'].browse(pos_config_id) # Tax related taxes = self.taxes_id.compute_all(price, config.currency_id, quantity, self) grouped_taxes = {} for tax in taxes['taxes']: if tax['id'] in grouped_taxes: grouped_taxes[tax['id']]['amount'] += tax['amount']/quantity if quantity else 0 else: grouped_taxes[tax['id']] = { 'name': tax['name'], 'amount': tax['amount']/quantity if quantity else 0 } all_prices = { 'price_without_tax': taxes['total_excluded']/quantity if quantity else 0, 'price_with_tax': taxes['total_included']/quantity if quantity else 0, 'tax_details': list(grouped_taxes.values()), } # Pricelists if config.use_pricelist: pricelists = config.available_pricelist_ids else: pricelists = config.pricelist_id price_per_pricelist_id = pricelists.price_get(self.id, quantity) pricelist_list = [{'name': pl.name, 'price': price_per_pricelist_id[pl.id]} for pl in pricelists] # Warehouses warehouse_list = [ {'name': w.name, 'available_quantity': self.with_context({'warehouse': w.id}).qty_available, 'forecasted_quantity': self.with_context({'warehouse': w.id}).virtual_available, 'uom': self.uom_name} for w in self.env['stock.warehouse'].search([])] # Suppliers key = itemgetter('name') supplier_list = [] for key, group in groupby(sorted(self.seller_ids, key=key), key=key): for s in list(group): if not((s.date_start and s.date_start > date.today()) or (s.date_end and s.date_end < date.today()) or (s.min_qty > quantity)): supplier_list.append({ 'name': s.name.name, 'delay': s.delay, 'price': s.price }) break # Variants variant_list = [{'name': attribute_line.attribute_id.name, 'values': list(map(lambda attr_name: {'name': attr_name, 'search': '%s %s' % (self.name, attr_name)}, attribute_line.value_ids.mapped('name')))} for attribute_line in self.attribute_line_ids] return { 'all_prices': all_prices, 'pricelists': pricelist_list, 'warehouses': warehouse_list, 'suppliers': supplier_list, 'variants': variant_list } class UomCateg(models.Model): _inherit = 'uom.category' is_pos_groupable = fields.Boolean(string='Group Products in POS', help="Check if you want to group products of this category in point of sale orders") class Uom(models.Model): _inherit = 'uom.uom' is_pos_groupable = fields.Boolean(related='category_id.is_pos_groupable', readonly=False)
43.410256
5,079
681
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockRule(models.Model): _inherit = 'stock.rule' def _get_stock_move_values(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values): move_values = super()._get_stock_move_values(product_id, product_qty, product_uom, location_id, name, origin, company_id, values) if values.get('product_description_variants') and values.get('group_id') and values['group_id'].pos_order_id: move_values['description_picking'] = values['product_description_variants'] return move_values
45.4
681
1,649
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' sale_tax_id = fields.Many2one('account.tax', string="Default Sale Tax", related='company_id.account_sale_tax_id', readonly=False) module_pos_mercury = fields.Boolean(string="Vantiv Payment Terminal", help="The transactions are processed by Vantiv. Set your Vantiv credentials on the related payment method.") module_pos_adyen = fields.Boolean(string="Adyen Payment Terminal", help="The transactions are processed by Adyen. Set your Adyen credentials on the related payment method.") module_pos_six = fields.Boolean(string="Six Payment Terminal", help="The transactions are processed by Six. Set the IP address of the terminal on the related payment method.") update_stock_quantities = fields.Selection(related="company_id.point_of_sale_update_stock_quantities", readonly=False) module_pos_coupon = fields.Boolean("Coupon and Promotion Programs", help="Allow the use of coupon and promotion programs in PoS.") account_default_pos_receivable_account_id = fields.Many2one(string='Default Account Receivable (PoS)', related='company_id.account_default_pos_receivable_account_id', readonly=False) module_pos_gift_card = fields.Boolean("Gift Cards", help="Allow the use of gift card") def set_values(self): super(ResConfigSettings, self).set_values() if not self.group_product_pricelist: configs = self.env['pos.config'].search([('use_pricelist', '=', True)]) for config in configs: config.use_pricelist = False
71.695652
1,649
651
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields from odoo.tools.translate import _ class BarcodeRule(models.Model): _inherit = 'barcode.rule' type = fields.Selection(selection_add=[ ('weight', 'Weighted Product'), ('price', 'Priced Product'), ('discount', 'Discounted Product'), ('client', 'Client'), ('cashier', 'Cashier') ], ondelete={ 'weight': 'set default', 'price': 'set default', 'discount': 'set default', 'client': 'set default', 'cashier': 'set default', })
28.304348
651
5,180
py
PYTHON
15.0
from odoo import api, fields, models, _ from odoo.tools import formatLang, float_is_zero from odoo.exceptions import ValidationError class PosPayment(models.Model): """ Used to register payments made in a pos.order. See `payment_ids` field of pos.order model. The main characteristics of pos.payment can be read from `payment_method_id`. """ _name = "pos.payment" _description = "Point of Sale Payments" _order = "id desc" name = fields.Char(string='Label', readonly=True) pos_order_id = fields.Many2one('pos.order', string='Order', required=True) amount = fields.Monetary(string='Amount', required=True, currency_field='currency_id', readonly=True, help="Total amount of the payment.") payment_method_id = fields.Many2one('pos.payment.method', string='Payment Method', required=True) payment_date = fields.Datetime(string='Date', required=True, readonly=True, default=lambda self: fields.Datetime.now()) currency_id = fields.Many2one('res.currency', string='Currency', related='pos_order_id.currency_id') currency_rate = fields.Float(string='Conversion Rate', related='pos_order_id.currency_rate', help='Conversion rate from company currency to order currency.') partner_id = fields.Many2one('res.partner', string='Customer', related='pos_order_id.partner_id') session_id = fields.Many2one('pos.session', string='Session', related='pos_order_id.session_id', store=True, index=True) company_id = fields.Many2one('res.company', string='Company', related='pos_order_id.company_id', store=True) card_type = fields.Char('Type of card used') cardholder_name = fields.Char('Cardholder Name') transaction_id = fields.Char('Payment Transaction ID') payment_status = fields.Char('Payment Status') ticket = fields.Char('Payment Receipt Info') is_change = fields.Boolean(string='Is this payment change?', default=False) account_move_id = fields.Many2one('account.move') def name_get(self): res = [] for payment in self: if payment.name: res.append((payment.id, '%s %s' % (payment.name, formatLang(self.env, payment.amount, currency_obj=payment.currency_id)))) else: res.append((payment.id, formatLang(self.env, payment.amount, currency_obj=payment.currency_id))) return res @api.constrains('payment_method_id') def _check_payment_method_id(self): for payment in self: if payment.payment_method_id not in payment.session_id.config_id.payment_method_ids: raise ValidationError(_('The payment method selected is not allowed in the config of the POS session.')) def _export_for_ui(self, payment): return { 'payment_method_id': payment.payment_method_id.id, 'amount': payment.amount, 'payment_status': payment.payment_status, 'card_type': payment.card_type, 'cardholder_name': payment.cardholder_name, 'transaction_id': payment.transaction_id, 'ticket': payment.ticket, 'is_change': payment.is_change, } def export_for_ui(self): return self.mapped(self._export_for_ui) if self else [] def _create_payment_moves(self): result = self.env['account.move'] for payment in self: order = payment.pos_order_id payment_method = payment.payment_method_id if payment_method.type == 'pay_later' or float_is_zero(payment.amount, precision_rounding=order.currency_id.rounding): continue accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id) pos_session = order.session_id journal = pos_session.config_id.journal_id payment_move = self.env['account.move'].with_context(default_journal_id=journal.id).create({ 'journal_id': journal.id, 'date': fields.Date.context_today(payment), 'ref': _('Invoice payment for %s (%s) using %s') % (order.name, order.account_move.name, payment_method.name), 'pos_payment_ids': payment.ids, }) result |= payment_move payment.write({'account_move_id': payment_move.id}) amounts = pos_session._update_amounts({'amount': 0, 'amount_converted': 0}, {'amount': payment.amount}, payment.payment_date) credit_line_vals = pos_session._credit_amounts({ 'account_id': accounting_partner.property_account_receivable_id.id, 'partner_id': accounting_partner.id, 'move_id': payment_move.id, }, amounts['amount'], amounts['amount_converted']) debit_line_vals = pos_session._debit_amounts({ 'account_id': pos_session.company_id.account_default_pos_receivable_account_id.id, 'move_id': payment_move.id, }, amounts['amount'], amounts['amount_converted']) self.env['account.move.line'].with_context(check_move_validity=False).create([credit_line_vals, debit_line_vals]) payment_move._post() return result
53.958333
5,180
2,761
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class ResPartner(models.Model): _inherit = 'res.partner' pos_order_count = fields.Integer( compute='_compute_pos_order', help="The number of point of sales orders related to this customer", groups="point_of_sale.group_pos_user", ) pos_order_ids = fields.One2many('pos.order', 'partner_id', readonly=True) def _compute_pos_order(self): # retrieve all children partners and prefetch 'parent_id' on them all_partners = self.with_context(active_test=False).search([('id', 'child_of', self.ids)]) all_partners.read(['parent_id']) pos_order_data = self.env['pos.order'].read_group( domain=[('partner_id', 'in', all_partners.ids)], fields=['partner_id'], groupby=['partner_id'] ) self.pos_order_count = 0 for group in pos_order_data: partner = self.browse(group['partner_id'][0]) while partner: if partner in self: partner.pos_order_count += group['partner_id_count'] partner = partner.parent_id def action_view_pos_order(self): ''' This function returns an action that displays the pos orders from partner. ''' action = self.env['ir.actions.act_window']._for_xml_id('point_of_sale.action_pos_pos_form') if self.is_company: action['domain'] = [('partner_id.commercial_partner_id.id', '=', self.id)] else: action['domain'] = [('partner_id.id', '=', self.id)] return action @api.model def create_from_ui(self, partner): """ create or modify a partner from the point of sale ui. partner contains the partner's fields. """ # image is a dataurl, get the data after the comma if partner.get('image_1920'): partner['image_1920'] = partner['image_1920'].split(',')[1] partner_id = partner.pop('id', False) if partner_id: # Modifying existing partner self.browse(partner_id).write(partner) else: partner_id = self.create(partner).id return partner_id @api.ondelete(at_uninstall=False) def _unlink_except_active_pos_session(self): running_sessions = self.env['pos.session'].sudo().search([('state', '!=', 'closed')]) if running_sessions: raise UserError( _("You cannot delete contacts while there are active PoS sessions. Close the session(s) %s first.") % ", ".join(session.name for session in running_sessions) )
41.208955
2,761
65,808
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from datetime import timedelta from functools import partial from itertools import groupby import psycopg2 import pytz import re from odoo import api, fields, models, tools, _ from odoo.tools import float_is_zero, float_round, float_repr, float_compare from odoo.exceptions import ValidationError, UserError from odoo.http import request from odoo.osv.expression import AND import base64 _logger = logging.getLogger(__name__) class PosOrder(models.Model): _name = "pos.order" _description = "Point of Sale Orders" _order = "date_order desc, name desc, id desc" @api.model def _amount_line_tax(self, line, fiscal_position_id): taxes = line.tax_ids.filtered(lambda t: t.company_id.id == line.order_id.company_id.id) taxes = fiscal_position_id.map_tax(taxes) price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = taxes.compute_all(price, line.order_id.pricelist_id.currency_id, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)['taxes'] return sum(tax.get('amount', 0.0) for tax in taxes) @api.model def _order_fields(self, ui_order): process_line = partial(self.env['pos.order.line']._order_line_fields, session_id=ui_order['pos_session_id']) return { 'user_id': ui_order['user_id'] or False, 'session_id': ui_order['pos_session_id'], 'lines': [process_line(l) for l in ui_order['lines']] if ui_order['lines'] else False, 'pos_reference': ui_order['name'], 'sequence_number': ui_order['sequence_number'], 'partner_id': ui_order['partner_id'] or False, 'date_order': ui_order['creation_date'].replace('T', ' ')[:19], 'fiscal_position_id': ui_order['fiscal_position_id'], 'pricelist_id': ui_order['pricelist_id'], 'amount_paid': ui_order['amount_paid'], 'amount_total': ui_order['amount_total'], 'amount_tax': ui_order['amount_tax'], 'amount_return': ui_order['amount_return'], 'company_id': self.env['pos.session'].browse(ui_order['pos_session_id']).company_id.id, 'to_invoice': ui_order['to_invoice'] if "to_invoice" in ui_order else False, 'to_ship': ui_order['to_ship'] if "to_ship" in ui_order else False, 'is_tipped': ui_order.get('is_tipped', False), 'tip_amount': ui_order.get('tip_amount', 0), } @api.model def _payment_fields(self, order, ui_paymentline): return { 'amount': ui_paymentline['amount'] or 0.0, 'payment_date': ui_paymentline['name'], 'payment_method_id': ui_paymentline['payment_method_id'], 'card_type': ui_paymentline.get('card_type'), 'cardholder_name': ui_paymentline.get('cardholder_name'), 'transaction_id': ui_paymentline.get('transaction_id'), 'payment_status': ui_paymentline.get('payment_status'), 'ticket': ui_paymentline.get('ticket'), 'pos_order_id': order.id, } # This deals with orders that belong to a closed session. In order # to recover from this situation we create a new rescue session, # making it obvious that something went wrong. # A new, separate, rescue session is preferred for every such recovery, # to avoid adding unrelated orders to live sessions. def _get_valid_session(self, order): PosSession = self.env['pos.session'] closed_session = PosSession.browse(order['pos_session_id']) _logger.warning('session %s (ID: %s) was closed but received order %s (total: %s) belonging to it', closed_session.name, closed_session.id, order['name'], order['amount_total']) rescue_session = PosSession.search([ ('state', 'not in', ('closed', 'closing_control')), ('rescue', '=', True), ('config_id', '=', closed_session.config_id.id), ], limit=1) if rescue_session: _logger.warning('reusing recovery session %s for saving order %s', rescue_session.name, order['name']) return rescue_session _logger.warning('attempting to create recovery session for saving order %s', order['name']) new_session = PosSession.create({ 'config_id': closed_session.config_id.id, 'name': _('(RESCUE FOR %(session)s)') % {'session': closed_session.name}, 'rescue': True, # avoid conflict with live sessions }) # bypass opening_control (necessary when using cash control) new_session.action_pos_session_open() return new_session def _get_fields_for_draft_order(self): """This method is here to be overridden in order to add fields that are required for draft orders.""" return [] @api.model def _process_order(self, order, draft, existing_order): """Create or update an pos.order from a given dictionary. :param dict order: dictionary representing the order. :param bool draft: Indicate that the pos_order is not validated yet. :param existing_order: order to be updated or False. :type existing_order: pos.order. :returns: id of created/updated pos.order :rtype: int """ order = order['data'] pos_session = self.env['pos.session'].browse(order['pos_session_id']) if pos_session.state == 'closing_control' or pos_session.state == 'closed': order['pos_session_id'] = self._get_valid_session(order).id pos_order = False if not existing_order: pos_order = self.create(self._order_fields(order)) else: pos_order = existing_order pos_order.lines.unlink() order['user_id'] = pos_order.user_id.id pos_order.write(self._order_fields(order)) pos_order = pos_order.with_company(pos_order.company_id) self = self.with_company(pos_order.company_id) self._process_payment_lines(order, pos_order, pos_session, draft) if not draft: try: pos_order.action_pos_order_paid() except psycopg2.DatabaseError: # do not hide transactional errors, the order(s) won't be saved! raise except Exception as e: _logger.error('Could not fully process the POS Order: %s', tools.ustr(e)) pos_order._create_order_picking() pos_order._compute_total_cost_in_real_time() if pos_order.to_invoice and pos_order.state == 'paid': pos_order._generate_pos_order_invoice() return pos_order.id def _process_payment_lines(self, pos_order, order, pos_session, draft): """Create account.bank.statement.lines from the dictionary given to the parent function. If the payment_line is an updated version of an existing one, the existing payment_line will first be removed before making a new one. :param pos_order: dictionary representing the order. :type pos_order: dict. :param order: Order object the payment lines should belong to. :type order: pos.order :param pos_session: PoS session the order was created in. :type pos_session: pos.session :param draft: Indicate that the pos_order is not validated yet. :type draft: bool. """ prec_acc = order.pricelist_id.currency_id.decimal_places order_bank_statement_lines= self.env['pos.payment'].search([('pos_order_id', '=', order.id)]) order_bank_statement_lines.unlink() for payments in pos_order['statement_ids']: order.add_payment(self._payment_fields(order, payments[2])) order.amount_paid = sum(order.payment_ids.mapped('amount')) if not draft and not float_is_zero(pos_order['amount_return'], prec_acc): cash_payment_method = pos_session.payment_method_ids.filtered('is_cash_count')[:1] if not cash_payment_method: raise UserError(_("No cash statement found for this session. Unable to record returned cash.")) return_payment_vals = { 'name': _('return'), 'pos_order_id': order.id, 'amount': -pos_order['amount_return'], 'payment_date': fields.Datetime.now(), 'payment_method_id': cash_payment_method.id, 'is_change': True, } order.add_payment(return_payment_vals) def _prepare_invoice_line(self, order_line): name = order_line.product_id.get_product_multiline_description_sale() return { 'product_id': order_line.product_id.id, 'quantity': order_line.qty if self.amount_total >= 0 else -order_line.qty, 'discount': order_line.discount, 'price_unit': order_line.price_unit, 'name': name, 'tax_ids': [(6, 0, order_line.tax_ids_after_fiscal_position.ids)], 'product_uom_id': order_line.product_uom_id.id, } def _prepare_invoice_lines(self): invoice_lines = [] for line in self.lines: invoice_lines.append((0, None, self._prepare_invoice_line(line))) if line.order_id.pricelist_id.discount_policy == 'without_discount' and float_compare(line.price_unit, line.product_id.lst_price, precision_rounding=self.currency_id.rounding) < 0: invoice_lines.append((0, None, { 'name': _('Price discount from %s -> %s', float_repr(line.product_id.lst_price, self.currency_id.decimal_places), float_repr(line.price_unit, self.currency_id.decimal_places)), 'display_type': 'line_note', })) if line.customer_note: invoice_lines.append((0, None, { 'name': line.customer_note, 'display_type': 'line_note', })) return invoice_lines def _get_pos_anglo_saxon_price_unit(self, product, partner_id, quantity): moves = self.filtered(lambda o: o.partner_id.id == partner_id)\ .mapped('picking_ids.move_lines')\ ._filter_anglo_saxon_moves(product)\ .sorted(lambda x: x.date) price_unit = product.with_company(self.company_id)._compute_average_price(0, quantity, moves) return price_unit name = fields.Char(string='Order Ref', required=True, readonly=True, copy=False, default='/') date_order = fields.Datetime(string='Date', readonly=True, index=True, default=fields.Datetime.now) user_id = fields.Many2one( comodel_name='res.users', string='Responsible', help="Person who uses the cash register. It can be a reliever, a student or an interim employee.", default=lambda self: self.env.uid, states={'done': [('readonly', True)], 'invoiced': [('readonly', True)]}, ) amount_tax = fields.Float(string='Taxes', digits=0, readonly=True, required=True) amount_total = fields.Float(string='Total', digits=0, readonly=True, required=True) amount_paid = fields.Float(string='Paid', states={'draft': [('readonly', False)]}, readonly=True, digits=0, required=True) amount_return = fields.Float(string='Returned', digits=0, required=True, readonly=True) margin = fields.Monetary(string="Margin", compute='_compute_margin') margin_percent = fields.Float(string="Margin (%)", compute='_compute_margin', digits=(12, 4)) is_total_cost_computed = fields.Boolean(compute='_compute_is_total_cost_computed', help="Allows to know if all the total cost of the order lines have already been computed") lines = fields.One2many('pos.order.line', 'order_id', string='Order Lines', states={'draft': [('readonly', False)]}, readonly=True, copy=True) company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True) pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', required=True, states={ 'draft': [('readonly', False)]}, readonly=True) partner_id = fields.Many2one('res.partner', string='Customer', change_default=True, index=True, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}) sequence_number = fields.Integer(string='Sequence Number', help='A session-unique sequence number for the order', default=1) session_id = fields.Many2one( 'pos.session', string='Session', required=True, index=True, domain="[('state', '=', 'opened')]", states={'draft': [('readonly', False)]}, readonly=True) config_id = fields.Many2one('pos.config', related='session_id.config_id', string="Point of Sale", readonly=False) currency_id = fields.Many2one('res.currency', related='config_id.currency_id', string="Currency") currency_rate = fields.Float("Currency Rate", compute='_compute_currency_rate', compute_sudo=True, store=True, digits=0, readonly=True, help='The rate of the currency to the currency of rate applicable at the date of the order') invoice_group = fields.Boolean(related="config_id.module_account", readonly=False) state = fields.Selection( [('draft', 'New'), ('cancel', 'Cancelled'), ('paid', 'Paid'), ('done', 'Posted'), ('invoiced', 'Invoiced')], 'Status', readonly=True, copy=False, default='draft') account_move = fields.Many2one('account.move', string='Invoice', readonly=True, copy=False, index=True) picking_ids = fields.One2many('stock.picking', 'pos_order_id') picking_count = fields.Integer(compute='_compute_picking_count') failed_pickings = fields.Boolean(compute='_compute_picking_count') picking_type_id = fields.Many2one('stock.picking.type', related='session_id.config_id.picking_type_id', string="Operation Type", readonly=False) procurement_group_id = fields.Many2one('procurement.group', 'Procurement Group', copy=False) note = fields.Text(string='Internal Notes') nb_print = fields.Integer(string='Number of Print', readonly=True, copy=False, default=0) pos_reference = fields.Char(string='Receipt Number', readonly=True, copy=False) sale_journal = fields.Many2one('account.journal', related='session_id.config_id.journal_id', string='Sales Journal', store=True, readonly=True, ondelete='restrict') fiscal_position_id = fields.Many2one( comodel_name='account.fiscal.position', string='Fiscal Position', readonly=True, states={'draft': [('readonly', False)]}, ) payment_ids = fields.One2many('pos.payment', 'pos_order_id', string='Payments', readonly=True) session_move_id = fields.Many2one('account.move', string='Session Journal Entry', related='session_id.move_id', readonly=True, copy=False) to_invoice = fields.Boolean('To invoice', copy=False) to_ship = fields.Boolean('To ship') is_invoiced = fields.Boolean('Is Invoiced', compute='_compute_is_invoiced') is_tipped = fields.Boolean('Is this already tipped?', readonly=True) tip_amount = fields.Float(string='Tip Amount', digits=0, readonly=True) refund_orders_count = fields.Integer('Number of Refund Orders', compute='_compute_refund_related_fields') is_refunded = fields.Boolean(compute='_compute_refund_related_fields') refunded_order_ids = fields.Many2many('pos.order', compute='_compute_refund_related_fields') has_refundable_lines = fields.Boolean('Has Refundable Lines', compute='_compute_has_refundable_lines') refunded_orders_count = fields.Integer(compute='_compute_refund_related_fields') @api.depends('lines.refund_orderline_ids', 'lines.refunded_orderline_id') def _compute_refund_related_fields(self): for order in self: order.refund_orders_count = len(order.mapped('lines.refund_orderline_ids.order_id')) order.is_refunded = order.refund_orders_count > 0 order.refunded_order_ids = order.mapped('lines.refunded_orderline_id.order_id') order.refunded_orders_count = len(order.refunded_order_ids) @api.depends('lines.refunded_qty', 'lines.qty') def _compute_has_refundable_lines(self): digits = self.env['decimal.precision'].precision_get('Product Unit of Measure') for order in self: order.has_refundable_lines = any([float_compare(line.qty, line.refunded_qty, digits) > 0 for line in order.lines]) @api.depends('account_move') def _compute_is_invoiced(self): for order in self: order.is_invoiced = bool(order.account_move) @api.depends('picking_ids', 'picking_ids.state') def _compute_picking_count(self): for order in self: order.picking_count = len(order.picking_ids) order.failed_pickings = bool(order.picking_ids.filtered(lambda p: p.state != 'done')) @api.depends('date_order', 'company_id', 'currency_id', 'company_id.currency_id') def _compute_currency_rate(self): for order in self: order.currency_rate = self.env['res.currency']._get_conversion_rate(order.company_id.currency_id, order.currency_id, order.company_id, order.date_order) @api.depends('lines.is_total_cost_computed') def _compute_is_total_cost_computed(self): for order in self: order.is_total_cost_computed = not False in order.lines.mapped('is_total_cost_computed') def _compute_total_cost_in_real_time(self): """ Compute the total cost of the order when it's processed by the server. It will compute the total cost of all the lines if it's possible. If a margin of one of the order's lines cannot be computed (because of session_id.update_stock_at_closing), then the margin of said order is not computed (it will be computed when closing the session). """ for order in self: lines = order.lines if not order._should_create_picking_real_time(): storable_fifo_avco_lines = lines.filtered(lambda l: l._is_product_storable_fifo_avco()) lines -= storable_fifo_avco_lines stock_moves = order.picking_ids.move_lines lines._compute_total_cost(stock_moves) def _compute_total_cost_at_session_closing(self, stock_moves): """ Compute the margin at the end of the session. This method should be called to compute the remaining lines margin containing a storable product with a fifo/avco cost method and then compute the order margin """ for order in self: storable_fifo_avco_lines = order.lines.filtered(lambda l: l._is_product_storable_fifo_avco()) storable_fifo_avco_lines._compute_total_cost(stock_moves) @api.depends('lines.margin', 'is_total_cost_computed') def _compute_margin(self): for order in self: if order.is_total_cost_computed: order.margin = sum(order.lines.mapped('margin')) amount_untaxed = order.currency_id.round(sum(line.price_subtotal for line in order.lines)) order.margin_percent = not float_is_zero(amount_untaxed, precision_rounding=order.currency_id.rounding) and order.margin / amount_untaxed or 0 else: order.margin = 0 order.margin_percent = 0 @api.onchange('payment_ids', 'lines') def _onchange_amount_all(self): for order in self: if not order.pricelist_id.currency_id: raise UserError(_("You can't: create a pos order from the backend interface, or unset the pricelist, or create a pos.order in a python test with Form tool, or edit the form view in studio if no PoS order exist")) currency = order.pricelist_id.currency_id order.amount_paid = sum(payment.amount for payment in order.payment_ids) order.amount_return = sum(payment.amount < 0 and payment.amount or 0 for payment in order.payment_ids) order.amount_tax = currency.round(sum(self._amount_line_tax(line, order.fiscal_position_id) for line in order.lines)) amount_untaxed = currency.round(sum(line.price_subtotal for line in order.lines)) order.amount_total = order.amount_tax + amount_untaxed def _compute_batch_amount_all(self): """ Does essentially the same thing as `_onchange_amount_all` but only for actually existing records It is intended as a helper method , not as a business one Practical to be used for migrations """ amounts = {order_id: {'paid': 0, 'return': 0, 'taxed': 0, 'taxes': 0} for order_id in self.ids} for order in self.env['pos.payment'].read_group([('pos_order_id', 'in', self.ids)], ['pos_order_id', 'amount'], ['pos_order_id']): amounts[order['pos_order_id'][0]]['paid'] = order['amount'] for order in self.env['pos.payment'].read_group(['&', ('pos_order_id', 'in', self.ids), ('amount', '<', 0)], ['pos_order_id', 'amount'], ['pos_order_id']): amounts[order['pos_order_id'][0]]['return'] = order['amount'] for order in self.env['pos.order.line'].read_group([('order_id', 'in', self.ids)], ['order_id', 'price_subtotal', 'price_subtotal_incl'], ['order_id']): amounts[order['order_id'][0]]['taxed'] = order['price_subtotal_incl'] amounts[order['order_id'][0]]['taxes'] = order['price_subtotal_incl'] - order['price_subtotal'] for order in self: currency = order.pricelist_id.currency_id order.write({ 'amount_paid': amounts[order.id]['paid'], 'amount_return': amounts[order.id]['return'], 'amount_tax': currency.round(amounts[order.id]['taxes']), 'amount_total': currency.round(amounts[order.id]['taxed']) }) @api.onchange('partner_id') def _onchange_partner_id(self): if self.partner_id: self.pricelist_id = self.partner_id.property_product_pricelist.id @api.ondelete(at_uninstall=False) def _unlink_except_draft_or_cancel(self): for pos_order in self.filtered(lambda pos_order: pos_order.state not in ['draft', 'cancel']): raise UserError(_('In order to delete a sale, it must be new or cancelled.')) @api.model def create(self, values): session = self.env['pos.session'].browse(values['session_id']) values = self._complete_values_from_session(session, values) return super(PosOrder, self).create(values) @api.model def _complete_values_from_session(self, session, values): if values.get('state') and values['state'] == 'paid': values['name'] = self._compute_order_name() values.setdefault('pricelist_id', session.config_id.pricelist_id.id) values.setdefault('fiscal_position_id', session.config_id.default_fiscal_position_id.id) values.setdefault('company_id', session.config_id.company_id.id) return values def write(self, vals): for order in self: if vals.get('state') and vals['state'] == 'paid' and order.name == '/': vals['name'] = self._compute_order_name() return super(PosOrder, self).write(vals) def _compute_order_name(self): if len(self.refunded_order_ids) != 0: return ','.join(self.refunded_order_ids.mapped('name')) + _(' REFUND') else: return self.session_id.config_id.sequence_id._next() def action_stock_picking(self): self.ensure_one() action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_ready') action['display_name'] = _('Pickings') action['context'] = {} action['domain'] = [('id', 'in', self.picking_ids.ids)] return action def action_view_invoice(self): return { 'name': _('Customer Invoice'), 'view_mode': 'form', 'view_id': self.env.ref('account.view_move_form').id, 'res_model': 'account.move', 'context': "{'move_type':'out_invoice'}", 'type': 'ir.actions.act_window', 'res_id': self.account_move.id, } def action_view_refund_orders(self): return { 'name': _('Refund Orders'), 'view_mode': 'tree,form', 'res_model': 'pos.order', 'type': 'ir.actions.act_window', 'domain': [('id', 'in', self.mapped('lines.refund_orderline_ids.order_id').ids)], } def action_view_refunded_orders(self): return { 'name': _('Refunded Orders'), 'view_mode': 'tree,form', 'res_model': 'pos.order', 'type': 'ir.actions.act_window', 'domain': [('id', 'in', self.refunded_order_ids.ids)], } def _is_pos_order_paid(self): return float_is_zero(self._get_rounded_amount(self.amount_total) - self.amount_paid, precision_rounding=self.currency_id.rounding) def _get_rounded_amount(self, amount): if self.config_id.cash_rounding: amount = float_round(amount, precision_rounding=self.config_id.rounding_method.rounding, rounding_method=self.config_id.rounding_method.rounding_method) currency = self.currency_id return currency.round(amount) if currency else amount def _get_partner_bank_id(self): bank_partner_id = False has_pay_later = any(not pm.journal_id for pm in self.payment_ids.mapped('payment_method_id')) if has_pay_later: if self.amount_total <= 0 and self.partner_id.bank_ids: bank_partner_id = self.partner_id.bank_ids[0].id elif self.amount_total >= 0 and self.company_id.partner_id.bank_ids: bank_partner_id = self.company_id.partner_id.bank_ids[0].id return bank_partner_id def _create_invoice(self, move_vals): self.ensure_one() new_move = self.env['account.move'].sudo().with_company(self.company_id).with_context(default_move_type=move_vals['move_type']).create(move_vals) message = _("This invoice has been created from the point of sale session: <a href=# data-oe-model=pos.order data-oe-id=%d>%s</a>") % (self.id, self.name) new_move.message_post(body=message) if self.config_id.cash_rounding: rounding_applied = float_round(self.amount_paid - self.amount_total, precision_rounding=new_move.currency_id.rounding) rounding_line = new_move.line_ids.filtered(lambda line: line.is_rounding_line) if rounding_line and rounding_line.debit > 0: rounding_line_difference = rounding_line.debit + rounding_applied elif rounding_line and rounding_line.credit > 0: rounding_line_difference = -rounding_line.credit + rounding_applied else: rounding_line_difference = rounding_applied if rounding_applied: if rounding_applied > 0.0: account_id = new_move.invoice_cash_rounding_id.loss_account_id.id else: account_id = new_move.invoice_cash_rounding_id.profit_account_id.id if rounding_line: if rounding_line_difference: rounding_line.with_context(check_move_validity=False).write({ 'debit': rounding_applied < 0.0 and -rounding_applied or 0.0, 'credit': rounding_applied > 0.0 and rounding_applied or 0.0, 'account_id': account_id, 'price_unit': rounding_applied, }) else: self.env['account.move.line'].with_context(check_move_validity=False).create({ 'debit': rounding_applied < 0.0 and -rounding_applied or 0.0, 'credit': rounding_applied > 0.0 and rounding_applied or 0.0, 'quantity': 1.0, 'amount_currency': rounding_applied, 'partner_id': new_move.partner_id.id, 'move_id': new_move.id, 'currency_id': new_move.currency_id if new_move.currency_id != new_move.company_id.currency_id else False, 'company_id': new_move.company_id.id, 'company_currency_id': new_move.company_id.currency_id.id, 'is_rounding_line': True, 'sequence': 9999, 'name': new_move.invoice_cash_rounding_id.name, 'account_id': account_id, }) else: if rounding_line: rounding_line.with_context(check_move_validity=False).unlink() if rounding_line_difference: existing_terms_line = new_move.line_ids.filtered( lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) if existing_terms_line.debit > 0: existing_terms_line_new_val = float_round( existing_terms_line.debit + rounding_line_difference, precision_rounding=new_move.currency_id.rounding) else: existing_terms_line_new_val = float_round( -existing_terms_line.credit + rounding_line_difference, precision_rounding=new_move.currency_id.rounding) existing_terms_line.write({ 'debit': existing_terms_line_new_val > 0.0 and existing_terms_line_new_val or 0.0, 'credit': existing_terms_line_new_val < 0.0 and -existing_terms_line_new_val or 0.0, }) new_move._recompute_payment_terms_lines() return new_move def action_pos_order_paid(self): self.ensure_one() # TODO: add support for mix of cash and non-cash payments when both cash_rounding and only_round_cash_method are True if not self.config_id.cash_rounding \ or self.config_id.only_round_cash_method \ and not any(p.payment_method_id.is_cash_count for p in self.payment_ids): total = self.amount_total else: total = float_round(self.amount_total, precision_rounding=self.config_id.rounding_method.rounding, rounding_method=self.config_id.rounding_method.rounding_method) isPaid = float_is_zero(total - self.amount_paid, precision_rounding=self.currency_id.rounding) if not isPaid and not self.config_id.cash_rounding: raise UserError(_("Order %s is not fully paid.", self.name)) elif not isPaid and self.config_id.cash_rounding: currency = self.currency_id if self.config_id.rounding_method.rounding_method == "HALF-UP": maxDiff = currency.round(self.config_id.rounding_method.rounding / 2) else: maxDiff = currency.round(self.config_id.rounding_method.rounding) diff = currency.round(self.amount_total - self.amount_paid) if not abs(diff) <= maxDiff: raise UserError(_("Order %s is not fully paid.", self.name)) self.write({'state': 'paid'}) return True def _prepare_invoice_vals(self): self.ensure_one() timezone = pytz.timezone(self._context.get('tz') or self.env.user.tz or 'UTC') vals = { 'invoice_origin': self.name, 'journal_id': self.session_id.config_id.invoice_journal_id.id, 'move_type': 'out_invoice' if self.amount_total >= 0 else 'out_refund', 'ref': self.name, 'partner_id': self.partner_id.id, 'partner_bank_id': self._get_partner_bank_id(), # considering partner's sale pricelist's currency 'currency_id': self.pricelist_id.currency_id.id, 'invoice_user_id': self.user_id.id, 'invoice_date': self.date_order.astimezone(timezone).date(), 'fiscal_position_id': self.fiscal_position_id.id, 'invoice_line_ids': self._prepare_invoice_lines(), 'invoice_payment_term_id': self.partner_id.property_payment_term_id.id or False, 'invoice_cash_rounding_id': self.config_id.rounding_method.id if self.config_id.cash_rounding and (not self.config_id.only_round_cash_method or any(p.payment_method_id.is_cash_count for p in self.payment_ids)) else False } if self.refunded_order_ids.account_move: vals['ref'] = _('Reversal of: %s', self.refunded_order_ids.account_move.name) vals['reversed_entry_id'] = self.refunded_order_ids.account_move.id if self.note: vals.update({'narration': self.note}) return vals def action_pos_order_invoice(self): self.write({'to_invoice': True}) res = self._generate_pos_order_invoice() if self.company_id.anglo_saxon_accounting and self.session_id.update_stock_at_closing and not self.to_ship: self._create_order_picking() return res def _generate_pos_order_invoice(self): moves = self.env['account.move'] for order in self: # Force company for all SUPERUSER_ID action if order.account_move: moves += order.account_move continue if not order.partner_id: raise UserError(_('Please provide a partner for the sale.')) move_vals = order._prepare_invoice_vals() new_move = order._create_invoice(move_vals) order.write({'account_move': new_move.id, 'state': 'invoiced'}) new_move.sudo().with_company(order.company_id)._post() moves += new_move order._apply_invoice_payments() if not moves: return {} return { 'name': _('Customer Invoice'), 'view_mode': 'form', 'view_id': self.env.ref('account.view_move_form').id, 'res_model': 'account.move', 'context': "{'move_type':'out_invoice'}", 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': moves and moves.ids[0] or False, } # this method is unused, and so is the state 'cancel' def action_pos_order_cancel(self): return self.write({'state': 'cancel'}) def _apply_invoice_payments(self): receivable_account = self.env["res.partner"]._find_accounting_partner(self.partner_id).property_account_receivable_id payment_moves = self.payment_ids.sudo().with_company(self.company_id)._create_payment_moves() if receivable_account.reconcile: invoice_receivables = self.account_move.line_ids.filtered(lambda line: line.account_id == receivable_account and not line.reconciled) if invoice_receivables: payment_receivables = payment_moves.mapped('line_ids').filtered(lambda line: line.account_id == receivable_account and line.partner_id) (invoice_receivables | payment_receivables).sorted(key=lambda l: l.amount_currency).sudo().with_company(self.company_id).reconcile() @api.model def create_from_ui(self, orders, draft=False): """ Create and update Orders from the frontend PoS application. Create new orders and update orders that are in draft status. If an order already exists with a status diferent from 'draft'it will be discareded, otherwise it will be saved to the database. If saved with 'draft' status the order can be overwritten later by this function. :param orders: dictionary with the orders to be created. :type orders: dict. :param draft: Indicate if the orders are ment to be finalised or temporarily saved. :type draft: bool. :Returns: list -- list of db-ids for the created and updated orders. """ order_ids = [] for order in orders: existing_order = False if 'server_id' in order['data']: existing_order = self.env['pos.order'].search(['|', ('id', '=', order['data']['server_id']), ('pos_reference', '=', order['data']['name'])], limit=1) if (existing_order and existing_order.state == 'draft') or not existing_order: order_ids.append(self._process_order(order, draft, existing_order)) return self.env['pos.order'].search_read(domain = [('id', 'in', order_ids)], fields = ['id', 'pos_reference']) def _should_create_picking_real_time(self): return not self.session_id.update_stock_at_closing or (self.company_id.anglo_saxon_accounting and self.to_invoice) def _create_order_picking(self): self.ensure_one() if self.to_ship: self.lines._launch_stock_rule_from_pos_order_lines() else: if self._should_create_picking_real_time(): picking_type = self.config_id.picking_type_id if self.partner_id.property_stock_customer: destination_id = self.partner_id.property_stock_customer.id elif not picking_type or not picking_type.default_location_dest_id: destination_id = self.env['stock.warehouse']._get_partner_locations()[0].id else: destination_id = picking_type.default_location_dest_id.id pickings = self.env['stock.picking']._create_picking_from_pos_order_lines(destination_id, self.lines, picking_type, self.partner_id) pickings.write({'pos_session_id': self.session_id.id, 'pos_order_id': self.id, 'origin': self.name}) def add_payment(self, data): """Create a new payment for the order""" self.ensure_one() self.env['pos.payment'].create(data) self.amount_paid = sum(self.payment_ids.mapped('amount')) def _prepare_refund_values(self, current_session): self.ensure_one() return { 'name': self.name + _(' REFUND'), 'session_id': current_session.id, 'date_order': fields.Datetime.now(), 'pos_reference': self.pos_reference, 'lines': False, 'amount_tax': -self.amount_tax, 'amount_total': -self.amount_total, 'amount_paid': 0, 'is_total_cost_computed': False } def _prepare_mail_values(self, name, client, ticket): message = _("<p>Dear %s,<br/>Here is your electronic ticket for the %s. </p>") % (client['name'], name) return { 'subject': _('Receipt %s', name), 'body_html': message, 'author_id': self.env.user.partner_id.id, 'email_from': self.env.company.email or self.env.user.email_formatted, 'email_to': client['email'], 'attachment_ids': self._add_mail_attachment(name, ticket), } def refund(self): """Create a copy of order for refund order""" refund_orders = self.env['pos.order'] for order in self: # When a refund is performed, we are creating it in a session having the same config as the original # order. It can be the same session, or if it has been closed the new one that has been opened. current_session = order.session_id.config_id.current_session_id if not current_session: raise UserError(_('To return product(s), you need to open a session in the POS %s', order.session_id.config_id.display_name)) refund_order = order.copy( order._prepare_refund_values(current_session) ) for line in order.lines: PosOrderLineLot = self.env['pos.pack.operation.lot'] for pack_lot in line.pack_lot_ids: PosOrderLineLot += pack_lot.copy() line.copy(line._prepare_refund_data(refund_order, PosOrderLineLot)) refund_orders |= refund_order return { 'name': _('Return Products'), 'view_mode': 'form', 'res_model': 'pos.order', 'res_id': refund_orders.ids[0], 'view_id': False, 'context': self.env.context, 'type': 'ir.actions.act_window', 'target': 'current', } def _add_mail_attachment(self, name, ticket): filename = 'Receipt-' + name + '.jpg' receipt = self.env['ir.attachment'].create({ 'name': filename, 'type': 'binary', 'datas': ticket, 'res_model': 'pos.order', 'res_id': self.ids[0], 'mimetype': 'image/jpeg', }) attachment = [(4, receipt.id)] if self.mapped('account_move'): report = self.env.ref('account.account_invoices')._render_qweb_pdf(self.account_move.ids[0]) filename = name + '.pdf' invoice = self.env['ir.attachment'].create({ 'name': filename, 'type': 'binary', 'datas': base64.b64encode(report[0]), 'res_model': 'pos.order', 'res_id': self.ids[0], 'mimetype': 'application/x-pdf' }) attachment += [(4, invoice.id)] return attachment def action_receipt_to_customer(self, name, client, ticket): if not self: return False if not client.get('email'): return False mail = self.env['mail.mail'].sudo().create(self._prepare_mail_values(name, client, ticket)) mail.send() @api.model def remove_from_ui(self, server_ids): """ Remove orders from the frontend PoS application Remove orders from the server by id. :param server_ids: list of the id's of orders to remove from the server. :type server_ids: list. :returns: list -- list of db-ids for the removed orders. """ orders = self.search([('id', 'in', server_ids),('state', '=', 'draft')]) orders.write({'state': 'cancel'}) # TODO Looks like delete cascade is a better solution. orders.mapped('payment_ids').sudo().unlink() orders.sudo().unlink() return orders.ids @api.model def search_paid_order_ids(self, config_id, domain, limit, offset): """Search for 'paid' orders that satisfy the given domain, limit and offset.""" default_domain = ['&', ('config_id', '=', config_id), '!', '|', ('state', '=', 'draft'), ('state', '=', 'cancelled')] real_domain = AND([domain, default_domain]) ids = self.search(AND([domain, default_domain]), limit=limit, offset=offset).ids totalCount = self.search_count(real_domain) return {'ids': ids, 'totalCount': totalCount} def _export_for_ui(self, order): timezone = pytz.timezone(self._context.get('tz') or self.env.user.tz or 'UTC') return { 'lines': [[0, 0, line] for line in order.lines.export_for_ui()], 'statement_ids': [[0, 0, payment] for payment in order.payment_ids.export_for_ui()], 'name': order.pos_reference, 'uid': re.search('([0-9]|-){14}', order.pos_reference).group(0), 'amount_paid': order.amount_paid, 'amount_total': order.amount_total, 'amount_tax': order.amount_tax, 'amount_return': order.amount_return, 'pos_session_id': order.session_id.id, 'is_session_closed': order.session_id.state == 'closed', 'pricelist_id': order.pricelist_id.id, 'partner_id': order.partner_id.id, 'user_id': order.user_id.id, 'sequence_number': order.sequence_number, 'creation_date': str(order.date_order.astimezone(timezone)), 'fiscal_position_id': order.fiscal_position_id.id, 'to_invoice': order.to_invoice, 'to_ship': order.to_ship, 'state': order.state, 'account_move': order.account_move.id, 'id': order.id, 'is_tipped': order.is_tipped, 'tip_amount': order.tip_amount, } def _get_fields_for_order_line(self): """This function is here to be overriden""" return [] def _prepare_order_line(self, order_line): """This function is here to be overriden""" return order_line def export_for_ui(self): """ Returns a list of dict with each item having similar signature as the return of `export_as_JSON` of models.Order. This is useful for back-and-forth communication between the pos frontend and backend. """ return self.mapped(self._export_for_ui) if self else [] class PosOrderLine(models.Model): _name = "pos.order.line" _description = "Point of Sale Order Lines" _rec_name = "product_id" def _order_line_fields(self, line, session_id=None): if line and 'name' not in line[2]: session = self.env['pos.session'].browse(session_id).exists() if session_id else None if session and session.config_id.sequence_line_id: # set name based on the sequence specified on the config line[2]['name'] = session.config_id.sequence_line_id._next() else: # fallback on any pos.order.line sequence line[2]['name'] = self.env['ir.sequence'].next_by_code('pos.order.line') if line and 'tax_ids' not in line[2]: product = self.env['product.product'].browse(line[2]['product_id']) line[2]['tax_ids'] = [(6, 0, [x.id for x in product.taxes_id])] # Clean up fields sent by the JS line = [ line[0], line[1], {k: v for k, v in line[2].items() if k in self.env['pos.order.line']._fields} ] return line company_id = fields.Many2one('res.company', string='Company', related="order_id.company_id", store=True) name = fields.Char(string='Line No', required=True, copy=False) notice = fields.Char(string='Discount Notice') product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], required=True, change_default=True) price_unit = fields.Float(string='Unit Price', digits=0) qty = fields.Float('Quantity', digits='Product Unit of Measure', default=1) price_subtotal = fields.Float(string='Subtotal w/o Tax', digits=0, readonly=True, required=True) price_subtotal_incl = fields.Float(string='Subtotal', digits=0, readonly=True, required=True) margin = fields.Monetary(string="Margin", compute='_compute_margin') margin_percent = fields.Float(string="Margin (%)", compute='_compute_margin', digits=(12, 4)) total_cost = fields.Float(string='Total cost', digits='Product Price', readonly=True) is_total_cost_computed = fields.Boolean(help="Allows to know if the total cost has already been computed or not") discount = fields.Float(string='Discount (%)', digits=0, default=0.0) order_id = fields.Many2one('pos.order', string='Order Ref', ondelete='cascade', required=True, index=True) tax_ids = fields.Many2many('account.tax', string='Taxes', readonly=True) tax_ids_after_fiscal_position = fields.Many2many('account.tax', compute='_get_tax_ids_after_fiscal_position', string='Taxes to Apply') pack_lot_ids = fields.One2many('pos.pack.operation.lot', 'pos_order_line_id', string='Lot/serial Number') product_uom_id = fields.Many2one('uom.uom', string='Product UoM', related='product_id.uom_id') currency_id = fields.Many2one('res.currency', related='order_id.currency_id') full_product_name = fields.Char('Full Product Name') customer_note = fields.Char('Customer Note', help='This is a note destined to the customer') refund_orderline_ids = fields.One2many('pos.order.line', 'refunded_orderline_id', 'Refund Order Lines', help='Orderlines in this field are the lines that refunded this orderline.') refunded_orderline_id = fields.Many2one('pos.order.line', 'Refunded Order Line', help='If this orderline is a refund, then the refunded orderline is specified in this field.') refunded_qty = fields.Float('Refunded Quantity', compute='_compute_refund_qty', help='Number of items refunded in this orderline.') @api.depends('refund_orderline_ids') def _compute_refund_qty(self): for orderline in self: orderline.refunded_qty = -sum(orderline.mapped('refund_orderline_ids.qty')) def _prepare_refund_data(self, refund_order, PosOrderLineLot): """ This prepares data for refund order line. Inheritance may inject more data here @param refund_order: the pre-created refund order @type refund_order: pos.order @param PosOrderLineLot: the pre-created Pack operation Lot @type PosOrderLineLot: pos.pack.operation.lot @return: dictionary of data which is for creating a refund order line from the original line @rtype: dict """ self.ensure_one() return { 'name': self.name + _(' REFUND'), 'qty': -(self.qty - self.refunded_qty), 'order_id': refund_order.id, 'price_subtotal': -self.price_subtotal, 'price_subtotal_incl': -self.price_subtotal_incl, 'pack_lot_ids': PosOrderLineLot, 'is_total_cost_computed': False, 'refunded_orderline_id': self.id, } @api.model def create(self, values): if values.get('order_id') and not values.get('name'): # set name based on the sequence specified on the config config = self.env['pos.order'].browse(values['order_id']).session_id.config_id if config.sequence_line_id: values['name'] = config.sequence_line_id._next() if not values.get('name'): # fallback on any pos.order sequence values['name'] = self.env['ir.sequence'].next_by_code('pos.order.line') return super(PosOrderLine, self).create(values) def write(self, values): if values.get('pack_lot_line_ids'): for pl in values.get('pack_lot_ids'): if pl[2].get('server_id'): pl[2]['id'] = pl[2]['server_id'] del pl[2]['server_id'] return super().write(values) @api.onchange('price_unit', 'tax_ids', 'qty', 'discount', 'product_id') def _onchange_amount_line_all(self): for line in self: res = line._compute_amount_line_all() line.update(res) def _compute_amount_line_all(self): self.ensure_one() fpos = self.order_id.fiscal_position_id tax_ids_after_fiscal_position = fpos.map_tax(self.tax_ids) price = self.price_unit * (1 - (self.discount or 0.0) / 100.0) taxes = tax_ids_after_fiscal_position.compute_all(price, self.order_id.pricelist_id.currency_id, self.qty, product=self.product_id, partner=self.order_id.partner_id) return { 'price_subtotal_incl': taxes['total_included'], 'price_subtotal': taxes['total_excluded'], } @api.onchange('product_id') def _onchange_product_id(self): if self.product_id: if not self.order_id.pricelist_id: raise UserError( _('You have to select a pricelist in the sale form !\n' 'Please set one before choosing a product.')) price = self.order_id.pricelist_id.get_product_price( self.product_id, self.qty or 1.0, self.order_id.partner_id) self.tax_ids = self.product_id.taxes_id.filtered(lambda r: not self.company_id or r.company_id == self.company_id) tax_ids_after_fiscal_position = self.order_id.fiscal_position_id.map_tax(self.tax_ids) self.price_unit = self.env['account.tax']._fix_tax_included_price_company(price, self.tax_ids, tax_ids_after_fiscal_position, self.company_id) self._onchange_qty() @api.onchange('qty', 'discount', 'price_unit', 'tax_ids') def _onchange_qty(self): if self.product_id: if not self.order_id.pricelist_id: raise UserError(_('You have to select a pricelist in the sale form.')) price = self.price_unit * (1 - (self.discount or 0.0) / 100.0) self.price_subtotal = self.price_subtotal_incl = price * self.qty if (self.tax_ids): taxes = self.tax_ids.compute_all(price, self.order_id.pricelist_id.currency_id, self.qty, product=self.product_id, partner=False) self.price_subtotal = taxes['total_excluded'] self.price_subtotal_incl = taxes['total_included'] @api.depends('order_id', 'order_id.fiscal_position_id') def _get_tax_ids_after_fiscal_position(self): for line in self: line.tax_ids_after_fiscal_position = line.order_id.fiscal_position_id.map_tax(line.tax_ids) def _export_for_ui(self, orderline): return { 'qty': orderline.qty, 'price_unit': orderline.price_unit, 'price_subtotal': orderline.price_subtotal, 'price_subtotal_incl': orderline.price_subtotal_incl, 'product_id': orderline.product_id.id, 'discount': orderline.discount, 'tax_ids': [[6, False, orderline.tax_ids.mapped(lambda tax: tax.id)]], 'id': orderline.id, 'pack_lot_ids': [[0, 0, lot] for lot in orderline.pack_lot_ids.export_for_ui()], 'customer_note': orderline.customer_note, 'refunded_qty': orderline.refunded_qty, 'refunded_orderline_id': orderline.refunded_orderline_id, } def export_for_ui(self): return self.mapped(self._export_for_ui) if self else [] def _get_procurement_group(self): return self.order_id.procurement_group_id def _prepare_procurement_group_vals(self): return { 'name': self.order_id.name, 'move_type': self.order_id.config_id.picking_policy, 'pos_order_id': self.order_id.id, 'partner_id': self.order_id.partner_id.id, } def _prepare_procurement_values(self, group_id=False): """ Prepare specific key for moves or other components that will be created from a stock rule comming from a sale order line. This method could be override in order to add other custom key that could be used in move/po creation. """ self.ensure_one() # Use the delivery date if there is else use date_order and lead time date_deadline = self.order_id.date_order values = { 'group_id': group_id, 'date_planned': date_deadline, 'date_deadline': date_deadline, 'route_ids': self.order_id.config_id.route_id, 'warehouse_id': self.order_id.config_id.warehouse_id or False, 'partner_id': self.order_id.partner_id.id, 'product_description_variants': self.full_product_name, 'company_id': self.order_id.company_id, } return values def _launch_stock_rule_from_pos_order_lines(self): procurements = [] for line in self: line = line.with_company(line.company_id) if not line.product_id.type in ('consu','product'): continue group_id = line._get_procurement_group() if not group_id: group_id = self.env['procurement.group'].create(line._prepare_procurement_group_vals()) line.order_id.procurement_group_id = group_id values = line._prepare_procurement_values(group_id=group_id) product_qty = line.qty procurement_uom = line.product_id.uom_id procurements.append(self.env['procurement.group'].Procurement( line.product_id, product_qty, procurement_uom, line.order_id.partner_id.property_stock_customer, line.name, line.order_id.name, line.order_id.company_id, values)) if procurements: self.env['procurement.group'].run(procurements) # This next block is currently needed only because the scheduler trigger is done by picking confirmation rather than stock.move confirmation orders = self.mapped('order_id') for order in orders: pickings_to_confirm = order.picking_ids if pickings_to_confirm: # Trigger the Scheduler for Pickings pickings_to_confirm.action_confirm() tracked_lines = order.lines.filtered(lambda l: l.product_id.tracking != 'none') lines_by_tracked_product = groupby(sorted(tracked_lines, key=lambda l: l.product_id.id), key=lambda l: l.product_id.id) for product, lines in lines_by_tracked_product: lines = self.env['pos.order.line'].concat(*lines) moves = pickings_to_confirm.move_lines.filtered(lambda m: m.product_id.id == product) moves.move_line_ids.unlink() moves._add_mls_related_to_order(lines, are_qties_done=False) moves._recompute_state() return True def _is_product_storable_fifo_avco(self): self.ensure_one() return self.product_id.type == 'product' and self.product_id.cost_method in ['fifo', 'average'] def _compute_total_cost(self, stock_moves): """ Compute the total cost of the order lines. :param stock_moves: recordset of `stock.move`, used for fifo/avco lines """ for line in self.filtered(lambda l: not l.is_total_cost_computed): product = line.product_id if line._is_product_storable_fifo_avco() and stock_moves: product_cost = product._compute_average_price(0, line.qty, self._get_stock_moves_to_consider(stock_moves, product)) else: product_cost = product.standard_price line.total_cost = line.qty * product.cost_currency_id._convert( from_amount=product_cost, to_currency=line.currency_id, company=line.company_id or self.env.company, date=line.order_id.date_order or fields.Date.today(), round=False, ) line.is_total_cost_computed = True def _get_stock_moves_to_consider(self, stock_moves, product): return stock_moves.filtered(lambda ml: ml.product_id.id == product.id) @api.depends('price_subtotal', 'total_cost') def _compute_margin(self): for line in self: line.margin = line.price_subtotal - line.total_cost line.margin_percent = not float_is_zero(line.price_subtotal, precision_rounding=line.currency_id.rounding) and line.margin / line.price_subtotal or 0 class PosOrderLineLot(models.Model): _name = "pos.pack.operation.lot" _description = "Specify product lot/serial number in pos order line" _rec_name = "lot_name" pos_order_line_id = fields.Many2one('pos.order.line') order_id = fields.Many2one('pos.order', related="pos_order_line_id.order_id", readonly=False) lot_name = fields.Char('Lot Name') product_id = fields.Many2one('product.product', related='pos_order_line_id.product_id', readonly=False) def _export_for_ui(self, lot): return { 'lot_name': lot.lot_name, } def export_for_ui(self): return self.mapped(self._export_for_ui) if self else [] class ReportSaleDetails(models.AbstractModel): _name = 'report.point_of_sale.report_saledetails' _description = 'Point of Sale Details' @api.model def get_sale_details(self, date_start=False, date_stop=False, config_ids=False, session_ids=False): """ Serialise the orders of the requested time period, configs and sessions. :param date_start: The dateTime to start, default today 00:00:00. :type date_start: str. :param date_stop: The dateTime to stop, default date_start + 23:59:59. :type date_stop: str. :param config_ids: Pos Config id's to include. :type config_ids: list of numbers. :param session_ids: Pos Config id's to include. :type session_ids: list of numbers. :returns: dict -- Serialised sales. """ domain = [('state', 'in', ['paid','invoiced','done'])] if (session_ids): domain = AND([domain, [('session_id', 'in', session_ids)]]) else: if date_start: date_start = fields.Datetime.from_string(date_start) else: # start by default today 00:00:00 user_tz = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC') today = user_tz.localize(fields.Datetime.from_string(fields.Date.context_today(self))) date_start = today.astimezone(pytz.timezone('UTC')) if date_stop: date_stop = fields.Datetime.from_string(date_stop) # avoid a date_stop smaller than date_start if (date_stop < date_start): date_stop = date_start + timedelta(days=1, seconds=-1) else: # stop by default today 23:59:59 date_stop = date_start + timedelta(days=1, seconds=-1) domain = AND([domain, [('date_order', '>=', fields.Datetime.to_string(date_start)), ('date_order', '<=', fields.Datetime.to_string(date_stop))] ]) if config_ids: domain = AND([domain, [('config_id', 'in', config_ids)]]) orders = self.env['pos.order'].search(domain) user_currency = self.env.company.currency_id total = 0.0 products_sold = {} taxes = {} for order in orders: if user_currency != order.pricelist_id.currency_id: total += order.pricelist_id.currency_id._convert( order.amount_total, user_currency, order.company_id, order.date_order or fields.Date.today()) else: total += order.amount_total currency = order.session_id.currency_id for line in order.lines: key = (line.product_id, line.price_unit, line.discount) products_sold.setdefault(key, 0.0) products_sold[key] += line.qty if line.tax_ids_after_fiscal_position: line_taxes = line.tax_ids_after_fiscal_position.sudo().compute_all(line.price_unit * (1-(line.discount or 0.0)/100.0), currency, line.qty, product=line.product_id, partner=line.order_id.partner_id or False) for tax in line_taxes['taxes']: taxes.setdefault(tax['id'], {'name': tax['name'], 'tax_amount':0.0, 'base_amount':0.0}) taxes[tax['id']]['tax_amount'] += tax['amount'] taxes[tax['id']]['base_amount'] += tax['base'] else: taxes.setdefault(0, {'name': _('No Taxes'), 'tax_amount':0.0, 'base_amount':0.0}) taxes[0]['base_amount'] += line.price_subtotal_incl payment_ids = self.env["pos.payment"].search([('pos_order_id', 'in', orders.ids)]).ids if payment_ids: self.env.cr.execute(""" SELECT method.name, sum(amount) total FROM pos_payment AS payment, pos_payment_method AS method WHERE payment.payment_method_id = method.id AND payment.id IN %s GROUP BY method.name """, (tuple(payment_ids),)) payments = self.env.cr.dictfetchall() else: payments = [] return { 'currency_precision': user_currency.decimal_places, 'total_paid': user_currency.round(total), 'payments': payments, 'company_name': self.env.company.name, 'taxes': list(taxes.values()), 'products': sorted([{ 'product_id': product.id, 'product_name': product.name, 'code': product.default_code, 'quantity': qty, 'price_unit': price_unit, 'discount': discount, 'uom': product.uom_id.name } for (product, price_unit, discount), qty in products_sold.items()], key=lambda l: l['product_name']) } @api.model def _get_report_values(self, docids, data=None): data = dict(data or {}) configs = self.env['pos.config'].browse(data['config_ids']) data.update(self.get_sale_details(data['date_start'], data['date_stop'], configs.ids)) return data class AccountCashRounding(models.Model): _inherit = 'account.cash.rounding' @api.constrains('rounding', 'rounding_method', 'strategy') def _check_session_state(self): open_session = self.env['pos.session'].search([('config_id.rounding_method', 'in', self.ids), ('state', '!=', 'closed')], limit=1) if open_session: raise ValidationError( _("You are not allowed to change the cash rounding configuration while a pos session using it is already opened."))
50.311927
65,808
903
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models class AccountChartTemplate(models.Model): _inherit = 'account.chart.template' def _load(self, sale_tax_rate, purchase_tax_rate, company): """Remove the payment methods that are created for the company before installing the chart of accounts. Keeping these existing pos.payment.method records interferes with the installation of chart of accounts because pos.payment.method model has fields linked to account.journal and account.account records that are deleted during the loading of chart of accounts. """ self.env['pos.payment.method'].search([('company_id', '=', company.id)]).unlink() result = super(AccountChartTemplate, self)._load(sale_tax_rate, purchase_tax_rate, company) self.env['pos.config'].post_install_pos_localisation(companies=company) return result
50.166667
903
1,276
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2004-2008 PC Solutions (<http://pcsol.be>). All Rights Reserved from odoo import fields, models, api, _ from odoo.exceptions import UserError class AccountBankStatement(models.Model): _inherit = 'account.bank.statement' pos_session_id = fields.Many2one('pos.session', string="Session", copy=False) account_id = fields.Many2one('account.account', related='journal_id.default_account_id', readonly=True) def button_validate_or_action(self): # OVERRIDE to check the consistency of the statement's state regarding the session's state. for statement in self: if statement.pos_session_id.state in ('opened', 'closing_control') and statement.state == 'open': raise UserError(_("You can't validate a bank statement that is used in an opened Session of a Point of Sale.")) return super(AccountBankStatement, self).button_validate_or_action() @api.ondelete(at_uninstall=False) def _unlink_except_linked_to_pos_session(self): for bs in self: if bs.pos_session_id: raise UserError(_("You cannot delete a bank statement linked to Point of Sale session."))
51.04
1,276
1,328
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ from odoo.exceptions import UserError class PosInvoiceReport(models.AbstractModel): _name = 'report.point_of_sale.report_invoice' _description = 'Point of Sale Invoice Report' @api.model def _get_report_values(self, docids, data=None): PosOrder = self.env['pos.order'] ids_to_print = [] invoiced_posorders_ids = [] selected_orders = PosOrder.browse(docids) for order in selected_orders.filtered(lambda o: o.account_move): ids_to_print.append(order.account_move.id) invoiced_posorders_ids.append(order.id) not_invoiced_orders_ids = list(set(docids) - set(invoiced_posorders_ids)) if not_invoiced_orders_ids: not_invoiced_posorders = PosOrder.browse(not_invoiced_orders_ids) not_invoiced_orders_names = [a.name for a in not_invoiced_posorders] raise UserError(_('No link to an invoice for %s.') % ', '.join(not_invoiced_orders_names)) return { 'docs': self.env['account.move'].sudo().browse(ids_to_print), 'qr_code_urls': self.env['report.account.report_invoice'].sudo()._get_report_values(ids_to_print)['qr_code_urls'] }
44.266667
1,328
5,348
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class PosOrderReport(models.Model): _name = "report.pos.order" _description = "Point of Sale Orders Report" _auto = False _order = 'date desc' date = fields.Datetime(string='Order Date', readonly=True) order_id = fields.Many2one('pos.order', string='Order', readonly=True) partner_id = fields.Many2one('res.partner', string='Customer', readonly=True) product_id = fields.Many2one('product.product', string='Product', readonly=True) product_tmpl_id = fields.Many2one('product.template', string='Product Template', readonly=True) state = fields.Selection( [('draft', 'New'), ('paid', 'Paid'), ('done', 'Posted'), ('invoiced', 'Invoiced'), ('cancel', 'Cancelled')], string='Status', readonly=True) user_id = fields.Many2one('res.users', string='User', readonly=True) price_total = fields.Float(string='Total Price', readonly=True) price_sub_total = fields.Float(string='Subtotal w/o discount', readonly=True) total_discount = fields.Float(string='Total Discount', readonly=True) average_price = fields.Float(string='Average Price', readonly=True, group_operator="avg") company_id = fields.Many2one('res.company', string='Company', readonly=True) nbr_lines = fields.Integer(string='Sale Line Count', readonly=True) product_qty = fields.Integer(string='Product Quantity', readonly=True) journal_id = fields.Many2one('account.journal', string='Journal', readonly=True) delay_validation = fields.Integer(string='Delay Validation', readonly=True) product_categ_id = fields.Many2one('product.category', string='Product Category', readonly=True) invoiced = fields.Boolean(readonly=True) config_id = fields.Many2one('pos.config', string='Point of Sale', readonly=True) pos_categ_id = fields.Many2one('pos.category', string='PoS Category', readonly=True) pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', readonly=True) session_id = fields.Many2one('pos.session', string='Session', readonly=True) margin = fields.Float(string='Margin', readonly=True) def _select(self): return """ SELECT MIN(l.id) AS id, COUNT(*) AS nbr_lines, s.date_order AS date, SUM(l.qty) AS product_qty, SUM(l.qty * l.price_unit / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) AS price_sub_total, SUM(ROUND((l.qty * l.price_unit) * (100 - l.discount) / 100 / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END, cu.decimal_places)) AS price_total, SUM((l.qty * l.price_unit) * (l.discount / 100) / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) AS total_discount, CASE WHEN SUM(l.qty * u.factor) = 0 THEN NULL ELSE (SUM(l.qty*l.price_unit / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END)/SUM(l.qty * u.factor))::decimal END AS average_price, SUM(cast(to_char(date_trunc('day',s.date_order) - date_trunc('day',s.create_date),'DD') AS INT)) AS delay_validation, s.id as order_id, s.partner_id AS partner_id, s.state AS state, s.user_id AS user_id, s.company_id AS company_id, s.sale_journal AS journal_id, l.product_id AS product_id, pt.categ_id AS product_categ_id, p.product_tmpl_id, ps.config_id, pt.pos_categ_id, s.pricelist_id, s.session_id, s.account_move IS NOT NULL AS invoiced, SUM(l.price_subtotal - COALESCE(l.total_cost,0) / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) AS margin """ def _from(self): return """ FROM pos_order_line AS l INNER JOIN pos_order s ON (s.id=l.order_id) LEFT JOIN product_product p ON (l.product_id=p.id) LEFT JOIN product_template pt ON (p.product_tmpl_id=pt.id) LEFT JOIN uom_uom u ON (u.id=pt.uom_id) LEFT JOIN pos_session ps ON (s.session_id=ps.id) LEFT JOIN res_company co ON (s.company_id=co.id) LEFT JOIN res_currency cu ON (co.currency_id=cu.id) """ def _group_by(self): return """ GROUP BY s.id, s.date_order, s.partner_id,s.state, pt.categ_id, s.user_id, s.company_id, s.sale_journal, s.pricelist_id, s.account_move, s.create_date, s.session_id, l.product_id, pt.categ_id, pt.pos_categ_id, p.product_tmpl_id, ps.config_id """ def init(self): tools.drop_view_if_exists(self._cr, self._table) self._cr.execute(""" CREATE OR REPLACE VIEW %s AS ( %s %s %s ) """ % (self._table, self._select(), self._from(), self._group_by()) )
50.933333
5,348
4,032
py
PYTHON
15.0
# -*- coding: utf-8 -*- import json import logging from odoo import http from odoo.http import request from odoo.osv.expression import AND from odoo.tools import convert _logger = logging.getLogger(__name__) class PosController(http.Controller): @http.route(['/pos/web', '/pos/ui'], type='http', auth='user') def pos_web(self, config_id=False, **k): """Open a pos session for the given config. The right pos session will be selected to open, if non is open yet a new session will be created. /pos/ui and /pos/web both can be used to acces the POS. On the SaaS, /pos/ui uses HTTPS while /pos/web uses HTTP. :param debug: The debug mode to load the session in. :type debug: str. :param config_id: id of the config that has to be loaded. :type config_id: str. :returns: object -- The rendered pos session. """ domain = [ ('state', 'in', ['opening_control', 'opened']), ('user_id', '=', request.session.uid), ('rescue', '=', False) ] if config_id: domain = AND([domain,[('config_id', '=', int(config_id))]]) pos_session = request.env['pos.session'].sudo().search(domain, limit=1) # The same POS session can be opened by a different user => search without restricting to # current user. Note: the config must be explicitly given to avoid fallbacking on a random # session. if not pos_session and config_id: domain = [ ('state', 'in', ['opening_control', 'opened']), ('rescue', '=', False), ('config_id', '=', int(config_id)), ] pos_session = request.env['pos.session'].sudo().search(domain, limit=1) if not pos_session: return request.redirect('/web#action=point_of_sale.action_client_pos_menu') # The POS only work in one company, so we enforce the one of the session in the context company = pos_session.company_id session_info = request.env['ir.http'].session_info() session_info['user_context']['allowed_company_ids'] = company.ids session_info['user_companies'] = {'current_company': company.id, 'allowed_companies': {company.id: session_info['user_companies']['allowed_companies'][company.id]}} context = { 'session_info': session_info, 'login_number': pos_session.login(), } response = request.render('point_of_sale.index', context) response.headers['Cache-Control'] = 'no-store' return response @http.route('/pos/ui/tests', type='http', auth="user") def test_suite(self, mod=None, **kwargs): domain = [ ('state', '=', 'opened'), ('user_id', '=', request.session.uid), ('rescue', '=', False) ] pos_session = request.env['pos.session'].sudo().search(domain, limit=1) session_info = request.env['ir.http'].session_info() session_info['user_context']['allowed_company_ids'] = pos_session.company_id.ids context = { 'session_info': session_info, } return request.render('point_of_sale.qunit_suite', qcontext=context) @http.route('/pos/sale_details_report', type='http', auth='user') def print_sale_details(self, date_start=False, date_stop=False, **kw): r = request.env['report.point_of_sale.report_saledetails'] pdf, _ = request.env.ref('point_of_sale.sale_details_report').with_context(date_start=date_start, date_stop=date_stop)._render_qweb_pdf(r) pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) @http.route('/pos/load_onboarding_data', type='json', auth='user') def load_onboarding_data(self): convert.convert_file(request.env.cr, 'point_of_sale', 'data/point_of_sale_onboarding.xml', None, mode='init', kind='data')
45.303371
4,032
1,779
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Blogs', 'category': 'Website/Website', 'sequence': 200, 'website': 'https://www.odoo.com/app/blog', 'summary': 'Publish blog posts, announces, news', 'version': '1.1', 'description': "", 'depends': ['website_mail', 'website_partner'], 'data': [ 'data/mail_data.xml', 'data/mail_templates.xml', 'data/website_blog_data.xml', 'data/blog_snippet_template_data.xml', 'views/website_blog_views.xml', 'views/website_blog_components.xml', 'views/website_blog_posts_loop.xml', 'views/website_blog_templates.xml', 'views/snippets/snippets.xml', 'views/snippets/s_blog_posts.xml', 'security/ir.model.access.csv', 'security/website_blog_security.xml', ], 'demo': [ 'data/website_blog_demo.xml' ], 'test': [ ], 'installable': True, 'application': True, 'assets': { 'website.assets_wysiwyg': [ 'website_blog/static/src/js/options.js', 'website_blog/static/src/js/wysiwyg.js', 'website_blog/static/src/snippets/s_blog_posts/options.js', ], 'website.assets_editor': [ 'website_blog/static/src/js/website_blog.editor.js', 'website_blog/static/src/js/tours/website_blog.js', ], 'web.assets_tests': [ 'website_blog/static/tests/**/*', ], 'web.assets_frontend': [ 'website_blog/static/src/scss/website_blog.scss', 'website_blog/static/src/js/contentshare.js', 'website_blog/static/src/js/website_blog.js', ], }, 'license': 'LGPL-3', }
32.944444
1,779
5,178
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError from odoo.tests.common import users from odoo.addons.website.tools import MockRequest from odoo.addons.website_blog.tests.common import TestWebsiteBlogCommon from odoo.addons.portal.controllers.mail import PortalChatter class TestWebsiteBlogFlow(TestWebsiteBlogCommon): def setUp(self): super(TestWebsiteBlogFlow, self).setUp() group_portal = self.env.ref('base.group_portal') self.user_portal = self.env['res.users'].with_context({'no_reset_password': True}).create({ 'name': 'Dorian Portal', 'login': 'portal_user', 'email': 'portal_user@example.com', 'notification_type': 'inbox', 'groups_id': [(6, 0, [group_portal.id])] }) def test_website_blog_followers(self): """ Test the flow of followers and notifications for blogs. Intended flow : - people subscribe to a blog - when creating a new post, nobody except the creator follows it - people subscribed to the blog does not receive comments on posts - when published, a notification is sent to all blog followers - if someone subscribe to the post or comment it, it become follower and receive notification for future comments. """ # Create a new blog, subscribe the employee to the blog self.assertIn( self.user_blogmanager.partner_id, self.test_blog.message_partner_ids, 'website_blog: blog create should be in the blog followers') self.test_blog.message_subscribe([self.user_employee.partner_id.id, self.user_public.partner_id.id]) # Create a new post, blog followers should not follow the post self.assertNotIn( self.user_employee.partner_id, self.test_blog_post.message_partner_ids, 'website_blog: subscribing to a blog should not subscribe to its posts') self.assertNotIn( self.user_public.partner_id, self.test_blog_post.message_partner_ids, 'website_blog: subscribing to a blog should not subscribe to its posts') # Publish the blog self.test_blog_post.write({'website_published': True}) # Check publish message has been sent to blog followers publish_message = next((m for m in self.test_blog_post.blog_id.message_ids if m.subtype_id.id == self.ref('website_blog.mt_blog_blog_published')), None) self.assertEqual( publish_message.notified_partner_ids, self.user_employee.partner_id | self.user_public.partner_id, 'website_blog: peuple following a blog should be notified of a published post') # Armand posts a message -> becomes follower self.test_blog_post.sudo().message_post( body='Armande BlogUser Commented', message_type='comment', author_id=self.user_employee.partner_id.id, subtype_xmlid='mail.mt_comment', ) self.assertIn( self.user_employee.partner_id, self.test_blog_post.message_partner_ids, 'website_blog: people commenting a post should follow it afterwards') @users('portal_user') def test_blog_comment(self): """Test comment on blog post with attachment.""" attachment = self.env['ir.attachment'].sudo().create({ 'name': 'some_attachment.pdf', 'res_model': 'mail.compose.message', 'datas': 'test', 'type': 'binary', 'access_token': 'azerty', }) with MockRequest(self.env): PortalChatter().portal_chatter_post( 'blog.post', self.test_blog_post.id, 'Test message blog post', attachment_ids=[attachment.id], attachment_tokens=[attachment.access_token] ) self.assertTrue(self.env['mail.message'].sudo().search( [('model', '=', 'blog.post'), ('attachment_ids', 'in', attachment.ids)])) second_attachment = self.env['ir.attachment'].sudo().create({ 'name': 'some_attachment.pdf', 'res_model': 'mail.compose.message', 'datas': 'test', 'type': 'binary', 'access_token': 'azerty', }) with self.assertRaises(UserError), MockRequest(self.env): PortalChatter().portal_chatter_post( 'blog.post', self.test_blog_post.id, 'Test message blog post', attachment_ids=[second_attachment.id], attachment_tokens=['wrong_token'] ) self.assertFalse(self.env['mail.message'].sudo().search( [('model', '=', 'blog.post'), ('attachment_ids', 'in', second_attachment.ids)])) def test_website_blog_teaser_content(self): """ Make sure that the content of the post is correctly rendered in proper plain text. """ self.test_blog_post.content = "<h2>Test Content</h2>" self.assertEqual(self.test_blog_post.teaser, "Test Content...")
43.881356
5,178
1,095
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.tagged('post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def test_admin(self): # Ensure at least two blogs exist for the step asking to select a blog self.env['blog.blog'].create({'name': 'Travel'}) # Ensure at least one image exists for the step that chooses one self.env['ir.attachment'].create({ 'public': True, 'type': 'url', 'url': '/web/image/123/transparent.png', 'name': 'transparent.png', 'mimetype': 'image/png', }) self.start_tour("/", 'blog', login='admin') def test_blog_post_tags(self): self.start_tour("/blog", 'blog_tags', login='admin') def test_autocomplete_with_date(self): self.env.ref('website_blog.opt_blog_sidebar_show').active = True self.env.ref('website_blog.opt_sidebar_blog_index_follow_us').active = False self.start_tour("/blog", 'blog_autocomplete_with_date')
36.5
1,095
2,466
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website.tests.test_performance import UtilPerf import random class TestBlogPerformance(UtilPerf): def setUp(self): super().setUp() # if website_livechat is installed, disable it if 'channel_id' in self.env['website']: self.env['website'].search([]).channel_id = False def test_10_perf_sql_blog_standard_data(self): self.assertEqual(self._get_url_hot_query('/blog'), 26) self.assertEqual(self._get_url_hot_query('/blog', cache=False), 25) def test_20_perf_sql_blog_bigger_data_scaling(self): BlogPost = self.env['blog.post'] BlogTag = self.env['blog.tag'] blogs = self.env['blog.blog'].search([]) blog_tags = BlogTag.create([{'name': 'Blog Tag Test %s' % i} for i in range(1, 20)]) BlogPost.create([{'name': 'Blog Post Test %s' % i, 'is_published': True, 'blog_id': blogs[i % 2].id} for i in range(1, 20)]) blog_posts = BlogPost.search([]) for blog_post in blog_posts: blog_post.tag_ids += blog_tags blog_tags = blog_tags[:-1] self.assertEqual(self._get_url_hot_query('/blog'), 26) self.assertEqual(self._get_url_hot_query('/blog', cache=False), 25) self.assertEqual(self._get_url_hot_query(blog_post[0].website_url), 29) self.assertEqual(self._get_url_hot_query(blog_post[0].website_url, cache=False), 28) def test_30_perf_sql_blog_bigger_data_scaling(self): BlogPost = self.env['blog.post'] BlogTag = self.env['blog.tag'] blogs = self.env['blog.blog'].search([]) blog_tags = BlogTag.create([{'name': 'New Blog Tag Test %s' % i} for i in range(1, 50)]) BlogPost.create([{'name': 'New Blog Post Test %s' % i, 'is_published': True, 'blog_id': blogs[random.randint(0, 1)].id} for i in range(1, 100)]) blog_posts = BlogPost.search([]) for blog_post in blog_posts: blog_post.write({'tag_ids': [[6, 0, random.choices(blog_tags.ids, k=random.randint(0, len(blog_tags)))]]}) self.assertLessEqual(self._get_url_hot_query('/blog'), 28) self.assertLessEqual(self._get_url_hot_query('/blog', cache=False), 28) self.assertLessEqual(self._get_url_hot_query(blog_post[0].website_url), 32) self.assertLessEqual(self._get_url_hot_query(blog_post[0].website_url, cache=False), 31)
52.468085
2,466
1,814
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class TestWebsiteBlogCommon(common.TransactionCase): def setUp(self): super(TestWebsiteBlogCommon, self).setUp() Users = self.env['res.users'] group_blog_manager_id = self.ref('website.group_website_designer') group_employee_id = self.ref('base.group_user') group_public_id = self.ref('base.group_public') self.user_employee = Users.with_context({'no_reset_password': True}).create({ 'name': 'Armande Employee', 'login': 'armande', 'email': 'armande.employee@example.com', 'notification_type': 'inbox', 'groups_id': [(6, 0, [group_employee_id])] }) self.user_blogmanager = Users.with_context({'no_reset_password': True}).create({ 'name': 'Bastien BlogManager', 'login': 'bastien', 'email': 'bastien.blogmanager@example.com', 'notification_type': 'inbox', 'groups_id': [(6, 0, [group_blog_manager_id, group_employee_id])] }) self.user_public = Users.with_context({'no_reset_password': True}).create({ 'name': 'Cedric Public', 'login': 'cedric', 'email': 'cedric.public@example.com', 'notification_type': 'inbox', 'groups_id': [(6, 0, [group_public_id])] }) self.test_blog = self.env['blog.blog'].with_user(self.user_blogmanager).create({ 'name': 'New Blog', }) self.test_blog_post = self.env['blog.post'].with_user(self.user_blogmanager).create({ 'name': 'New Post', 'blog_id': self.test_blog.id, 'website_published': True, })
39.434783
1,814
15,782
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime import random import re from odoo import api, models, fields, _ from odoo.addons.http_routing.models.ir_http import slug, unslug from odoo.addons.website.tools import text_from_html from odoo.tools.json import scriptsafe as json_scriptsafe from odoo.tools.translate import html_translate class Blog(models.Model): _name = 'blog.blog' _description = 'Blog' _inherit = [ 'mail.thread', 'website.seo.metadata', 'website.multi.mixin', 'website.cover_properties.mixin', 'website.searchable.mixin', ] _order = 'name' name = fields.Char('Blog Name', required=True, translate=True) subtitle = fields.Char('Blog Subtitle', translate=True) active = fields.Boolean('Active', default=True) content = fields.Html('Content', translate=html_translate, sanitize=False) blog_post_ids = fields.One2many('blog.post', 'blog_id', 'Blog Posts') blog_post_count = fields.Integer("Posts", compute='_compute_blog_post_count') @api.depends('blog_post_ids') def _compute_blog_post_count(self): for record in self: record.blog_post_count = len(record.blog_post_ids) def write(self, vals): res = super(Blog, self).write(vals) if 'active' in vals: # archiving/unarchiving a blog does it on its posts, too post_ids = self.env['blog.post'].with_context(active_test=False).search([ ('blog_id', 'in', self.ids) ]) for blog_post in post_ids: blog_post.active = vals['active'] return res @api.returns('mail.message', lambda value: value.id) def message_post(self, *, parent_id=False, subtype_id=False, **kwargs): """ Temporary workaround to avoid spam. If someone replies on a channel through the 'Presentation Published' email, it should be considered as a note as we don't want all channel followers to be notified of this answer. """ self.ensure_one() if parent_id: parent_message = self.env['mail.message'].sudo().browse(parent_id) if parent_message.subtype_id and parent_message.subtype_id == self.env.ref('website_blog.mt_blog_blog_published'): subtype_id = self.env.ref('mail.mt_note').id return super(Blog, self).message_post(parent_id=parent_id, subtype_id=subtype_id, **kwargs) def all_tags(self, join=False, min_limit=1): BlogTag = self.env['blog.tag'] req = """ SELECT p.blog_id, count(*), r.blog_tag_id FROM blog_post_blog_tag_rel r join blog_post p on r.blog_post_id=p.id WHERE p.blog_id in %s GROUP BY p.blog_id, r.blog_tag_id ORDER BY count(*) DESC """ self._cr.execute(req, [tuple(self.ids)]) tag_by_blog = {i.id: [] for i in self} all_tags = set() for blog_id, freq, tag_id in self._cr.fetchall(): if freq >= min_limit: if join: all_tags.add(tag_id) else: tag_by_blog[blog_id].append(tag_id) if join: return BlogTag.browse(all_tags) for blog_id in tag_by_blog: tag_by_blog[blog_id] = BlogTag.browse(tag_by_blog[blog_id]) return tag_by_blog @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] search_fields = ['name'] fetch_fields = ['id', 'name'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'url', 'type': 'text', 'truncate': False}, } if with_description: search_fields.append('subtitle') fetch_fields.append('subtitle') mapping['description'] = {'name': 'subtitle', 'type': 'text', 'match': True} return { 'model': 'blog.blog', 'base_domain': [website.website_domain()], 'search_fields': search_fields, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-rss-square', 'order': 'name desc, id desc' if 'name desc' in order else 'name asc, id desc', } def _search_render_results(self, fetch_fields, mapping, icon, limit): results_data = super()._search_render_results(fetch_fields, mapping, icon, limit) for data in results_data: data['url'] = '/blog/%s' % data['id'] return results_data class BlogTagCategory(models.Model): _name = 'blog.tag.category' _description = 'Blog Tag Category' _order = 'name' name = fields.Char('Name', required=True, translate=True) tag_ids = fields.One2many('blog.tag', 'category_id', string='Tags') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag category already exists !"), ] class BlogTag(models.Model): _name = 'blog.tag' _description = 'Blog Tag' _inherit = ['website.seo.metadata'] _order = 'name' name = fields.Char('Name', required=True, translate=True) category_id = fields.Many2one('blog.tag.category', 'Category', index=True) post_ids = fields.Many2many('blog.post', string='Posts') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ] class BlogPost(models.Model): _name = "blog.post" _description = "Blog Post" _inherit = ['mail.thread', 'website.seo.metadata', 'website.published.multi.mixin', 'website.cover_properties.mixin', 'website.searchable.mixin'] _order = 'id DESC' _mail_post_access = 'read' def _compute_website_url(self): super(BlogPost, self)._compute_website_url() for blog_post in self: blog_post.website_url = "/blog/%s/%s" % (slug(blog_post.blog_id), slug(blog_post)) def _default_content(self): return ''' <p class="o_default_snippet_text">''' + _("Start writing here...") + '''</p> ''' name = fields.Char('Title', required=True, translate=True, default='') subtitle = fields.Char('Sub Title', translate=True) author_id = fields.Many2one('res.partner', 'Author', default=lambda self: self.env.user.partner_id) author_avatar = fields.Binary(related='author_id.image_128', string="Avatar", readonly=False) author_name = fields.Char(related='author_id.display_name', string="Author Name", readonly=False, store=True) active = fields.Boolean('Active', default=True) blog_id = fields.Many2one('blog.blog', 'Blog', required=True, ondelete='cascade') tag_ids = fields.Many2many('blog.tag', string='Tags') content = fields.Html('Content', default=_default_content, translate=html_translate, sanitize=False) teaser = fields.Text('Teaser', compute='_compute_teaser', inverse='_set_teaser') teaser_manual = fields.Text(string='Teaser Content') website_message_ids = fields.One2many(domain=lambda self: [('model', '=', self._name), ('message_type', '=', 'comment')]) # creation / update stuff create_date = fields.Datetime('Created on', index=True, readonly=True) published_date = fields.Datetime('Published Date') post_date = fields.Datetime('Publishing date', compute='_compute_post_date', inverse='_set_post_date', store=True, help="The blog post will be visible for your visitors as of this date on the website if it is set as published.") create_uid = fields.Many2one('res.users', 'Created by', index=True, readonly=True) write_date = fields.Datetime('Last Updated on', index=True, readonly=True) write_uid = fields.Many2one('res.users', 'Last Contributor', index=True, readonly=True) visits = fields.Integer('No of Views', copy=False, default=0) website_id = fields.Many2one(related='blog_id.website_id', readonly=True, store=True) @api.depends('content', 'teaser_manual') def _compute_teaser(self): for blog_post in self: if blog_post.teaser_manual: blog_post.teaser = blog_post.teaser_manual else: content = text_from_html(blog_post.content) content = re.sub('\\s+', ' ', content).strip() blog_post.teaser = content[:200] + '...' def _set_teaser(self): for blog_post in self: blog_post.teaser_manual = blog_post.teaser @api.depends('create_date', 'published_date') def _compute_post_date(self): for blog_post in self: if blog_post.published_date: blog_post.post_date = blog_post.published_date else: blog_post.post_date = blog_post.create_date def _set_post_date(self): for blog_post in self: blog_post.published_date = blog_post.post_date if not blog_post.published_date: blog_post._write(dict(post_date=blog_post.create_date)) # dont trigger inverse function def _check_for_publication(self, vals): if vals.get('is_published'): for post in self.filtered(lambda p: p.active): post.blog_id.message_post_with_view( 'website_blog.blog_post_template_new_post', subject=post.name, values={'post': post}, subtype_id=self.env['ir.model.data']._xmlid_to_res_id('website_blog.mt_blog_blog_published')) return True return False @api.model def create(self, vals): post_id = super(BlogPost, self.with_context(mail_create_nolog=True)).create(vals) post_id._check_for_publication(vals) return post_id def write(self, vals): result = True # archiving a blog post, unpublished the blog post if 'active' in vals and not vals['active']: vals['is_published'] = False for post in self: copy_vals = dict(vals) published_in_vals = set(vals.keys()) & {'is_published', 'website_published'} if (published_in_vals and 'published_date' not in vals and (not post.published_date or post.published_date <= fields.Datetime.now())): copy_vals['published_date'] = vals[list(published_in_vals)[0]] and fields.Datetime.now() or False result &= super(BlogPost, post).write(copy_vals) self._check_for_publication(vals) return result @api.returns('self', lambda value: value.id) def copy_data(self, default=None): self.ensure_one() name = _("%s (copy)", self.name) default = dict(default or {}, name=name) return super(BlogPost, self).copy_data(default) def get_access_action(self, access_uid=None): """ Instead of the classic form view, redirect to the post on website directly if user is an employee or if the post is published. """ self.ensure_one() user = access_uid and self.env['res.users'].sudo().browse(access_uid) or self.env.user if user.share and not self.sudo().website_published: return super(BlogPost, self).get_access_action(access_uid) return { 'type': 'ir.actions.act_url', 'url': self.website_url, 'target': 'self', 'target_type': 'public', 'res_id': self.id, } def _notify_get_groups(self, msg_vals=None): """ Add access button to everyone if the document is published. """ groups = super(BlogPost, self)._notify_get_groups(msg_vals=msg_vals) if self.website_published: for group_name, group_method, group_data in groups: group_data['has_button_access'] = True return groups def _notify_record_by_inbox(self, message, recipients_data, msg_vals=False, **kwargs): """ Override to avoid keeping all notified recipients of a comment. We avoid tracking needaction on post comments. Only emails should be sufficient. """ if msg_vals.get('message_type', message.message_type) == 'comment': return return super(BlogPost, self)._notify_record_by_inbox(message, recipients_data, msg_vals=msg_vals, **kwargs) def _default_website_meta(self): res = super(BlogPost, self)._default_website_meta() res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.subtitle res['default_opengraph']['og:type'] = 'article' res['default_opengraph']['article:published_time'] = self.post_date res['default_opengraph']['article:modified_time'] = self.write_date res['default_opengraph']['article:tag'] = self.tag_ids.mapped('name') # background-image might contain single quotes eg `url('/my/url')` res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = json_scriptsafe.loads(self.cover_properties).get('background-image', 'none')[4:-1].strip("'") res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name res['default_meta_description'] = self.subtitle return res @api.model def _search_get_detail(self, website, order, options): with_description = options['displayDescription'] with_date = options['displayDetail'] blog = options.get('blog') tags = options.get('tag') date_begin = options.get('date_begin') date_end = options.get('date_end') state = options.get('state') domain = [website.website_domain()] if blog: domain.append([('blog_id', '=', unslug(blog)[1])]) if tags: active_tag_ids = [unslug(tag)[1] for tag in tags.split(',')] or [] if active_tag_ids: domain.append([('tag_ids', 'in', active_tag_ids)]) if date_begin and date_end: domain.append([("post_date", ">=", date_begin), ("post_date", "<=", date_end)]) if self.env.user.has_group('website.group_website_designer'): if state == "published": domain.append([("website_published", "=", True), ("post_date", "<=", fields.Datetime.now())]) elif state == "unpublished": domain.append(['|', ("website_published", "=", False), ("post_date", ">", fields.Datetime.now())]) else: domain.append([("post_date", "<=", fields.Datetime.now())]) search_fields = ['name', 'author_name'] def search_in_tags(env, search_term): tags_like_search = env['blog.tag'].search([('name', 'ilike', search_term)]) return [('tag_ids', 'in', tags_like_search.ids)] fetch_fields = ['name', 'website_url'] mapping = { 'name': {'name': 'name', 'type': 'text', 'match': True}, 'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False}, } if with_description: search_fields.append('content') fetch_fields.append('content') mapping['description'] = {'name': 'content', 'type': 'text', 'html': True, 'match': True} if with_date: fetch_fields.append('published_date') mapping['detail'] = {'name': 'published_date', 'type': 'date'} return { 'model': 'blog.post', 'base_domain': domain, 'search_fields': search_fields, 'search_extra': search_in_tags, 'fetch_fields': fetch_fields, 'mapping': mapping, 'icon': 'fa-rss', }
44.207283
15,782
3,117
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo import models, fields, _ class WebsiteSnippetFilter(models.Model): _inherit = 'website.snippet.filter' def _get_hardcoded_sample(self, model): samples = super()._get_hardcoded_sample(model) if model._name == 'blog.post': data = [{ 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_2.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('Islands'), 'subtitle': _('Alone in the ocean'), 'post_date': fields.Date.today() - timedelta(days=1), 'website_url': "", }, { 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_3.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('With a View'), 'subtitle': _('Awesome hotel rooms'), 'post_date': fields.Date.today() - timedelta(days=2), 'website_url': "", }, { 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_4.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('Skies'), 'subtitle': _('Taking pictures in the dark'), 'post_date': fields.Date.today() - timedelta(days=3), 'website_url': "", }, { 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_5.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('Satellites'), 'subtitle': _('Seeing the world from above'), 'post_date': fields.Date.today() - timedelta(days=4), 'website_url': "", }, { 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_6.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('Viewpoints'), 'subtitle': _('Seaside vs mountain side'), 'post_date': fields.Date.today() - timedelta(days=5), 'website_url': "", }, { 'cover_properties': '{"background-image": "url(\'/website_blog/static/src/img/cover_7.jpg\')", "resize_class": "o_record_has_cover o_half_screen_height", "opacity": "0"}', 'name': _('Jungle'), 'subtitle': _('Spotting the fauna'), 'post_date': fields.Date.today() - timedelta(days=6), 'website_url': "", }] merged = [] for index in range(0, max(len(samples), len(data))): merged.append({**samples[index % len(samples)], **data[index % len(data)]}) # merge definitions samples = merged return samples
54.684211
3,117
3,448
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ from odoo.addons.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = "website" @api.model def page_search_dependencies(self, page_id=False): dep = super(Website, self).page_search_dependencies(page_id=page_id) page = self.env['website.page'].browse(int(page_id)) path = page.url dom = [ ('content', 'ilike', path) ] posts = self.env['blog.post'].search(dom) if posts: page_key = _('Blog Post') if len(posts) > 1: page_key = _('Blog Posts') dep[page_key] = [] for p in posts: dep[page_key].append({ 'text': _('Blog Post <b>%s</b> seems to have a link to this page !', p.name), 'item': p.name, 'link': p.website_url, }) return dep @api.model def page_search_key_dependencies(self, page_id=False): dep = super(Website, self).page_search_key_dependencies(page_id=page_id) page = self.env['website.page'].browse(int(page_id)) key = page.key dom = [ ('content', 'ilike', key) ] posts = self.env['blog.post'].search(dom) if posts: page_key = _('Blog Post') if len(posts) > 1: page_key = _('Blog Posts') dep[page_key] = [] for p in posts: dep[page_key].append({ 'text': _('Blog Post <b>%s</b> seems to be calling this file !', p.name), 'item': p.name, 'link': p.website_url, }) return dep def get_suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('Blog'), url_for('/blog'), 'website_blog')) return suggested_controllers def configurator_set_menu_links(self, menu_company, module_data): blogs = module_data.get('#blog', []) for idx, blog in enumerate(blogs): new_blog = self.env['blog.blog'].create({ 'name': blog['name'], 'website_id': self.id, }) blog_menu_values = { 'name': blog['name'], 'url': '/blog/%s' % new_blog.id, 'sequence': blog['sequence'], 'parent_id': menu_company.id if menu_company else self.menu_id.id, 'website_id': self.id, } if idx == 0: blog_menu = self.env['website.menu'].search([('url', '=', '/blog'), ('website_id', '=', self.id)]) blog_menu.write(blog_menu_values) else: self.env['website.menu'].create(blog_menu_values) super().configurator_set_menu_links(menu_company, module_data) def _search_get_details(self, search_type, order, options): result = super()._search_get_details(search_type, order, options) if search_type in ['blogs', 'blogs_only', 'all']: result.append(self.env['blog.blog']._search_get_detail(self, order, options)) if search_type in ['blogs', 'blog_posts_only', 'all']: result.append(self.env['blog.post']._search_get_detail(self, order, options)) return result
37.075269
3,448
16,470
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re import werkzeug import itertools import pytz import babel.dates from collections import OrderedDict from odoo import http, fields from odoo.addons.http_routing.models.ir_http import slug, unslug from odoo.addons.website.controllers.main import QueryURL from odoo.addons.portal.controllers.portal import _build_url_w_params from odoo.http import request from odoo.osv import expression from odoo.tools import html2plaintext from odoo.tools.misc import get_lang from odoo.tools import sql class WebsiteBlog(http.Controller): _blog_post_per_page = 12 # multiple of 2,3,4 _post_comment_per_page = 10 def tags_list(self, tag_ids, current_tag): tag_ids = list(tag_ids) # required to avoid using the same list if current_tag in tag_ids: tag_ids.remove(current_tag) else: tag_ids.append(current_tag) tag_ids = request.env['blog.tag'].browse(tag_ids) return ','.join(slug(tag) for tag in tag_ids) def nav_list(self, blog=None): dom = blog and [('blog_id', '=', blog.id)] or [] if not request.env.user.has_group('website.group_website_designer'): dom += [('post_date', '<=', fields.Datetime.now())] groups = request.env['blog.post']._read_group_raw( dom, ['name', 'post_date'], groupby=["post_date"], orderby="post_date desc") for group in groups: (r, label) = group['post_date'] start, end = r.split('/') group['post_date'] = label group['date_begin'] = start group['date_end'] = end locale = get_lang(request.env).code start = pytz.UTC.localize(fields.Datetime.from_string(start)) tzinfo = pytz.timezone(request.context.get('tz', 'utc') or 'utc') group['month'] = babel.dates.format_datetime(start, format='MMMM', tzinfo=tzinfo, locale=locale) group['year'] = babel.dates.format_datetime(start, format='yyyy', tzinfo=tzinfo, locale=locale) return OrderedDict((year, [m for m in months]) for year, months in itertools.groupby(groups, lambda g: g['year'])) def _prepare_blog_values(self, blogs, blog=False, date_begin=False, date_end=False, tags=False, state=False, page=False, search=None): """ Prepare all values to display the blogs index page or one specific blog""" BlogPost = request.env['blog.post'] BlogTag = request.env['blog.tag'] # prepare domain domain = request.website.website_domain() if blog: domain += [('blog_id', '=', blog.id)] if date_begin and date_end: domain += [("post_date", ">=", date_begin), ("post_date", "<=", date_end)] active_tag_ids = tags and [unslug(tag)[1] for tag in tags.split(',')] or [] active_tags = BlogTag if active_tag_ids: active_tags = BlogTag.browse(active_tag_ids).exists() fixed_tag_slug = ",".join(slug(t) for t in active_tags) if fixed_tag_slug != tags: path = request.httprequest.full_path new_url = path.replace("/tag/%s" % tags, fixed_tag_slug and "/tag/%s" % fixed_tag_slug or "", 1) if new_url != path: # check that really replaced and avoid loop return request.redirect(new_url, 301) domain += [('tag_ids', 'in', active_tags.ids)] if request.env.user.has_group('website.group_website_designer'): count_domain = domain + [("website_published", "=", True), ("post_date", "<=", fields.Datetime.now())] published_count = BlogPost.search_count(count_domain) unpublished_count = BlogPost.search_count(domain) - published_count if state == "published": domain += [("website_published", "=", True), ("post_date", "<=", fields.Datetime.now())] elif state == "unpublished": domain += ['|', ("website_published", "=", False), ("post_date", ">", fields.Datetime.now())] else: domain += [("post_date", "<=", fields.Datetime.now())] use_cover = request.website.is_view_active('website_blog.opt_blog_cover_post') fullwidth_cover = request.website.is_view_active('website_blog.opt_blog_cover_post_fullwidth_design') # if blog, we show blog title, if use_cover and not fullwidth_cover we need pager + latest always offset = (page - 1) * self._blog_post_per_page if not blog and use_cover and not fullwidth_cover and not tags and not date_begin and not date_end and not search: offset += 1 options = { 'displayDescription': True, 'displayDetail': False, 'displayExtraDetail': False, 'displayExtraLink': False, 'displayImage': False, 'allowFuzzy': not request.params.get('noFuzzy'), 'blog': str(blog.id) if blog else None, 'tag': ','.join([str(id) for id in active_tags.ids]), 'date_begin': date_begin, 'date_end': date_end, 'state': state, } total, details, fuzzy_search_term = request.website._search_with_fuzzy("blog_posts_only", search, limit=page * self._blog_post_per_page, order="is_published desc, post_date desc, id asc", options=options) posts = details[0].get('results', BlogPost) first_post = BlogPost # TODO adapt next line in master. if posts and not blog and posts[0].website_published and not search: first_post = posts[0] posts = posts[offset:offset + self._blog_post_per_page] url_args = dict() if search: url_args["search"] = search if date_begin and date_end: url_args["date_begin"] = date_begin url_args["date_end"] = date_end pager = request.website.pager( url=request.httprequest.path.partition('/page/')[0], total=total, page=page, step=self._blog_post_per_page, url_args=url_args, ) if not blogs: all_tags = request.env['blog.tag'] else: all_tags = blogs.all_tags(join=True) if not blog else blogs.all_tags().get(blog.id, request.env['blog.tag']) tag_category = sorted(all_tags.mapped('category_id'), key=lambda category: category.name.upper()) other_tags = sorted(all_tags.filtered(lambda x: not x.category_id), key=lambda tag: tag.name.upper()) # for performance prefetch the first post with the others post_ids = (first_post | posts).ids # and avoid accessing related blogs one by one posts.blog_id return { 'date_begin': date_begin, 'date_end': date_end, 'first_post': first_post.with_prefetch(post_ids), 'other_tags': other_tags, 'tag_category': tag_category, 'nav_list': self.nav_list(), 'tags_list': self.tags_list, 'pager': pager, 'posts': posts.with_prefetch(post_ids), 'tag': tags, 'active_tag_ids': active_tags.ids, 'domain': domain, 'state_info': state and {"state": state, "published": published_count, "unpublished": unpublished_count}, 'blogs': blogs, 'blog': blog, 'search': fuzzy_search_term or search, 'search_count': total, 'original_search': fuzzy_search_term and search, } @http.route([ '/blog', '/blog/page/<int:page>', '/blog/tag/<string:tag>', '/blog/tag/<string:tag>/page/<int:page>', '''/blog/<model("blog.blog"):blog>''', '''/blog/<model("blog.blog"):blog>/page/<int:page>''', '''/blog/<model("blog.blog"):blog>/tag/<string:tag>''', '''/blog/<model("blog.blog"):blog>/tag/<string:tag>/page/<int:page>''', ], type='http', auth="public", website=True, sitemap=True) def blog(self, blog=None, tag=None, page=1, search=None, **opt): Blog = request.env['blog.blog'] # TODO adapt in master. This is a fix for templates wrongly using the # 'blog_url' QueryURL which is defined below. Indeed, in the case where # we are rendering a blog page where no specific blog is selected we # define(d) that as `QueryURL('/blog', ['tag'], ...)` but then some # parts of the template used it like this: `blog_url(blog=XXX)` thus # generating an URL like "/blog?blog=blog.blog(2,)". Adding "blog" to # the list of params would not be right as would create "/blog/blog/2" # which is still wrong as we want "/blog/2". And of course the "/blog" # prefix in the QueryURL definition is needed in case we only specify a # tag via `blog_url(tab=X)` (we expect /blog/tag/X). Patching QueryURL # or making blog_url a custom function instead of a QueryURL instance # could be a solution but it was judged not stable enough. We'll do that # in master. Here we only support "/blog?blog=blog.blog(2,)" URLs. if isinstance(blog, str): blog = Blog.browse(int(re.search(r'\d+', blog)[0])) if not blog.exists(): raise werkzeug.exceptions.NotFound() blogs = Blog.search(request.website.website_domain(), order="create_date asc, id asc") if not blog and len(blogs) == 1: url = QueryURL('/blog/%s' % slug(blogs[0]), search=search, **opt)() return request.redirect(url, code=302) date_begin, date_end, state = opt.get('date_begin'), opt.get('date_end'), opt.get('state') if tag and request.httprequest.method == 'GET': # redirect get tag-1,tag-2 -> get tag-1 tags = tag.split(',') if len(tags) > 1: url = QueryURL('' if blog else '/blog', ['blog', 'tag'], blog=blog, tag=tags[0], date_begin=date_begin, date_end=date_end, search=search)() return request.redirect(url, code=302) values = self._prepare_blog_values(blogs=blogs, blog=blog, date_begin=date_begin, date_end=date_end, tags=tag, state=state, page=page, search=search) # in case of a redirection need by `_prepare_blog_values` we follow it if isinstance(values, werkzeug.wrappers.Response): return values if blog: values['main_object'] = blog values['edit_in_backend'] = True values['blog_url'] = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end, search=search) else: values['blog_url'] = QueryURL('/blog', ['tag'], date_begin=date_begin, date_end=date_end, search=search) return request.render("website_blog.blog_post_short", values) @http.route(['''/blog/<model("blog.blog"):blog>/feed'''], type='http', auth="public", website=True, sitemap=True) def blog_feed(self, blog, limit='15', **kwargs): v = {} v['blog'] = blog v['base_url'] = blog.get_base_url() v['posts'] = request.env['blog.post'].search([('blog_id', '=', blog.id)], limit=min(int(limit), 50), order="post_date DESC") v['html2plaintext'] = html2plaintext r = request.render("website_blog.blog_feed", v, headers=[('Content-Type', 'application/atom+xml')]) return r @http.route([ '''/blog/<model("blog.blog"):blog>/post/<model("blog.post", "[('blog_id','=',blog.id)]"):blog_post>''', ], type='http', auth="public", website=True, sitemap=False) def old_blog_post(self, blog, blog_post, tag_id=None, page=1, enable_editor=None, **post): # Compatibility pre-v14 return request.redirect(_build_url_w_params("/blog/%s/%s" % (slug(blog), slug(blog_post)), request.params), code=301) @http.route([ '''/blog/<model("blog.blog"):blog>/<model("blog.post", "[('blog_id','=',blog.id)]"):blog_post>''', ], type='http', auth="public", website=True, sitemap=True) def blog_post(self, blog, blog_post, tag_id=None, page=1, enable_editor=None, **post): """ Prepare all values to display the blog. :return dict values: values for the templates, containing - 'blog_post': browse of the current post - 'blog': browse of the current blog - 'blogs': list of browse records of blogs - 'tag': current tag, if tag_id in parameters - 'tags': all tags, for tag-based navigation - 'pager': a pager on the comments - 'nav_list': a dict [year][month] for archives navigation - 'next_post': next blog post, to direct the user towards the next interesting post """ BlogPost = request.env['blog.post'] date_begin, date_end = post.get('date_begin'), post.get('date_end') domain = request.website.website_domain() blogs = blog.search(domain, order="create_date, id asc") tag = None if tag_id: tag = request.env['blog.tag'].browse(int(tag_id)) blog_url = QueryURL('', ['blog', 'tag'], blog=blog_post.blog_id, tag=tag, date_begin=date_begin, date_end=date_end) if not blog_post.blog_id.id == blog.id: return request.redirect("/blog/%s/%s" % (slug(blog_post.blog_id), slug(blog_post)), code=301) tags = request.env['blog.tag'].search([]) # Find next Post blog_post_domain = [('blog_id', '=', blog.id)] if not request.env.user.has_group('website.group_website_designer'): blog_post_domain += [('post_date', '<=', fields.Datetime.now())] all_post = BlogPost.search(blog_post_domain) if blog_post not in all_post: return request.redirect("/blog/%s" % (slug(blog_post.blog_id))) # should always return at least the current post all_post_ids = all_post.ids current_blog_post_index = all_post_ids.index(blog_post.id) nb_posts = len(all_post_ids) next_post_id = all_post_ids[(current_blog_post_index + 1) % nb_posts] if nb_posts > 1 else None next_post = next_post_id and BlogPost.browse(next_post_id) or False values = { 'tags': tags, 'tag': tag, 'blog': blog, 'blog_post': blog_post, 'blogs': blogs, 'main_object': blog_post, 'nav_list': self.nav_list(blog), 'enable_editor': enable_editor, 'next_post': next_post, 'date': date_begin, 'blog_url': blog_url, } response = request.render("website_blog.blog_post_complete", values) if blog_post.id not in request.session.get('posts_viewed', []): if sql.increment_field_skiplock(blog_post, 'visits'): if not request.session.get('posts_viewed'): request.session['posts_viewed'] = [] request.session['posts_viewed'].append(blog_post.id) request.session.modified = True return response @http.route('/blog/<int:blog_id>/post/new', type='http', auth="user", website=True) def blog_post_create(self, blog_id, **post): # Use sudo so this line prevents both editor and admin to access blog from another website # as browse() will return the record even if forbidden by security rules but editor won't # be able to access it if not request.env['blog.blog'].browse(blog_id).sudo().can_access_from_current_website(): raise werkzeug.exceptions.NotFound() new_blog_post = request.env['blog.post'].create({ 'blog_id': blog_id, 'is_published': False, }) return request.redirect("/blog/%s/%s?enable_editor=1" % (slug(new_blog_post.blog_id), slug(new_blog_post))) @http.route('/blog/post_duplicate', type='http', auth="user", website=True, methods=['POST']) def blog_post_copy(self, blog_post_id, **post): """ Duplicate a blog. :param blog_post_id: id of the blog post currently browsed. :return redirect to the new blog created """ new_blog_post = request.env['blog.post'].with_context(mail_create_nosubscribe=True).browse(int(blog_post_id)).copy() return request.redirect("/blog/%s/%s?enable_editor=1" % (slug(new_blog_post.blog_id), slug(new_blog_post)))
47.191977
16,470
1,161
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "Events Booths Sales", 'category': 'Marketing/Events', 'version': '1.0', 'summary': "Manage event booths sale", 'description': """ Sell your event booths and track payments on sale orders. """, 'depends': ['event_booth', 'event_sale'], 'data': [ 'security/ir.model.access.csv', 'data/product_data.xml', 'data/event_booth_category_data.xml', 'views/sale_order_views.xml', 'views/event_type_booth_views.xml', 'views/event_booth_category_views.xml', 'views/event_booth_registration_views.xml', 'views/event_booth_views.xml', 'wizard/event_booth_configurator_views.xml', ], 'auto_install': True, 'assets': { 'web.assets_backend': [ 'event_booth_sale/static/src/js/event_booth_configurator_form_controller.js', 'event_booth_sale/static/src/js/event_booth_configurator_form_view.js', 'event_booth_sale/static/src/js/event_booth_configurator_widget.js', ] }, 'license': 'LGPL-3', }
35.181818
1,161
7,412
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command from odoo.addons.event_booth_sale.tests.common import TestEventBoothSaleCommon from odoo.addons.sale.tests.common import TestSaleCommon from odoo.tests.common import tagged, users from odoo.tools import float_compare class TestEventBoothSaleWData(TestEventBoothSaleCommon): @classmethod def setUpClass(cls): super(TestEventBoothSaleWData, cls).setUpClass() cls.booth_1, cls.booth_2 = cls.env['event.booth'].create([ { 'name': 'Test Booth 1', 'booth_category_id': cls.event_booth_category_1.id, 'event_id': cls.event_0.id, }, { 'name': 'Test Booth 2', 'booth_category_id': cls.event_booth_category_1.id, 'event_id': cls.event_0.id, } ]) cls.event_booth_product.taxes_id = cls.tax_10 class TestEventBoothSale(TestEventBoothSaleWData): @users('user_sales_salesman') def test_event_booth_prices_with_sale_order(self): sale_order = self.env['sale.order'].create({ 'partner_id': self.event_customer.id, 'pricelist_id': self.test_pricelist.id, 'order_line': [ Command.create({ 'product_id': self.event_booth_product.id, 'event_id': self.event_0.id, 'event_booth_category_id': self.event_booth_category_1.id, 'event_booth_pending_ids': (self.booth_1 + self.booth_2).ids }) ] }) self.assertEqual(self.booth_1.price, self.event_booth_product.list_price, "Booth price should be equal from product price.") self.assertEqual(self.event_booth_category_1.with_context(pricelist=self.test_pricelist.id).price_reduce_taxinc, 22.0, "Booth price reduce tax should be equal to its price with 10% taxes ($20.0 + $2.0)") # Here we expect the price to be the sum of the booth ($40.0) self.assertEqual(float_compare(sale_order.amount_untaxed, 40.0, precision_rounding=0.1), 0, "Untaxed amount should be the sum of the booths prices ($40.0).") self.assertEqual(float_compare(sale_order.amount_total, 44.0, precision_rounding=0.1), 0, "Total amount should be the sum of the booths prices with 10% taxes ($40.0 + $4.0)") self.event_booth_category_1.write({'price': 100.0}) sale_order.update_prices() self.assertNotEqual(self.booth_1.price, self.event_booth_product.list_price, "Booth price should be different from product price.") self.assertEqual(self.event_booth_category_1.with_context(pricelist=self.test_pricelist.id).price_reduce_taxinc, 110.0, "Booth price reduce tax should be equal to its price with 10% taxes ($100.0 + $10.0)") # Here we expect the price to be the sum of the booth ($200.0) self.assertEqual(float_compare(sale_order.amount_untaxed, 200.0, precision_rounding=0.1), 0, "Untaxed amount should be the sum of the booths prices ($200.0).") self.assertEqual(float_compare(sale_order.amount_total, 220.0, precision_rounding=0.1), 0, "Total amount should be the sum of the booths prices with 10% taxes ($200.0 + $20.0).") # Confirm the SO. sale_order.action_confirm() for booth in self.booth_1 + self.booth_2: self.assertEqual( booth.sale_order_id.id, sale_order.id, "Booth sale order should be the same as the original sale order.") self.assertEqual( booth.sale_order_line_id.id, sale_order.order_line[0].id, "Booth sale order line should the same as the order line in the original sale order.") self.assertEqual( booth.partner_id.id, self.event_customer.id, "Booth partner should be the same as sale order customer.") self.assertEqual( booth.contact_email, self.event_customer.email, "Booth contact email should be the same as sale order customer email.") self.assertEqual( booth.contact_name, self.event_customer.name, "Booth contact name should be the same as sale order customer name.") self.assertEqual( booth.contact_mobile, self.event_customer.mobile, "Booth contact mobile should be the same as sale order customer mobile.") self.assertEqual( booth.contact_phone, self.event_customer.phone, "Booth contact phone should be the same as sale order customer phone.") self.assertEqual( booth.state, 'unavailable', "Booth should not be available anymore.") @tagged('post_install', '-at_install') class TestEventBoothSaleInvoice(TestSaleCommon, TestEventBoothSaleWData): @classmethod def setUpClass(cls): super(TestEventBoothSaleInvoice, cls).setUpClass() # Add group `group_account_invoice` to user_sales_salesman to allow to pay the invoice cls.user_sales_salesman.groups_id += cls.env.ref('account.group_account_invoice') @users('user_sales_salesman') def test_event_booth_with_invoice(self): booth = self.booth_1.with_env(self.env) self.assertEqual(booth.state, 'available') sale_order = self.env['sale.order'].create({ 'partner_id': self.event_customer.id, 'pricelist_id': self.test_pricelist.id, 'order_line': [ Command.create({ 'product_id': self.event_booth_product.id, 'event_id': self.event_0.id, 'event_booth_pending_ids': booth.ids }) ] }) sale_order.action_confirm() self.assertEqual(booth.state, 'unavailable') self.assertFalse(booth.is_paid) # Create and check that the invoice was created invoice = sale_order._create_invoices() self.assertEqual(len(sale_order.invoice_ids), 1, "Invoice not created.") # Confirm the invoice and check SO invoice status invoice.action_post() self.assertEqual( sale_order.invoice_status, 'invoiced', f"Order is in '{sale_order.invoice_status}' status while it should be 'invoiced'.") # Pay the invoice. journal = self.env['account.journal'].search([('type', '=', 'cash'), ('company_id', '=', sale_order.company_id.id)], limit=1) register_payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'journal_id': journal.id, }) register_payments._create_payments() # Check the invoice payment state after paying the invoice in_payment_state = invoice._get_invoice_in_payment_state() self.assertEqual(invoice.payment_state, in_payment_state, f"Invoice payment is in '{invoice.payment_state}' status while it should be '{in_payment_state}'.") self.assertEqual(booth.state, 'unavailable') self.assertTrue(booth.is_paid)
47.819355
7,412
1,101
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.event_booth.tests.common import TestEventBoothCommon from odoo.addons.event_sale.tests.common import TestEventSaleCommon class TestEventBoothSaleCommon(TestEventBoothCommon, TestEventSaleCommon): @classmethod def setUpClass(cls): super(TestEventBoothSaleCommon, cls).setUpClass() cls.event_booth_product = cls.env['product.product'].create({ 'name': 'Test Booth Product', 'description_sale': 'Mighty Booth Description', 'list_price': 20, 'standard_price': 60.0, 'detailed_type': 'event_booth', }) (cls.event_booth_category_1 + cls.event_booth_category_2).write({ 'product_id': cls.event_booth_product.id, }) cls.tax_10 = cls.env['account.tax'].sudo().create({ 'name': 'Tax 10', 'amount': 10, }) cls.test_pricelist = cls.env['product.pricelist'].sudo().create({ 'name': 'Test Pricelist', })
34.40625
1,101
4,151
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, timedelta from odoo import Command from odoo.addons.event_booth_sale.tests.common import TestEventBoothSaleCommon from odoo.fields import Datetime as FieldsDatetime from odoo.tests.common import users, Form class TestEventData(TestEventBoothSaleCommon): @users('user_eventmanager') def test_event_configuration_booths_from_type(self): """ Test data computation (related to booths) of event coming from its event.type template. """ # setup test records event_type_nobooth = self.env['event.type'].create({ 'name': 'No booth', }) event_type_wbooths = self.env['event.type'].create({ 'name': 'Using booths', 'event_type_booth_ids': [ Command.clear(), Command.create({ 'name': 'Standard Booth', 'booth_category_id': self.event_booth_category_1.id, }), Command.create({ 'name': 'Premium Booth', 'booth_category_id': self.event_booth_category_2.id, }) ] }) # no booth by default as no booths on type event = self.env['event.event'].create({ 'name': 'Event', 'date_begin': FieldsDatetime.to_string(datetime.today() + timedelta(days=1)), 'date_end': FieldsDatetime.to_string(datetime.today() + timedelta(days=15)), 'event_type_id': event_type_nobooth.id }) self.assertEqual(event.event_booth_ids, self.env['event.booth']) # manually create booths: ok event.write({ 'event_booth_ids': [ Command.create({ 'name': 'Custom Standard Booth 1', 'booth_category_id': self.event_booth_category_1.id, }), Command.create({ 'name': 'Custom Standard Booth 2', 'booth_category_id': self.event_booth_category_1.id, }) ] }) self.assertEqual(event.event_booth_count, 2) self.assertEqual(event.event_booth_count_available, 2) self.assertEqual(event.event_booth_ids.product_id, self.event_booth_product) # updating partner is independent from availability event.event_booth_ids[1].write({'partner_id': self.event_customer.id}) self.assertEqual(event.event_booth_count, 2) self.assertEqual(event.event_booth_count_available, 2) self.assertEqual(event.event_booth_ids[1].message_partner_ids, self.event_customer) # one booth is sold event.event_booth_ids[1].write({'state': 'unavailable'}) self.assertEqual(event.event_booth_count, 2) self.assertEqual(event.event_booth_count_available, 1) # partner is reset: booth still unavailable but follower removed event.event_booth_ids[1].write({'partner_id': False}) self.assertEqual(event.event_booth_count, 2) self.assertEqual(event.event_booth_count_available, 1) self.assertEqual(event.event_booth_ids[1].message_partner_ids, self.env['res.partner']) # add group or the test will fail self.user_eventmanager.write({'groups_id': [ (4, self.env.ref('sales_team.group_sale_salesman').id), ]}) # change event type to one using booths: include event type booths and keep reserved booths with Form(event) as event_form: event_form.event_type_id = event_type_wbooths self.assertEqual(event.event_booth_count, 3) self.assertEqual( set(r['name'] for r in event.event_booth_ids), set(('Custom Standard Booth 2', 'Standard Booth', 'Premium Booth')), 'Should keep booths with reservation, remove unused ones and add type ones' ) self.assertEqual(event.event_booth_count_available, 2) self.assertEqual(event.event_booth_category_ids, self.event_booth_category_1 + self.event_booth_category_2)
44.159574
4,151
1,558
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields, _ from odoo.exceptions import ValidationError class EventBoothConfigurator(models.TransientModel): _name = 'event.booth.configurator' _description = 'Event Booth Configurator' product_id = fields.Many2one('product.product', string='Product', readonly=True) sale_order_line_id = fields.Many2one('sale.order.line', string='Sale Order Line', readonly=True) event_id = fields.Many2one('event.event', string='Event', required=True) event_booth_category_available_ids = fields.Many2many(related='event_id.event_booth_category_available_ids', readonly=True) event_booth_category_id = fields.Many2one( 'event.booth.category', string='Booth Category', required=True, compute='_compute_event_booth_category_id', readonly=False, store=True) event_booth_ids = fields.Many2many( 'event.booth', string='Booth', required=True, compute='_compute_event_booth_ids', readonly=False, store=True) @api.depends('event_id') def _compute_event_booth_category_id(self): self.event_booth_category_id = False @api.depends('event_id', 'event_booth_category_id') def _compute_event_booth_ids(self): self.event_booth_ids = False @api.constrains('event_booth_ids') def _check_if_no_booth_ids(self): if any(not wizard.event_booth_ids for wizard in self): raise ValidationError(_('You have to select at least one booth.'))
45.823529
1,558
557
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class AccountMove(models.Model): _inherit = 'account.move' def action_invoice_paid(self): """ When an invoice linked to a sales order selling registrations is paid, update booths accordingly as they are booked when invoice is paid. """ res = super(AccountMove, self).action_invoice_paid() self.mapped('line_ids.sale_line_ids')._update_event_booths(set_paid=True) return res
34.8125
557
1,305
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class SaleOrder(models.Model): _inherit = 'sale.order' event_booth_ids = fields.One2many('event.booth', 'sale_order_id', string='Booths') event_booth_count = fields.Integer(string='Booth Count', compute='_compute_event_booth_count') @api.depends('event_booth_ids') def _compute_event_booth_count(self): if self.ids: slot_data = self.env['event.booth'].read_group( [('sale_order_id', 'in', self.ids)], ['sale_order_id'], ['sale_order_id'] ) slot_mapped = dict((data['sale_order_id'][0], data['sale_order_id_count']) for data in slot_data) else: slot_mapped = dict() for so in self: so.event_booth_count = slot_mapped.get(so.id, 0) def action_confirm(self): res = super(SaleOrder, self).action_confirm() for so in self: so.order_line._update_event_booths() return res def action_view_booth_list(self): action = self.env['ir.actions.act_window']._for_xml_id('event_booth.event_booth_action') action['domain'] = [('sale_order_id', 'in', self.ids)] return action
37.285714
1,305
5,176
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class SaleOrderLine(models.Model): _inherit = 'sale.order.line' event_booth_category_id = fields.Many2one('event.booth.category', string='Booths Category', ondelete='set null') event_booth_pending_ids = fields.Many2many( 'event.booth', string='Pending Booths', search='_search_event_booth_pending_ids', compute='_compute_event_booth_pending_ids', inverse='_inverse_event_booth_pending_ids', help='Used to create registration when providing the desired event booth.' ) event_booth_registration_ids = fields.One2many( 'event.booth.registration', 'sale_order_line_id', string='Confirmed Registration') event_booth_ids = fields.One2many('event.booth', 'sale_order_line_id', string='Confirmed Booths') is_event_booth = fields.Boolean(compute='_compute_is_event_booth') @api.depends('product_id.type') def _compute_is_event_booth(self): for record in self: record.is_event_booth = record.product_id.detailed_type == 'event_booth' @api.depends('event_booth_ids') def _compute_name_short(self): wbooth = self.filtered(lambda line: line.event_booth_pending_ids) for record in wbooth: record.name_short = record.event_booth_pending_ids.event_id.name super(SaleOrderLine, self - wbooth)._compute_name_short() @api.depends('event_booth_registration_ids') def _compute_event_booth_pending_ids(self): for so_line in self: so_line.event_booth_pending_ids = so_line.event_booth_registration_ids.event_booth_id def _inverse_event_booth_pending_ids(self): for so_line in self: self.env['event.booth.registration'].create([{ 'event_booth_id': booth.id, 'sale_order_line_id': so_line.id, 'partner_id': so_line.order_id.partner_id.id } for booth in so_line.event_booth_pending_ids]) def _search_event_booth_pending_ids(self, operator, value): return [('event_booth_registration_ids.event_booth_id', operator, value)] @api.constrains('event_booth_registration_ids') def _check_event_booth_registration_ids(self): if len(self.event_booth_registration_ids.event_booth_id.event_id) > 1: raise ValidationError(_('Registrations from the same Order Line must belong to a single event.')) @api.onchange('product_id') def _onchange_product_id_booth(self): """We reset the event when the selected product doesn't belong to any pending booths.""" if self.event_id and (not self.product_id or self.product_id not in self.event_booth_pending_ids.product_id): self.event_id = None @api.onchange('event_id') def _onchange_event_id_booth(self): """We reset the pending booths when the event changes to avoid inconsistent state.""" if self.event_booth_pending_ids and (not self.event_id or self.event_id != self.event_booth_pending_ids.event_id): self.event_booth_pending_ids = None @api.onchange('event_booth_pending_ids') def _onchange_event_booth_pending_ids(self): # trigger the description computation self.product_id_change() def _update_event_booths(self, set_paid=False): for so_line in self.filtered('is_event_booth'): if so_line.event_booth_pending_ids and not so_line.event_booth_ids: unavailable = so_line.event_booth_pending_ids.filtered(lambda booth: not booth.is_available) if unavailable: raise ValidationError( _('The following booths are unavailable, please remove them to continue : %(booth_names)s', booth_names=''.join('\n\t- %s' % booth.display_name for booth in unavailable))) so_line.event_booth_registration_ids.sudo().action_confirm() if so_line.event_booth_ids and set_paid: so_line.event_booth_ids.sudo().action_set_paid() return True def get_sale_order_line_multiline_description_sale(self, product): if self.event_booth_pending_ids: booths = self.event_booth_pending_ids.with_context( lang=self.order_id.partner_id.lang, ) return booths._get_booth_multiline_description() return super(SaleOrderLine, self).get_sale_order_line_multiline_description_sale(product) def _get_display_price(self, product): if self.event_booth_pending_ids and self.event_id: company = self.event_id.company_id or self.env.company currency = company.currency_id total_price = sum([booth.price for booth in self.event_booth_pending_ids]) return currency._convert( total_price, self.order_id.currency_id, self.order_id.company_id or self.env.company.id, self.order_id.date_order or fields.Date.today()) return super(SaleOrderLine, self)._get_display_price(product)
50.745098
5,176
4,518
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class EventBoothCategory(models.Model): _inherit = 'event.booth.category' def _default_product_id(self): return self.env.ref('event_booth_sale.product_product_event_booth', raise_if_not_found=False) product_id = fields.Many2one( 'product.product', string='Product', required=True, domain=[('detailed_type', '=', 'event_booth')], default=_default_product_id) price = fields.Float(string='Price', compute='_compute_price', digits='Product Price', readonly=False, store=True) currency_id = fields.Many2one(related='product_id.currency_id') price_reduce = fields.Float( string='Price Reduce', compute='_compute_price_reduce', compute_sudo=True, digits='Product Price') price_reduce_taxinc = fields.Float( string='Price Reduce Tax inc', compute='_compute_price_reduce_taxinc', compute_sudo=True ) image_1920 = fields.Image(compute='_compute_image_1920', readonly=False, store=True) @api.depends('product_id') def _compute_image_1920(self): for category in self: category.image_1920 = category.image_1920 if category.image_1920 else category.product_id.image_1920 @api.depends('product_id') def _compute_price(self): """ By default price comes from category but can be changed by event people as product may be shared across various categories. """ for category in self: if category.product_id and category.product_id.list_price: category.price = category.product_id.list_price + category.product_id.price_extra @api.depends_context('pricelist', 'quantity') @api.depends('product_id', 'price') def _compute_price_reduce(self): for category in self: product = category.product_id pricelist = self.env['product.pricelist'].browse(self._context.get('pricelist')) lst_price = product.currency_id._convert( product.lst_price, pricelist.currency_id, self.env.company, fields.Datetime.now() ) discount = (lst_price - product.price) / lst_price if lst_price else 0.0 category.price_reduce = (1.0 - discount) * category.price @api.depends_context('pricelist', 'quantity') @api.depends('product_id', 'price_reduce') def _compute_price_reduce_taxinc(self): for category in self: tax_ids = category.product_id.taxes_id taxes = tax_ids.compute_all(category.price_reduce, category.currency_id, 1.0, product=category.product_id) category.price_reduce_taxinc = taxes['total_included'] def _init_column(self, column_name): """ Initialize product_id for existing columns when installing sale bridge, to ensure required attribute is fulfilled. """ if column_name != "product_id": return super(EventBoothCategory, self)._init_column(column_name) # fetch void columns self.env.cr.execute("SELECT id FROM %s WHERE product_id IS NULL" % self._table) booth_category_ids = self.env.cr.fetchall() if not booth_category_ids: return # update existing columns _logger.debug("Table '%s': setting default value of new column %s to unique values for each row", self._table, column_name) default_booth_product = self._default_product_id() if default_booth_product: product_id = default_booth_product.id else: product_id = self.env['product.product'].create({ 'name': 'Generic Event Booth Product', 'categ_id': self.env.ref('event_sale.product_category_events').id, 'list_price': 100, 'standard_price': 0, 'detailed_type': 'event_booth', 'invoice_policy': 'order', }).id self.env['ir.model.data'].create({ 'name': 'product_product_event_booth', 'module': 'event_booth_sale', 'model': 'product.product', 'res_id': product_id, }) self.env.cr._obj.execute( f'UPDATE {self._table} SET product_id = %s WHERE id IN %s;', (product_id, tuple(booth_category_ids)) )
43.864078
4,518
242
py
PYTHON
15.0
from odoo import fields, models class SaleOrderTemplateLine(models.Model): _inherit = "sale.order.template.line" product_id = fields.Many2one(domain="[('sale_ok', '=', True), ('detailed_type', 'not in', ['event', 'event_booth'])]")
40.333333
242
923
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = 'product.template' detailed_type = fields.Selection(selection_add=[ ('event_booth', 'Event Booth'), ], ondelete={'event_booth': 'set service'}) @api.onchange('detailed_type') def _onchange_type_event_booth(self): if self.detailed_type == 'event_booth': self.invoice_policy = 'order' def _detailed_type_mapping(self): type_mapping = super()._detailed_type_mapping() type_mapping['event_booth'] = 'service' return type_mapping class Product(models.Model): _inherit = 'product.product' @api.onchange('detailed_type') def _onchange_type_event_booth(self): if self.detailed_type == 'event_booth': self.invoice_policy = 'order'
29.774194
923
606
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class EventTypeBooth(models.Model): _inherit = 'event.type.booth' product_id = fields.Many2one(related='booth_category_id.product_id') price = fields.Float(related='booth_category_id.price') currency_id = fields.Many2one(related='booth_category_id.currency_id') @api.model def _get_event_booth_fields_whitelist(self): res = super(EventTypeBooth, self)._get_event_booth_fields_whitelist() return res + ['product_id', 'price']
35.647059
606
3,759
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class EventBoothRegistration(models.Model): """event.booth.registrations are used to allow multiple partners to book the same booth. Whenever a partner has paid his registration all the others linked to the booth will be deleted.""" _name = 'event.booth.registration' _description = 'Event Booth Registration' sale_order_line_id = fields.Many2one('sale.order.line', string='Sale Order Line', required=True, ondelete='cascade') event_booth_id = fields.Many2one('event.booth', string='Booth', required=True) partner_id = fields.Many2one( 'res.partner', related='sale_order_line_id.order_partner_id', store=True) contact_name = fields.Char(string='Contact Name', compute='_compute_contact_name', readonly=False, store=True) contact_email = fields.Char(string='Contact Email', compute='_compute_contact_email', readonly=False, store=True) contact_phone = fields.Char(string='Contact Phone', compute='_compute_contact_phone', readonly=False, store=True) contact_mobile = fields.Char(string='Contact Mobile', compute='_compute_contact_mobile', readonly=False, store=True) _sql_constraints = [('unique_registration', 'unique(sale_order_line_id, event_booth_id)', 'There can be only one registration for a booth by sale order line')] @api.depends('partner_id') def _compute_contact_name(self): for registration in self: if not registration.contact_name: registration.contact_name = registration.partner_id.name or False @api.depends('partner_id') def _compute_contact_email(self): for registration in self: if not registration.contact_email: registration.contact_email = registration.partner_id.email or False @api.depends('partner_id') def _compute_contact_phone(self): for registration in self: if not registration.contact_phone: registration.contact_phone = registration.partner_id.phone or False @api.depends('partner_id') def _compute_contact_mobile(self): for registration in self: if not registration.contact_mobile: registration.contact_mobile = registration.partner_id.mobile or False @api.model def _get_fields_for_booth_confirmation(self): return ['sale_order_line_id', 'partner_id', 'contact_name', 'contact_email', 'contact_phone', 'contact_mobile'] def action_confirm(self): for registration in self: values = { field: registration[field].id if isinstance(registration[field], models.BaseModel) else registration[field] for field in self._get_fields_for_booth_confirmation() } registration.event_booth_id.action_confirm(values) self._cancel_pending_registrations() def _cancel_pending_registrations(self): body = '<p>%(message)s: <ul>%(booth_names)s</ul></p>' % { 'message': _('Your order has been cancelled because the following booths have been reserved'), 'booth_names': ''.join('<li>%s</li>' % booth.display_name for booth in self.event_booth_id) } other_registrations = self.search([ ('event_booth_id', 'in', self.event_booth_id.ids), ('id', 'not in', self.ids) ]) for order in other_registrations.sale_order_line_id.order_id: order.sudo().message_post( body=body, partner_ids=order.user_id.partner_id.ids, ) order.sudo().action_cancel() other_registrations.unlink()
48.192308
3,759
2,023
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class EventBooth(models.Model): _inherit = 'event.booth' # registrations event_booth_registration_ids = fields.One2many('event.booth.registration', 'event_booth_id') # sale information sale_order_line_registration_ids = fields.Many2many( 'sale.order.line', 'event_booth_registration', 'event_booth_id', 'sale_order_line_id', string='SO Lines with reservations', groups='sales_team.group_sale_salesman', copy=False) sale_order_line_id = fields.Many2one( 'sale.order.line', string='Final Sale Order Line', ondelete='set null', readonly=True, states={'available': [('readonly', False)]}, groups='sales_team.group_sale_salesman', copy=False) sale_order_id = fields.Many2one( related='sale_order_line_id.order_id', store='True', readonly=True, groups='sales_team.group_sale_salesman') is_paid = fields.Boolean('Is Paid', copy=False) @api.ondelete(at_uninstall=False) def _unlink_except_linked_sale_order(self): booth_with_so = self.sudo().filtered('sale_order_id') if booth_with_so: raise UserError(_( 'You can\'t delete the following booths as they are linked to sales orders: ' '%(booths)s', booths=', '.join(booth_with_so.mapped('name')))) def action_set_paid(self): self.write({'is_paid': True}) def action_view_sale_order(self): self.sale_order_id.ensure_one() action = self.env['ir.actions.actions']._for_xml_id('sale.action_orders') action['views'] = [(False, 'form')] action['res_id'] = self.sale_order_id.id return action def _get_booth_multiline_description(self): return '%s : \n%s' % ( self.event_id.display_name, '\n'.join(['- %s' % booth.name for booth in self]) )
41.285714
2,023
246
py
PYTHON
15.0
from odoo import fields, models class SaleOrderTemplateOption(models.Model): _inherit = "sale.order.template.option" product_id = fields.Many2one(domain="[('sale_ok', '=', True), ('detailed_type', 'not in', ['event', 'event_booth'])]")
41
246
1,361
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Egyptian E-Invoice Integration", 'summary': """ Egyptian Tax Authority Invoice Integration """, 'description': """ This module integrate with the ETA Portal to automatically sign and send your invoices to the tax Authority. Special thanks to Plementus <info@plementus.com> for their help in developing this module. """, 'author': 'odoo', 'website': 'https://www.odoo.com', 'category': 'account', 'version': '0.2', 'license': 'LGPL-3', 'depends': ['account_edi', 'l10n_eg'], 'data': [ 'data/account_edi_data.xml', 'data/l10n_eg_edi.activity.type.csv', 'data/l10n_eg_edi.uom.code.csv', 'data/uom.uom.csv', 'security/ir.model.access.csv', 'security/eta_thumb_drive_security.xml', 'views/uom_uom_view.xml', 'views/account_move_view.xml', 'views/account_journal_view.xml', 'views/eta_thumb_drive.xml', 'views/product_template_views.xml', 'views/res_config_settings_view.xml', 'views/report_invoice.xml', 'data/res_country_data.xml', ], 'assets': { 'web.assets_backend': [ 'l10n_eg_edi_eta/static/src/js/sign_invoice.js', ], }, 'external_dependencies': { 'python': ['asn1crypto'], }, }
33.195122
1,361
41,264
py
PYTHON
15.0
import json from unittest.mock import patch from freezegun import freeze_time from odoo.tests import tagged from .common import TestEGEdiCommon ETA_TEST_RESPONSE = { 'l10n_eg_uuid': 'UUIDXIL9182712KMHJQ', 'l10n_eg_long_id': 'LIDMN12132LASKXXA', 'l10n_eg_internal_id': 'INTLA1212MMKA12', 'l10n_eg_hash_key': 'BaK12lX1kASdma12', 'l10n_eg_submission_number': '12125523452353', } ETA_TEST_SIGNATURES = [{'1': '1'}] COMMON_REQUEST_DICT = { 'issuer': { 'address': { 'country': 'EG', 'governate': 'Cairo', 'regionCity': 'Iswan', 'street': '12th dec. street', 'buildingNumber': '10', 'postalCode': '', 'branchID': '0', }, 'name': 'branch partner', 'type': 'B', 'id': '918KKL1', }, 'documentType': 'i', 'documentTypeVersion': '1.0', 'dateTimeIssued': '2022-03-15T00:00:00Z', 'taxpayerActivityCode': '8121', 'internalID': 'INV/2022/00001', 'totalDiscountAmount': 0.0, 'extraDiscountAmount': 0.0, 'totalItemsDiscountAmount': 0.0, 'signatures': ETA_TEST_SIGNATURES, } def mocked_action_post_sign_invoices(self): for invoice in self: eta_invoice = self.env['account.edi.format']._l10n_eg_eta_prepare_eta_invoice(self) eta_invoice['signatures'] = ETA_TEST_SIGNATURES attachment = self.env['ir.attachment'].create( { 'name': ('ETA_INVOICE_DOC_%s', invoice.name), 'res_id': invoice.id, 'res_model': invoice._name, 'type': 'binary', 'raw': json.dumps(dict(request=eta_invoice)), 'mimetype': 'application/json', 'description': ('Egyptian Tax authority JSON invoice generated for %s.', invoice.name), } ) invoice.l10n_eg_eta_json_doc_id = attachment.id return True def mocked_l10n_eg_edi_post_invoice_web_service(self, invoice): eta_invoice_json = json.loads(invoice.l10n_eg_eta_json_doc_id.raw) eta_invoice_json['response'] = ETA_TEST_RESPONSE invoice.l10n_eg_eta_json_doc_id.raw = json.dumps(eta_invoice_json) return {'success': True, 'attachment': invoice.l10n_eg_eta_json_doc_id} @tagged('post_install_l10n', 'post_install', '-at_install') class TestEdiJson(TestEGEdiCommon): def test_1_simple_test_local_parter_no_tax(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( partner_id=self.partner_a.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 100.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, }, { 'product_id': self.product_a.id, 'price_unit': 200.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'EG', 'governate': 'Cairo', 'regionCity': 'Iswan', 'street': '12th dec. street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_a', 'type': 'B', 'id': 'BE0477472701', }, 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 100.0}, 'discount': {'rate': 0.0, 'amount': 0.0}, 'taxableItems': [], 'salesTotal': 100.0, 'netTotal': 100.0, 'total': 100.0, }, { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 200.0}, 'discount': {'rate': 0.0, 'amount': 0.0}, 'taxableItems': [], 'salesTotal': 200.0, 'netTotal': 200.0, 'total': 200.0, }, ], 'taxTotals': [], 'totalSalesAmount': 300.0, 'netAmount': 300.0, 'totalAmount': 300.0, }, 'response': ETA_TEST_RESPONSE, }, ) def test_2_simple_test_local_parter_vat_14(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( partner_id=self.partner_a.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 120.99, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, { 'product_id': self.product_a.id, 'price_unit': 999.99, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'EG', 'governate': 'Cairo', 'regionCity': 'Iswan', 'street': '12th dec. street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_a', 'type': 'B', 'id': 'BE0477472701', }, 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 120.99}, 'discount': {'rate': 0.0, 'amount': -0.0}, 'taxableItems': [{'taxType': 'T1', 'amount': 16.94, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 120.99, 'netTotal': 120.99, 'total': 137.93, }, { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 999.99}, 'discount': {'rate': 0.0, 'amount': 0.0}, 'taxableItems': [{'taxType': 'T1', 'amount': 140.0, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 999.99, 'netTotal': 999.99, 'total': 1139.99, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 156.94}], 'totalSalesAmount': 1120.98, 'netAmount': 1120.98, 'totalAmount': 1277.92, }, 'response': ETA_TEST_RESPONSE, }, ) def test_3_simple_test_local_parter_vat_14_discount_credit_note(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( move_type='out_refund', partner_id=self.partner_a.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 12.0, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, { 'product_id': self.product_a.id, 'price_unit': 99.96, 'quantity': 1.0, 'discount': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'EG', 'governate': 'Cairo', 'regionCity': 'Iswan', 'street': '12th dec. street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_a', 'type': 'B', 'id': 'BE0477472701', }, 'internalID': 'RINV/2022/00001', 'documentType': 'c', 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 12.0}, 'discount': {'rate': 10.0, 'amount': 1.2}, 'taxableItems': [{'taxType': 'T1', 'amount': 1.51, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 12.0, 'netTotal': 10.8, 'total': 12.31, }, { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 99.95556}, 'discount': {'rate': 10.0, 'amount': 9.99556}, 'taxableItems': [{'taxType': 'T1', 'amount': 12.59, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 99.95556, 'netTotal': 89.96, 'total': 102.55, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 14.1}], 'totalDiscountAmount': 11.19556, 'totalSalesAmount': 111.95556, 'netAmount': 100.76, 'totalAmount': 114.86, }, 'response': ETA_TEST_RESPONSE, }, ) def test_4_simple_test_local_parter_vat_14_discount(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( partner_id=self.partner_a.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 120.99, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, { 'product_id': self.product_a.id, 'price_unit': 999.55, 'quantity': 1.0, 'discount': 10.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_standard_sale_14').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'EG', 'governate': 'Cairo', 'regionCity': 'Iswan', 'street': '12th dec. street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_a', 'type': 'B', 'id': 'BE0477472701', }, 'documentType': 'i', 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 120.98889}, 'discount': {'rate': 10.0, 'amount': 12.09889}, 'taxableItems': [{'taxType': 'T1', 'amount': 15.24, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 120.98889, 'netTotal': 108.89, 'total': 124.13, }, { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 999.55556}, 'discount': {'rate': 10.0, 'amount': 99.95556}, 'taxableItems': [{'taxType': 'T1', 'amount': 125.94, 'subType': 'V009', 'rate': 14.0}], 'salesTotal': 999.55556, 'netTotal': 899.6, 'total': 1025.54, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 141.18}], 'totalDiscountAmount': 112.05445, 'totalSalesAmount': 1120.54445, 'netAmount': 1008.49, 'totalAmount': 1149.67, }, 'response': ETA_TEST_RESPONSE, }, ) def test_5_simple_test_foreign_partner_exempt_discount(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( partner_id=self.partner_b.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 120.99, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, { 'product_id': self.product_b.id, 'price_unit': 999.55, 'quantity': 5.0, 'discount': 13.0, 'product_uom_id': self.env.ref('uom.product_uom_cm').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'US', 'governate': 'New York', 'regionCity': 'New York City', 'street': '5th avenue street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_b', 'type': 'F', 'id': 'ESF35999705', }, 'documentType': 'i', 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 120.98889}, 'discount': {'rate': 10.0, 'amount': 12.09889}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 120.98889, 'netTotal': 108.89, 'total': 108.89, }, { 'description': 'product_b', 'itemType': 'EGS', 'itemCode': 'EG-EGS-TEST', 'unitType': 'CMT', 'quantity': 5.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': {'currencySold': 'EGP', 'amountEGP': 999.54943}, 'discount': {'rate': 13.0, 'amount': 649.70713}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 4997.74713, 'netTotal': 4348.04, 'total': 4348.04, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 0.0}], 'totalDiscountAmount': 661.80602, 'totalSalesAmount': 5118.73602, 'netAmount': 4456.93, 'totalAmount': 4456.93, }, 'response': ETA_TEST_RESPONSE, }, ) def test_6_simple_test_foreign_parter_exempt_discount_foreign_currency(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( currency_id=self.currency_aed_id.id, partner_id=self.partner_b.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 120.99, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, { 'product_id': self.product_b.id, 'price_unit': 999.55, 'quantity': 5.0, 'discount': 13.0, 'product_uom_id': self.env.ref('uom.product_uom_cm').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'US', 'governate': 'New York', 'regionCity': 'New York City', 'street': '5th avenue street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_b', 'type': 'F', 'id': 'ESF35999705', }, 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': { 'currencySold': 'AED', 'amountEGP': 610.68889, 'currencyExchangeRate': 5.04748, 'amountSold': 120.99, }, 'discount': {'rate': 10.0, 'amount': 61.06889}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 610.68889, 'netTotal': 549.62, 'total': 549.62, }, { 'description': 'product_b', 'itemType': 'EGS', 'itemCode': 'EG-EGS-TEST', 'unitType': 'CMT', 'quantity': 5.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': { 'currencySold': 'AED', 'amountEGP': 5045.24598, 'currencyExchangeRate': 5.04748, 'amountSold': 999.55, }, 'discount': {'rate': 13.0, 'amount': 3279.40989}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 25226.22989, 'netTotal': 21946.82, 'total': 21946.82, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 0.0}], 'totalDiscountAmount': 3340.47878, 'totalSalesAmount': 25836.91878, 'netAmount': 22496.44, 'totalAmount': 22496.44, }, 'response': ETA_TEST_RESPONSE, }, ) def test_7_simple_test_foreign_parter_exempt_discount_foreign_currency_credit_note(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( move_type='out_invoice', currency_id=self.currency_aed_id.id, partner_id=self.partner_b.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 100.0, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, { 'product_id': self.product_b.id, 'price_unit': 100.35, 'quantity': 5.0, 'discount': 13.0, 'product_uom_id': self.env.ref('uom.product_uom_cm').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) self.assertEqual( json_file, { 'request': {**COMMON_REQUEST_DICT, 'receiver': { 'address': { 'country': 'US', 'governate': 'New York', 'regionCity': 'New York City', 'street': '5th avenue street', 'buildingNumber': '12', 'postalCode': '', }, 'name': 'partner_b', 'type': 'F', 'id': 'ESF35999705', }, 'invoiceLines': [ { 'description': 'product_a', 'itemType': 'GS1', 'itemCode': '1KGS1TEST', 'unitType': 'C62', 'quantity': 1.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': { 'currencySold': 'AED', 'amountEGP': 504.75556, 'currencyExchangeRate': 5.04756, 'amountSold': 100.0, }, 'discount': {'rate': 10.0, 'amount': 50.47556}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 504.75556, 'netTotal': 454.28, 'total': 454.28, }, { 'description': 'product_b', 'itemType': 'EGS', 'itemCode': 'EG-EGS-TEST', 'unitType': 'CMT', 'quantity': 5.0, 'internalCode': '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': { 'currencySold': 'AED', 'amountEGP': 506.51494, 'currencyExchangeRate': 5.04756, 'amountSold': 100.35, }, 'discount': {'rate': 13.0, 'amount': 329.23471}, 'taxableItems': [{'taxType': 'T1', 'amount': 0.0, 'subType': 'V003', 'rate': 0.0}], 'salesTotal': 2532.57471, 'netTotal': 2203.34, 'total': 2203.34, }, ], 'taxTotals': [{'taxType': 'T1', 'amount': 0.0}], 'totalDiscountAmount': 379.71027, 'totalSalesAmount': 3037.33027, 'netAmount': 2657.62, 'totalAmount': 2657.62, }, 'response': ETA_TEST_RESPONSE, }, ) def test_8_test_serialization_function(self): with freeze_time(self.frozen_today), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_move.AccountMove.action_post_sign_invoices', new=mocked_action_post_sign_invoices, ), patch( 'odoo.addons.l10n_eg_edi_eta.models.account_edi_format.AccountEdiFormat._l10n_eg_edi_post_invoice_web_service', new=mocked_l10n_eg_edi_post_invoice_web_service, ): invoice = self.create_invoice( move_type='out_invoice', currency_id=self.currency_aed_id.id, partner_id=self.partner_c.id, invoice_line_ids=[ { 'product_id': self.product_a.id, 'price_unit': 100.0, 'quantity': 1.0, 'product_uom_id': self.env.ref('uom.product_uom_unit').id, 'discount': 10.0, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, { 'product_id': self.product_b.id, 'price_unit': 100.35, 'quantity': 5.0, 'discount': 13.0, 'product_uom_id': self.env.ref('uom.product_uom_cm').id, 'tax_ids': [(6, 0, self.env.ref(f'l10n_eg.{self.env.company.id}_eg_exempt_sale').ids)], }, ], ) invoice.action_post() invoice.action_post_sign_invoices() generated_files = self._process_documents_web_services(invoice, {'eg_eta'}) self.assertTrue(generated_files) json_file = json.loads(generated_files[0]) serialized_string = self.env['l10n_eg_edi.thumb.drive']._serialize_for_signing(json_file['request']) self.assertEqual(serialized_string, '"ISSUER""ADDRESS""COUNTRY""EG""GOVERNATE""Cairo""REGIONCITY""Iswan""STREET""12th dec. street""BUILDINGNUMBER""10""POSTALCODE""""BRANCHID""0""NAME""branch partner""TYPE""B""ID""918KKL1""RECEIVER""ADDRESS""COUNTRY""EG""GOVERNATE""Cairo""REGIONCITY""Iswan""STREET""12th dec. street""BUILDINGNUMBER""12""POSTALCODE""""NAME""عميل 1""TYPE""B""ID""EG11231212""DOCUMENTTYPE""i""DOCUMENTTYPEVERSION""1.0""DATETIMEISSUED""2022-03-15T00:00:00Z""TAXPAYERACTIVITYCODE""8121""INTERNALID""INV/2022/00001""INVOICELINES""INVOICELINES""DESCRIPTION""product_a""ITEMTYPE""GS1""ITEMCODE""1KGS1TEST""UNITTYPE""C62""QUANTITY""1.0""INTERNALCODE""""VALUEDIFFERENCE""0.0""TOTALTAXABLEFEES""0.0""ITEMSDISCOUNT""0.0""UNITVALUE""CURRENCYSOLD""AED""AMOUNTEGP""504.75556""CURRENCYEXCHANGERATE""5.04756""AMOUNTSOLD""100.0""DISCOUNT""RATE""10.0""AMOUNT""50.47556""TAXABLEITEMS""TAXABLEITEMS""TAXTYPE""T1""AMOUNT""0.0""SUBTYPE""V003""RATE""0.0""SALESTOTAL""504.75556""NETTOTAL""454.28""TOTAL""454.28""INVOICELINES""DESCRIPTION""product_b""ITEMTYPE""EGS""ITEMCODE""EG-EGS-TEST""UNITTYPE""CMT""QUANTITY""5.0""INTERNALCODE""""VALUEDIFFERENCE""0.0""TOTALTAXABLEFEES""0.0""ITEMSDISCOUNT""0.0""UNITVALUE""CURRENCYSOLD""AED""AMOUNTEGP""506.51494""CURRENCYEXCHANGERATE""5.04756""AMOUNTSOLD""100.35""DISCOUNT""RATE""13.0""AMOUNT""329.23471""TAXABLEITEMS""TAXABLEITEMS""TAXTYPE""T1""AMOUNT""0.0""SUBTYPE""V003""RATE""0.0""SALESTOTAL""2532.57471""NETTOTAL""2203.34""TOTAL""2203.34""TAXTOTALS""TAXTOTALS""TAXTYPE""T1""AMOUNT""0.0""TOTALDISCOUNTAMOUNT""379.71027""TOTALSALESAMOUNT""3037.33027""NETAMOUNT""2657.62""TOTALAMOUNT""2657.62""EXTRADISCOUNTAMOUNT""0.0""TOTALITEMSDISCOUNTAMOUNT""0.0""SIGNATURES""SIGNATURES""1""1"')
50.625767
41,260
4,011
py
PYTHON
15.0
from datetime import datetime from pytz import timezone from odoo.fields import Command from odoo.tests import tagged from odoo.addons.account_edi.tests.common import AccountEdiTestCommon @tagged('post_install_l10n', 'post_install', '-at_install') class TestEGEdiCommon(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_eg.egypt_chart_template_standard', edi_format_ref='l10n_eg_edi_eta.edi_eg_eta'): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) cls.frozen_today = datetime(year=2022, month=3, day=15, hour=0, minute=0, second=0, tzinfo=timezone('utc')) cls.currency_aed_id = cls.env.ref('base.AED') cls.currency_aed_id.write({'active': True}) cls.env['res.currency.rate'].search([]).unlink() cls.env['res.currency.rate'].create({'currency_id': cls.currency_aed_id.id, 'rate': 0.198117095128, 'name': '2022-03-15'}) # Allow to see the full result of AssertionError. cls.maxDiff = None cls.company_data['company'].write({ 'country_id': cls.env.ref('base.eg').id, 'l10n_eg_client_identifier': 'ahuh1pojnbakKK', 'l10n_eg_client_secret': '1ashiqwhejmasn197', 'vat': 'EG1103143170L', }) # ==== Business ==== cls.partner_a.write({ 'vat': 'BE0477472701', 'country_id': cls.env.ref('base.eg').id, 'city': 'Iswan', 'state_id': cls.env.ref('base.state_eg_c').id, 'l10n_eg_building_no': '12', 'street': '12th dec. street', 'is_company': True, }) cls.partner_b.write({ 'vat': 'ESF35999705', 'country_id': cls.env.ref('base.us').id, 'city': 'New York City', 'state_id': cls.env.ref('base.state_us_27').id, 'l10n_eg_building_no': '12', 'street': '5th avenue street', 'is_company': True, }) cls.partner_c = cls.env['res.partner'].create({ 'name': 'عميل 1', 'vat': 'EG11231212', 'country_id': cls.env.ref('base.eg').id, 'city': 'Iswan', 'state_id': cls.env.ref('base.state_eg_c').id, 'l10n_eg_building_no': '12', 'street': '12th dec. street', 'is_company': True, }) cls.product_a.write({'barcode': '1KGS1TEST', }) cls.product_b.write({ 'barcode': 'EG-EGS-TEST', 'uom_id': cls.env.ref('uom.product_uom_cm').id, }) cls.company_branch = cls.env['res.partner'].create({ 'name': 'branch partner', 'vat': '918KKL1', 'country_id': cls.env.ref('base.eg').id, 'city': 'Iswan', 'state_id': cls.env.ref('base.state_eg_c').id, 'l10n_eg_building_no': '10', 'street': '12th dec. street', 'is_company': True, }) cls.company_data['default_journal_sale'].write({ 'l10n_eg_branch_id': cls.company_branch.id, 'l10n_eg_branch_identifier': '0', 'l10n_eg_activity_type_id': cls.env.ref('l10n_eg_edi_eta.l10n_eg_activity_type_8121').id, }) @classmethod def _get_tax_by_xml_id(cls, trailing_xml_id): return cls.env.ref(f'l10n_es.{cls.env.company.id}_account_tax_template_{trailing_xml_id}') @classmethod def create_invoice(cls, **kwargs): return (cls.env['account.move'] .with_context(edi_test_mode=True) .create({ 'move_type': 'out_invoice', 'partner_id': cls.partner_a.id, 'invoice_date': '2022-03-15', 'date': '2022-03-15', **kwargs, 'invoice_line_ids': [Command.create({**line_vals, }) for line_vals in kwargs.get('invoice_line_ids', [])] }))
39.673267
4,007
6,536
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import json from odoo import api, models, fields, _ from odoo.exceptions import ValidationError, UserError from odoo.tools.sql import column_exists, create_column from datetime import datetime _logger = logging.getLogger(__name__) class AccountMove(models.Model): _inherit = 'account.move' l10n_eg_long_id = fields.Char(string='ETA Long ID', compute='_compute_eta_long_id') l10n_eg_qr_code = fields.Char(string='ETA QR Code', compute='_compute_eta_qr_code_str') l10n_eg_submission_number = fields.Char(string='Submission ID', compute='_compute_eta_response_data', store=True, copy=False) l10n_eg_uuid = fields.Char(string='Document UUID', compute='_compute_eta_response_data', store=True, copy=False) l10n_eg_eta_json_doc_id = fields.Many2one('ir.attachment', copy=False) l10n_eg_signing_time = fields.Datetime('Signing Time', copy=False) l10n_eg_is_signed = fields.Boolean(copy=False) def _auto_init(self): if not column_exists(self.env.cr, "account_move", "l10n_eg_uuid"): create_column(self.env.cr, "account_move", "l10n_eg_uuid", "VARCHAR") # Since l10n_eg_uuid columns does not exist we can assume l10n_eg_submission_number doesn't exist either create_column(self.env.cr, "account_move", "l10n_eg_submission_number", "VARCHAR") return super()._auto_init() @api.depends('l10n_eg_eta_json_doc_id.raw') def _compute_eta_long_id(self): for rec in self: response_data = rec.l10n_eg_eta_json_doc_id and json.loads(rec.l10n_eg_eta_json_doc_id.raw).get('response') if response_data: rec.l10n_eg_long_id = response_data.get('l10n_eg_long_id') else: rec.l10n_eg_long_id = False @api.depends('invoice_date', 'l10n_eg_uuid', 'l10n_eg_long_id') def _compute_eta_qr_code_str(self): for move in self: if move.invoice_date and move.l10n_eg_uuid and move.l10n_eg_long_id: is_prod = move.company_id.l10n_eg_production_env base_url = self.env['account.edi.format']._l10n_eg_get_eta_qr_domain(production_enviroment=is_prod) qr_code_str = '%s/documents/%s/share/%s' % (base_url, move.l10n_eg_uuid, move.l10n_eg_long_id) move.l10n_eg_qr_code = qr_code_str else: move.l10n_eg_qr_code = '' @api.depends('l10n_eg_eta_json_doc_id.raw') def _compute_eta_response_data(self): for rec in self: response_data = rec.l10n_eg_eta_json_doc_id and json.loads(rec.l10n_eg_eta_json_doc_id.raw).get('response') if response_data: rec.l10n_eg_uuid = response_data.get('l10n_eg_uuid') rec.l10n_eg_submission_number = response_data.get('l10n_eg_submission_number') rec.l10n_eg_long_id = response_data.get('l10n_eg_long_id') else: rec.l10n_eg_uuid = False rec.l10n_eg_submission_number = False rec.l10n_eg_long_id = False def button_draft(self): self.l10n_eg_eta_json_doc_id = False self.l10n_eg_is_signed = False return super().button_draft() def action_post_sign_invoices(self): # only sign invoices that are confirmed and not yet sent to the ETA. invoices = self.filtered(lambda r: r.country_code == 'EG' and r.state == 'posted' and not r.l10n_eg_submission_number and r.edi_document_ids.filtered(lambda e: e.edi_format_id.code == 'eg_eta')) if not invoices: return company_ids = invoices.mapped('company_id') # since the middleware accepts only one drive at a time, we have to limit signing to one company at a time if len(company_ids) > 1: raise UserError(_('Please only sign invoices from one company at a time')) company_id = company_ids[0] drive_id = self.env['l10n_eg_edi.thumb.drive'].search([('user_id', '=', self.env.user.id), ('company_id', '=', company_id.id)]) if not drive_id: raise ValidationError(_('Please setup a personal drive for company %s', company_id.name)) if not drive_id.certificate: raise ValidationError(_('Please setup the certificate on the thumb drive menu')) self.write({'l10n_eg_signing_time': datetime.utcnow()}) for invoice in invoices: eta_invoice = self.env['account.edi.format']._l10n_eg_eta_prepare_eta_invoice(invoice) attachment = self.env['ir.attachment'].create({ 'name': _('ETA_INVOICE_DOC_%s', invoice.name), 'res_id': invoice.id, 'res_model': invoice._name, 'type': 'binary', 'raw': json.dumps(dict(request=eta_invoice)), 'mimetype': 'application/json', 'description': _('Egyptian Tax authority JSON invoice generated for %s.', invoice.name), }) invoice.l10n_eg_eta_json_doc_id = attachment.id return drive_id.action_sign_invoices(self) def action_get_eta_invoice_pdf(self): """ This is a pdf with the structure from the government. While we can use our own format, some clients appreciate this to verify that all the data is there in case of confusion.""" self.ensure_one() eta_invoice_pdf = self.env['account.edi.format']._l10n_eg_get_eta_invoice_pdf(self) if eta_invoice_pdf.get('error', False): _logger.warning('PDF Content Error: %s.', eta_invoice_pdf.get('error')) return self.with_context(no_new_invoice=True).message_post(body=_('ETA invoice has been received'), attachments=[('ETA invoice of %s.pdf' % self.name, eta_invoice_pdf.get('data'))]) def _l10n_eg_edi_exchange_currency_rate(self): """ Calculate the rate based on the balance and amount_currency, so we recuperate the one used at the time""" self.ensure_one() from_currency = self.currency_id to_currency = self.company_id.currency_id return abs(self.invoice_line_ids[0].balance / self.invoice_line_ids[0].amount_currency) if from_currency != to_currency and self.invoice_line_ids else 1.0
52.709677
6,536
21,240
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import logging import requests from werkzeug.urls import url_quote from base64 import b64encode from urllib3.util.ssl_ import create_urllib3_context from odoo import api, models, _ from odoo.tools.float_utils import json_float_round _logger = logging.getLogger(__name__) ETA_DOMAINS = { 'preproduction': 'https://api.preprod.invoicing.eta.gov.eg', 'production': 'https://api.invoicing.eta.gov.eg', 'invoice.preproduction': 'https://preprod.invoicing.eta.gov.eg/', 'invoice.production': 'https://invoicing.eta.gov.eg', 'token.preproduction': 'https://id.preprod.eta.gov.eg', 'token.production': 'https://id.eta.gov.eg', } class L10nEgHTTPAdapter(requests.adapters.HTTPAdapter): """ An adapter to allow unsafe legacy renegotiation necessary to connect to gravely outdated ETA production servers. """ def init_poolmanager(self, *args, **kwargs): # This is not defined before Python 3.12 # cfr. https://github.com/python/cpython/pull/93927 # Origin: https://github.com/openssl/openssl/commit/ef51b4b9 OP_LEGACY_SERVER_CONNECT = 0x04 context = create_urllib3_context(options=OP_LEGACY_SERVER_CONNECT) kwargs["ssl_context"] = context return super().init_poolmanager(*args, **kwargs) class AccountEdiFormat(models.Model): _inherit = 'account.edi.format' @api.model def _l10n_eg_get_eta_qr_domain(self, production_enviroment=False): return production_enviroment and ETA_DOMAINS['invoice.production'] or ETA_DOMAINS['invoice.preproduction'] @api.model def _l10n_eg_get_eta_api_domain(self, production_enviroment=False): return production_enviroment and ETA_DOMAINS['production'] or ETA_DOMAINS['preproduction'] @api.model def _l10n_eg_get_eta_token_domain(self, production_enviroment=False): return production_enviroment and ETA_DOMAINS['token.production'] or ETA_DOMAINS['token.preproduction'] @api.model def _l10n_eg_eta_connect_to_server(self, request_data, request_url, method, is_access_token_req=False, production_enviroment=False): api_domain = is_access_token_req and self._l10n_eg_get_eta_token_domain(production_enviroment) or self._l10n_eg_get_eta_api_domain(production_enviroment) request_url = api_domain + request_url try: session = requests.session() session.mount("https://", L10nEgHTTPAdapter()) request_response = session.request(method, request_url, data=request_data.get('body'), headers=request_data.get('header'), timeout=(5, 10)) except (ValueError, requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.Timeout, requests.exceptions.HTTPError) as ex: return { 'error': str(ex), 'blocking_level': 'warning' } if not request_response.ok: response_data = request_response.json() if isinstance(response_data, dict) and response_data.get('error'): return { 'error': response_data.get('error', _('Unknown error')), 'blocking_level': 'error' } return { 'error': request_response.reason, 'blocking_level': 'error' } return {'response': request_response} @api.model def _l10n_eg_edi_round(self, amount, precision_digits=5): """ This method is call for rounding. If anything is wrong with rounding then we quick fix in method """ return json_float_round(amount, precision_digits) @api.model def _l10n_eg_edi_post_invoice_web_service(self, invoice): access_data = self._l10n_eg_eta_get_access_token(invoice) if access_data.get('error'): return access_data invoice_json = json.loads(invoice.l10n_eg_eta_json_doc_id.raw) request_url = '/api/v1.0/documentsubmissions' request_data = { 'body': json.dumps({'documents': [invoice_json['request']]}, ensure_ascii=False, indent=4).encode('utf-8'), 'header': {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % access_data.get('access_token')} } response_data = self._l10n_eg_eta_connect_to_server(request_data, request_url, 'POST', production_enviroment=invoice.company_id.l10n_eg_production_env) if response_data.get('error'): return response_data response_data = response_data.get('response').json() if response_data.get('rejectedDocuments', False) and isinstance(response_data.get('rejectedDocuments'), list): return { 'error': str(response_data.get('rejectedDocuments')[0].get('error')), 'blocking_level': 'error' } if response_data.get('submissionId') is not None and response_data.get('acceptedDocuments'): invoice_json['response'] = { 'l10n_eg_uuid': response_data['acceptedDocuments'][0].get('uuid'), 'l10n_eg_long_id': response_data['acceptedDocuments'][0].get('longId'), 'l10n_eg_internal_id': response_data['acceptedDocuments'][0].get('internalId'), 'l10n_eg_hash_key': response_data['acceptedDocuments'][0].get('hashKey'), 'l10n_eg_submission_number': response_data['submissionId'], } invoice.l10n_eg_eta_json_doc_id.raw = json.dumps(invoice_json) return {'attachment': invoice.l10n_eg_eta_json_doc_id} return { 'error': _('an Unknown error has occurred'), 'blocking_level': 'warning' } @api.model def _cancel_invoice_edi_eta(self, invoice): access_data = self._l10n_eg_eta_get_access_token(invoice) if access_data.get('error'): return access_data request_url = f'/api/v1/documents/state/{url_quote(invoice.l10n_eg_uuid)}/state' request_data = { 'body': json.dumps({'status': 'cancelled', 'reason': 'Cancelled'}), 'header': {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % access_data.get('access_token')} } response_data = self._l10n_eg_eta_connect_to_server(request_data, request_url, 'PUT', production_enviroment=invoice.company_id.l10n_eg_production_env) if response_data.get('error'): return response_data if response_data.get('response').ok: return {'success': True} return { 'error': _('an Unknown error has occurred'), 'blocking_level': 'warning' } @api.model def _l10n_eg_get_einvoice_status(self, invoice): access_data = self._l10n_eg_eta_get_access_token(invoice) if access_data.get('error'): return access_data request_url = f'/api/v1.0/documentsubmissions/{url_quote(invoice.l10n_eg_submission_number)}' request_data = { 'body': None, 'header': {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % access_data.get('access_token')} } response_data = self._l10n_eg_eta_connect_to_server(request_data, request_url, 'GET', production_enviroment=invoice.company_id.l10n_eg_production_env) if response_data.get('error'): return response_data response_data = response_data.get('response').json() document_summary = [doc for doc in response_data.get('documentSummary', []) if doc.get('uuid') == invoice.l10n_eg_uuid] return_dict = { 'Invalid': { 'error': _("This invoice has been marked as invalid by the ETA. Please check the ETA website for more information"), 'blocking_level': 'error' }, 'Submitted': { 'error': _("This invoice has been sent to the ETA, but we are still awaiting validation"), 'blocking_level': 'info' }, 'Valid': {'success': True}, 'Cancelled': {'error': _('Document Canceled'), 'blocking_level': 'error'}, } if document_summary and return_dict.get(document_summary[0].get('status')): return return_dict.get(document_summary[0]['status']) return {'error': _('an Unknown error has occured'), 'blocking_level': 'warning'} def _l10n_eg_eta_get_access_token(self, invoice): user = invoice.company_id.sudo().l10n_eg_client_identifier secret = invoice.company_id.sudo().l10n_eg_client_secret access = '%s:%s' % (user, secret) user_and_pass = b64encode(access.encode()).decode() request_url = '/connect/token' request_data = {'body': {'grant_type': 'client_credentials'}, 'header': {'Authorization': f'Basic {user_and_pass}'}} response_data = self._l10n_eg_eta_connect_to_server(request_data, request_url, 'POST', is_access_token_req=True, production_enviroment=invoice.company_id.l10n_eg_production_env) if response_data.get('error'): return response_data return {'access_token' : response_data.get('response').json().get('access_token')} @api.model def _l10n_eg_get_eta_invoice_pdf(self, invoice): access_data = self._l10n_eg_eta_get_access_token(invoice) if access_data.get('error'): return access_data request_url = f'/api/v1.0/documents/{url_quote(invoice.l10n_eg_uuid)}/pdf' request_data = {'body': None, 'header': {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % access_data.get('access_token')}} response_data = self._l10n_eg_eta_connect_to_server(request_data, request_url, 'GET', production_enviroment=invoice.company_id.l10n_eg_production_env) if response_data.get('error'): return response_data response_data = response_data.get('response') _logger.warning('PDF Function Response %s.', response_data) if response_data.ok: return {'data': response_data.content} else: return {'error': _('PDF Document is not available')} @api.model def _l10n_eg_validate_info_address(self, partner_id, issuer=False, invoice=False): fields = ["country_id", "state_id", "city", "street", "l10n_eg_building_no"] if (invoice and invoice.amount_total >= invoice.company_id.l10n_eg_invoicing_threshold) or self._l10n_eg_get_partner_tax_type(partner_id, issuer) != 'P': fields.append('vat') return all(partner_id[field] for field in fields) @api.model def _l10n_eg_eta_prepare_eta_invoice(self, invoice): def group_tax_retention(tax_values): return {'l10n_eg_eta_code': tax_values['tax_id'].l10n_eg_eta_code.split('_')[0]} date_string = invoice.invoice_date.strftime('%Y-%m-%dT%H:%M:%SZ') grouped_taxes = invoice._prepare_edi_tax_details(grouping_key_generator=group_tax_retention) invoice_line_data, totals = self._l10n_eg_eta_prepare_invoice_lines_data(invoice, grouped_taxes['invoice_line_tax_details']) eta_invoice = { 'issuer': self._l10n_eg_eta_prepare_address_data(invoice.journal_id.l10n_eg_branch_id, invoice, issuer=True,), 'receiver': self._l10n_eg_eta_prepare_address_data(invoice.partner_id, invoice), 'documentType': 'i' if invoice.move_type == 'out_invoice' else 'c' if invoice.move_type == 'out_refund' else 'd' if invoice.move_type == 'in_refund' else '', 'documentTypeVersion': '1.0', 'dateTimeIssued': date_string, 'taxpayerActivityCode': invoice.journal_id.l10n_eg_activity_type_id.code, 'internalID': invoice.name, } eta_invoice.update({ 'invoiceLines': invoice_line_data, 'taxTotals': [{ 'taxType': tax['l10n_eg_eta_code'].split('_')[0].upper(), 'amount': self._l10n_eg_edi_round(abs(tax['tax_amount'])), } for tax in grouped_taxes['tax_details'].values()], 'totalDiscountAmount': self._l10n_eg_edi_round(totals['discount_total']), 'totalSalesAmount': self._l10n_eg_edi_round(totals['total_price_subtotal_before_discount']), 'netAmount': self._l10n_eg_edi_round(abs(invoice.amount_untaxed_signed)), 'totalAmount': self._l10n_eg_edi_round(abs(invoice.amount_total_signed)), 'extraDiscountAmount': 0.0, 'totalItemsDiscountAmount': 0.0, }) if invoice.ref: eta_invoice['purchaseOrderReference'] = invoice.ref if invoice.invoice_origin: eta_invoice['salesOrderReference'] = invoice.invoice_origin return eta_invoice @api.model def _l10n_eg_eta_prepare_invoice_lines_data(self, invoice, tax_data): lines = [] totals = { 'discount_total': 0.0, 'total_price_subtotal_before_discount' : 0.0, } for line in invoice.invoice_line_ids.filtered(lambda x: not x.display_type): line_tax_details = tax_data.get(line, {}) price_unit = self._l10n_eg_edi_round(abs((line.balance / line.quantity) / (1 - (line.discount / 100.0)))) if line.quantity and line.discount != 100.0 else line.price_unit price_subtotal_before_discount = self._l10n_eg_edi_round(abs(line.balance / (1 - (line.discount / 100)))) if line.discount != 100.0 else price_unit * line.quantity discount_amount = self._l10n_eg_edi_round(price_subtotal_before_discount - abs(line.balance)) item_code = line.product_id.l10n_eg_eta_code or line.product_id.barcode lines.append({ 'description': line.name, 'itemType': item_code.startswith('EG') and 'EGS' or 'GS1', 'itemCode': item_code, 'unitType': line.product_uom_id.l10n_eg_unit_code_id.code, 'quantity': line.quantity, 'internalCode': line.product_id.default_code or '', 'valueDifference': 0.0, 'totalTaxableFees': 0.0, 'itemsDiscount': 0.0, 'unitValue': { 'currencySold': invoice.currency_id.name, 'amountEGP': price_unit, }, 'discount': { 'rate': line.discount, 'amount': discount_amount, }, 'taxableItems': [ { 'taxType': tax['tax_id'].l10n_eg_eta_code.split('_')[0].upper().upper(), 'amount': self._l10n_eg_edi_round(abs(tax['tax_amount'])), 'subType': tax['tax_id'].l10n_eg_eta_code.split('_')[1].upper(), 'rate': abs(tax['tax_id'].amount), } for tax_details in line_tax_details.get('tax_details', {}).values() for tax in tax_details.get('group_tax_details') ], 'salesTotal': price_subtotal_before_discount, 'netTotal': self._l10n_eg_edi_round(abs(line.balance)), 'total': self._l10n_eg_edi_round(abs(line.balance + line_tax_details.get('tax_amount', 0.0))), }) totals['discount_total'] += discount_amount totals['total_price_subtotal_before_discount'] += price_subtotal_before_discount if invoice.currency_id != self.env.ref('base.EGP'): lines[-1]['unitValue']['currencyExchangeRate'] = self._l10n_eg_edi_round(invoice._l10n_eg_edi_exchange_currency_rate()) lines[-1]['unitValue']['amountSold'] = line.price_unit return lines, totals @api.model def _l10n_eg_get_partner_tax_type(self, partner_id, issuer=False): if issuer: return 'B' elif partner_id.commercial_partner_id.country_code == 'EG': return 'B' if partner_id.commercial_partner_id.is_company else 'P' else: return 'F' @api.model def _l10n_eg_eta_prepare_address_data(self, partner, invoice, issuer=False): address = { 'address': { 'country': partner.country_id.code, 'governate': partner.state_id.name or '', 'regionCity': partner.city or '', 'street': partner.street or '', 'buildingNumber': partner.l10n_eg_building_no or '', 'postalCode': partner.zip or '', }, 'name': partner.name, } if issuer: address['address']['branchID'] = invoice.journal_id.l10n_eg_branch_identifier or '' individual_type = self._l10n_eg_get_partner_tax_type(partner, issuer) address['type'] = individual_type or '' if invoice.amount_total >= invoice.company_id.l10n_eg_invoicing_threshold or individual_type != 'P': address['id'] = partner.vat or '' return address # ------------------------------------------------------------------------- # EDI OVERRIDDEN METHODS # ------------------------------------------------------------------------- def _needs_web_services(self): return self.code == 'eg_eta' or super()._needs_web_services() def _check_move_configuration(self, invoice): errors = super()._check_move_configuration(invoice) if self.code != 'eg_eta': return errors if invoice.journal_id.l10n_eg_branch_id.vat == invoice.partner_id.vat: errors.append(_("You cannot issue an invoice to a partner with the same VAT number as the branch.")) if not self._l10n_eg_get_eta_token_domain(invoice.company_id.l10n_eg_production_env): errors.append(_("Please configure the token domain from the system parameters")) if not self._l10n_eg_get_eta_api_domain(invoice.company_id.l10n_eg_production_env): errors.append(_("Please configure the API domain from the system parameters")) if not all([invoice.journal_id.l10n_eg_branch_id, invoice.journal_id.l10n_eg_branch_identifier, invoice.journal_id.l10n_eg_activity_type_id]): errors.append(_("Please set the all the ETA information on the invoice's journal")) if not self._l10n_eg_validate_info_address(invoice.journal_id.l10n_eg_branch_id): errors.append(_("Please add all the required fields in the branch details")) if not self._l10n_eg_validate_info_address(invoice.partner_id, invoice=invoice): errors.append(_("Please add all the required fields in the customer details")) if not all(aml.product_uom_id.l10n_eg_unit_code_id.code for aml in invoice.invoice_line_ids.filtered(lambda x: not x.display_type)): errors.append(_("Please make sure the invoice lines UoM codes are all set up correctly")) if not all(tax.l10n_eg_eta_code for tax in invoice.invoice_line_ids.filtered(lambda x: not x.display_type).tax_ids): errors.append(_("Please make sure the invoice lines taxes all have the correct ETA tax code")) if not all(aml.product_id.l10n_eg_eta_code or aml.product_id.barcode for aml in invoice.invoice_line_ids.filtered(lambda x: not x.display_type)): errors.append(_("Please make sure the EGS/GS1 Barcode is set correctly on all products")) return errors def _post_invoice_edi(self, invoices): if self.code != 'eg_eta': return super()._post_invoice_edi(invoices) invoice = invoices # Batching is disabled for this EDI. # In case we have already sent it, but have not got a final answer yet. if invoice.l10n_eg_submission_number: return {invoice: self._l10n_eg_get_einvoice_status(invoice)} if not invoice.l10n_eg_eta_json_doc_id: return { invoice: { 'error': _("An error occured in created the ETA invoice, please retry signing"), 'blocking_level': 'error' } } invoice_json = json.loads(invoice.l10n_eg_eta_json_doc_id.raw)['request'] if not invoice_json.get('signatures'): return { invoice: { 'error': _("Please make sure the invoice is signed"), 'blocking_level': 'error' } } return {invoice: self._l10n_eg_edi_post_invoice_web_service(invoice)} def _cancel_invoice_edi(self, invoices): if self.code != 'eg_eta': return super()._cancel_invoice_edi(invoices) invoice = invoices return {invoice: self._cancel_invoice_edi_eta(invoice)} def _get_invoice_edi_content(self, move): if self.code != 'eg_eta': return super()._get_invoice_edi_content(move) return json.dumps(self._l10n_eg_eta_prepare_eta_invoice(move)).encode() def _is_compatible_with_journal(self, journal): # OVERRIDE if self.code != 'eg_eta': return super()._is_compatible_with_journal(journal) return journal.country_code == 'EG' and journal.type == 'sale'
52.186732
21,240
7,329
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import hashlib import json import pytz from asn1crypto import cms, core, x509, algos, tsp from odoo import models, fields, _ from odoo.exceptions import ValidationError class EtaThumbDrive(models.Model): _name = 'l10n_eg_edi.thumb.drive' _description = 'Thumb drive used to sign invoices in Egypt' user_id = fields.Many2one('res.users', required=True, default=lambda self: self.env.user) company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company) certificate = fields.Binary('ETA Certificate') pin = fields.Char('ETA USB Pin', required=True) access_token = fields.Char(required=True) _sql_constraints = [ ('user_drive_uniq', 'unique (user_id, company_id)', 'You can only have one thumb drive per user per company!'), ] def action_sign_invoices(self, invoice_ids): self.ensure_one() sign_host = self._get_host() to_sign_dict = dict() for invoice_id in invoice_ids: eta_invoice = json.loads(invoice_id.l10n_eg_eta_json_doc_id.raw)['request'] signed_attrs = self._generate_signed_attrs(eta_invoice, invoice_id.l10n_eg_signing_time) to_sign_dict[invoice_id.id] = base64.b64encode(signed_attrs.dump()).decode() return { 'type': 'ir.actions.client', 'tag': 'action_post_sign_invoice', 'params': { 'sign_host': sign_host, 'access_token': self.access_token, 'pin': self.pin, 'drive_id': self.id, 'invoices': json.dumps(to_sign_dict) } } def action_set_certificate_from_usb(self): self.ensure_one() sign_host = self._get_host() return { 'type': 'ir.actions.client', 'tag': 'action_get_drive_certificate', 'params': { 'sign_host': sign_host, 'access_token': self.access_token, 'pin': self.pin, 'drive_id': self.id } } def set_certificate(self, certificate): """ This is called from the browser to set the certificate""" self.ensure_one() self.certificate = certificate.encode() return True def set_signature_data(self, invoices): """ This is called from the browser with the signed data from the local server """ invoices = json.loads(invoices) for key, value in invoices.items(): invoice_id = self.env['account.move'].browse(int(key)) eta_invoice_json = json.loads(invoice_id.l10n_eg_eta_json_doc_id.raw) cades_bes = self._generate_cades_bes_signature(eta_invoice_json['request'], invoice_id.l10n_eg_signing_time, base64.b64decode(value)) signature = base64.b64encode(cades_bes.dump()).decode() eta_invoice_json['request']['signatures'] = [{'signatureType': 'I', 'value': signature}] invoice_id.l10n_eg_eta_json_doc_id.raw = json.dumps(eta_invoice_json) invoice_id.l10n_eg_is_signed = True return True def _get_host(self): # It should be on the loopback address or with a fully valid https host # in order to be an exception to the mixed-content restrictions sign_host = self.env['ir.config_parameter'].sudo().get_param('l10n_eg_eta.sign.host', 'http://localhost:8069') if not sign_host: raise ValidationError(_('Please define the host of sign tool.')) return sign_host def _serialize_for_signing(self, eta_inv): if not isinstance(eta_inv, dict): return json.dumps(str(eta_inv), ensure_ascii=False) canonical_str = [] for key, value in eta_inv.items(): if not isinstance(value, list): canonical_str.append(json.dumps(key, ensure_ascii=False).upper()) canonical_str.append(self._serialize_for_signing(value)) else: canonical_str.append(json.dumps(key, ensure_ascii=False).upper()) for elem in value: canonical_str.append(json.dumps(key, ensure_ascii=False).upper()) canonical_str.append(self._serialize_for_signing(elem)) return ''.join(canonical_str) def _generate_signed_attrs(self, eta_invoice, signing_time): cert = x509.Certificate.load(base64.b64decode(self.certificate)) data = hashlib.sha256(self._serialize_for_signing(eta_invoice).encode()).digest() return cms.CMSAttributes([ cms.CMSAttribute({ 'type': cms.CMSAttributeType('content_type'), 'values': ('digested_data',), }), cms.CMSAttribute({ 'type': cms.CMSAttributeType('message_digest'), 'values': (data,), }), cms.CMSAttribute({ 'type': tsp.CMSAttributeType('signing_certificate_v2'), 'values': ({ 'certs': (tsp.ESSCertIDv2({ 'hash_algorithm': algos.DigestAlgorithm({'algorithm': 'sha256'}), 'cert_hash': hashlib.sha256(cert.dump()).digest() }),) },), }), cms.CMSAttribute({ 'type': cms.CMSAttributeType('signing_time'), 'values': ( cms.Time({'utc_time': core.UTCTime(signing_time.replace(tzinfo=pytz.UTC))}),) }), ]) def _generate_signer_info(self, eta_invoice, signing_time, signature=False): cert = x509.Certificate.load(base64.b64decode(self.certificate)) signer_info = { 'version': 'v1', 'sid': cms.SignerIdentifier({ 'issuer_and_serial_number': cms.IssuerAndSerialNumber({ 'issuer': cert.issuer, 'serial_number': cert.serial_number, }), }), 'digest_algorithm': algos.DigestAlgorithm({'algorithm': 'sha256'}), 'signature_algorithm': algos.SignedDigestAlgorithm({ 'algorithm': 'sha256_rsa' }), 'signed_attrs': self._generate_signed_attrs(eta_invoice, signing_time) } if signature: signer_info['signature'] = signature return signer_info def _generate_cades_bes_signature(self, eta_invoice, signing_time, signature): cert = x509.Certificate.load(base64.b64decode(self.certificate)) signed_data = { 'version': 'v3', 'digest_algorithms': cms.DigestAlgorithms(( algos.DigestAlgorithm({'algorithm': 'sha256'}), )), 'encap_content_info': { 'content_type': 'digested_data', }, 'certificates': [cert], 'signer_infos': [ self._generate_signer_info(eta_invoice, signing_time, signature), ], } return cms.ContentInfo({'content_type': cms.ContentType('signed_data'), 'content': cms.SignedData(signed_data),})
41.88
7,329
944
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class AccountJournal(models.Model): _inherit = 'account.journal' l10n_eg_branch_id = fields.Many2one('res.partner', string='Branch', copy=False, help="Address of the subdivision of the company. You can just put the " "company partner if this is used for the main branch.") l10n_eg_activity_type_id = fields.Many2one('l10n_eg_edi.activity.type', 'ETA Activity Code', copy=False, help='This is the activity type of the branch according to Egyptian Tax Authority') l10n_eg_branch_identifier = fields.Char('ETA Branch ID', copy=False, help="This number can be found on the taxpayer profile on the eInvoicing portal. ")
55.529412
944
2,113
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" l10n_eg_eta_code = fields.Char('ETA Item code', compute='_compute_l10n_eg_eta_code', inverse='_set_l10n_eg_eta_code', help="This can be an EGS or GS1 product code, which is needed for the e-invoice. " "The best practice however is to use that code also as barcode and in that case, " "you should put it in the Barcode field instead and leave this field empty.") @api.depends('product_variant_ids.l10n_eg_eta_code') def _compute_l10n_eg_eta_code(self): self.l10n_eg_eta_code = False for template in self: if len(template.product_variant_ids) == 1: template.l10n_eg_eta_code = template.product_variant_ids.l10n_eg_eta_code def _set_l10n_eg_eta_code(self): if len(self.product_variant_ids) == 1: self.product_variant_ids.l10n_eg_eta_code = self.l10n_eg_eta_code @api.model_create_multi def create(self, vals_list): templates = super().create(vals_list) for template, vals in zip(templates, vals_list): related_vals = {} if vals.get('l10n_eg_eta_code'): related_vals['l10n_eg_eta_code'] = vals['l10n_eg_eta_code'] if related_vals: template.write(related_vals) return templates class ProductProduct(models.Model): _inherit = "product.product" l10n_eg_eta_code = fields.Char('ETA Code', copy=False, help="This can be an EGS or GS1 product code, which is needed for the e-invoice. " "The best practice however is to use that code also as barcode and in that case, " "you should put it in the Barcode field instead and leave this field empty. ")
44.020833
2,113
721
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class ResCompany(models.Model): _inherit = 'res.company' l10n_eg_client_identifier = fields.Char('ETA Client ID', groups="base.group_erp_manager") l10n_eg_client_secret = fields.Char('ETA Secret', groups="base.group_erp_manager") l10n_eg_production_env = fields.Boolean('In Production Environment') l10n_eg_invoicing_threshold = fields.Float('Invoicing Threshold', default=0.0, help="Threshold at which you are required to give the VAT number " "of the customer. ")
45.0625
721
605
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class UomCode(models.Model): _name = 'l10n_eg_edi.uom.code' _description = 'ETA code for the unit of measures' name = fields.Char(required=True, translate=True) code = fields.Char(required=True) class UomUom(models.Model): _inherit = 'uom.uom' l10n_eg_unit_code_id = fields.Many2one('l10n_eg_edi.uom.code', string='ETA Unit Code', help='This is the type of unit according to egyptian tax authority')
31.842105
605
1,022
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api, _ class ResCurrencyRate(models.Model): _inherit = 'res.currency.rate' @api.onchange('company_rate') def _onchange_rate_warning(self): # We send the ETA a rate that is 5 decimal accuracy, so to ensure consistency, Odoo should also operate with 5 decimal accuracy rate if self.company_id.account_fiscal_country_id.code == 'EG' and self.inverse_company_rate != round(self.inverse_company_rate, 5): return { 'warning': { 'title': _("Warning for %s", self.currency_id.name), 'message': _( "Please make sure that the EGP per unit is within 5 decimal accuracy.\n" "Higher decimal accuracy might lead to inconsistency with the ETA invoicing portal!" ) } } return super()._onchange_rate_warning()
42.583333
1,022
810
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api from odoo.osv import expression class EtaActivityType(models.Model): _name = 'l10n_eg_edi.activity.type' _description = 'ETA code for activity type' name = fields.Char(required=True, translate=True) code = fields.Char(required=True) @api.model def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] if operator == 'ilike' and not(name or '').strip(): domain = [] else: domain = ['|', ('name', operator, name), ('code', operator, name)] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
35.217391
810
545
py
PYTHON
15.0
from odoo import models, fields class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' l10n_eg_client_identifier = fields.Char(related='company_id.l10n_eg_client_identifier', readonly=False) l10n_eg_client_secret = fields.Char(related='company_id.l10n_eg_client_secret', readonly=False) l10n_eg_production_env = fields.Boolean(related='company_id.l10n_eg_production_env', readonly=False) l10n_eg_invoicing_threshold = fields.Float(related='company_id.l10n_eg_invoicing_threshold', readonly=False)
60.555556
545
475
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class ResPartner(models.Model): _inherit = 'res.partner' l10n_eg_building_no = fields.Char('Building No.') @api.model def _commercial_fields(self): return super()._commercial_fields() + ['l10n_eg_building_no'] def _address_fields(self): return super()._address_fields() + ['l10n_eg_building_no']
26.388889
475
468
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "IAP / CRM", 'summary': """Bridge between IAP and CRM""", 'description': """Bridge between IAP and CRM""", 'category': 'Hidden/Tools', 'version': '1.0', 'depends': [ 'crm', 'iap_mail', ], 'application': False, 'installable': True, 'auto_install': True, 'data': [ ], 'license': 'LGPL-3', }
22.285714
468
287
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Lead(models.Model): _inherit = 'crm.lead' reveal_id = fields.Char(string='Reveal ID', help="Technical ID of reveal request done by IAP.")
28.7
287
667
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'City Addresses', 'summary': 'Add a many2one field city on addresses', 'sequence': '19', 'category': 'Hidden/Tools', 'complexity': 'easy', 'description': """ City Management in Addresses ============================ This module allows to enforce users to choose the city of a partner inside a given list instead of a free text field. """, 'data': [ 'security/ir.model.access.csv', 'views/res_city_view.xml', 'views/res_country_view.xml', ], 'depends': ['base'], 'license': 'LGPL-3', }
30.318182
667
1,194
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class City(models.Model): _name = 'res.city' _description = 'City' _order = 'name' name = fields.Char("Name", required=True, translate=True) zipcode = fields.Char("Zip") country_id = fields.Many2one('res.country', string='Country', required=True) state_id = fields.Many2one( 'res.country.state', 'State', domain="[('country_id', '=', country_id)]") def name_get(self): res = [] for city in self: name = city.name if not city.zipcode else '%s (%s)' % (city.name, city.zipcode) res.append((city.id, name)) return res @api.model def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None): args = list(args or []) # optimize out the default criterion of ``ilike ''`` that matches everything if not (name == '' and operator == 'ilike'): args += ['|', (self._rec_name, operator, name), ('zipcode', operator, name)] return self._search(args, limit=limit, access_rights_uid=name_get_uid)
38.516129
1,194
415
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Country(models.Model): _inherit = 'res.country' enforce_cities = fields.Boolean( string='Enforce Cities', help="Check this box to ensure every address created in that country has a 'City' chosen " "in the list of the country's cities.")
31.923077
415
4,084
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from odoo import api, models, fields from odoo.tools.translate import _ class Partner(models.Model): _inherit = 'res.partner' country_enforce_cities = fields.Boolean(related='country_id.enforce_cities', readonly=True) city_id = fields.Many2one('res.city', string='City of Address') @api.onchange('city_id') def _onchange_city_id(self): if self.city_id: self.city = self.city_id.name self.zip = self.city_id.zipcode self.state_id = self.city_id.state_id elif self._origin: self.city = False self.zip = False self.state_id = False @api.model def _address_fields(self): """Returns the list of address fields that are synced from the parent.""" return super(Partner, self)._address_fields() + ['city_id',] @api.model def _fields_view_get_address(self, arch): arch = super(Partner, self)._fields_view_get_address(arch) # render the partner address accordingly to address_view_id doc = etree.fromstring(arch) if doc.xpath("//field[@name='city_id']"): return arch replacement_xml = """ <div> <field name="country_enforce_cities" invisible="1"/> <field name="type" invisible="1"/> <field name='city' placeholder="%(placeholder)s" class="o_address_city" attrs="{ 'invisible': [('country_enforce_cities', '=', True), '|', ('city_id', '!=', False), ('city', 'in', ['', False ])], 'readonly': [('type', '=', 'contact')%(parent_condition)s] }"%(required)s /> <field name='city_id' placeholder="%(placeholder)s" string="%(placeholder)s" class="o_address_city" context="{'default_country_id': country_id, 'default_name': city, 'default_zipcode': zip, 'default_state_id': state_id}" domain="[('country_id', '=', country_id)]" attrs="{ 'invisible': [('country_enforce_cities', '=', False)], 'readonly': [('type', '=', 'contact')%(parent_condition)s] }" /> </div> """ replacement_data = { 'placeholder': _('City'), } def _arch_location(node): in_subview = False view_type = False parent = node.getparent() while parent is not None and (not view_type or not in_subview): if parent.tag == 'field': in_subview = True elif parent.tag in ['list', 'tree', 'kanban', 'form']: view_type = parent.tag parent = parent.getparent() return { 'view_type': view_type, 'in_subview': in_subview, } for city_node in doc.xpath("//field[@name='city']"): location = _arch_location(city_node) replacement_data['parent_condition'] = '' replacement_data['required'] = '' if location['view_type'] == 'form' or not location['in_subview']: replacement_data['parent_condition'] = ", ('parent_id', '!=', False)" if 'required' in city_node.attrib: existing_value = city_node.attrib.get('required') replacement_data['required'] = f' required="{existing_value}"' replacement_formatted = replacement_xml % replacement_data for replace_node in etree.fromstring(replacement_formatted).getchildren(): city_node.addprevious(replace_node) parent = city_node.getparent() parent.remove(city_node) arch = etree.tostring(doc, encoding='unicode') return arch
40.84
4,084
403
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Microsoft Users', 'category': 'Hidden/Tools', 'description': """ The module adds Microsoft user in res user. =========================================== """, 'depends': ['base_setup'], 'data': [ 'data/microsoft_account_data.xml', ], 'license': 'LGPL-3', }
25.1875
403
7,388
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime import json import logging import requests from werkzeug import urls from odoo import api, fields, models, _ _logger = logging.getLogger(__name__) TIMEOUT = 20 DEFAULT_MICROSOFT_AUTH_ENDPOINT = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' DEFAULT_MICROSOFT_TOKEN_ENDPOINT = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' RESOURCE_NOT_FOUND_STATUSES = (204, 404) class MicrosoftService(models.AbstractModel): _name = 'microsoft.service' _description = 'Microsoft Service' def _get_calendar_scope(self): return 'offline_access openid Calendars.ReadWrite' @api.model def _get_auth_endpoint(self): return self.env["ir.config_parameter"].sudo().get_param('microsoft_account.auth_endpoint', DEFAULT_MICROSOFT_AUTH_ENDPOINT) @api.model def _get_token_endpoint(self): return self.env["ir.config_parameter"].sudo().get_param('microsoft_account.token_endpoint', DEFAULT_MICROSOFT_TOKEN_ENDPOINT) @api.model def generate_refresh_token(self, service, authorization_code): """ Call Microsoft API to refresh the token, with the given authorization code :param service : the name of the microsoft service to actualize :param authorization_code : the code to exchange against the new refresh token :returns the new refresh token """ Parameters = self.env['ir.config_parameter'].sudo() client_id = Parameters.get_param('microsoft_%s_client_id' % service) client_secret = Parameters.get_param('microsoft_%s_client_secret' % service) redirect_uri = Parameters.get_param('microsoft_redirect_uri') scope = self._get_calendar_scope() # Get the Refresh Token From Microsoft And store it in ir.config_parameter headers = {"Content-type": "application/x-www-form-urlencoded"} data = { 'client_id': client_id, 'redirect_uri': redirect_uri, 'client_secret': client_secret, 'scope': scope, 'grant_type': "refresh_token" } try: req = requests.post(self._get_token_endpoint(), data=data, headers=headers, timeout=TIMEOUT) req.raise_for_status() content = req.json() except IOError: error_msg = _("Something went wrong during your token generation. Maybe your Authorization Code is invalid or already expired") raise self.env['res.config.settings'].get_config_warning(error_msg) return content.get('refresh_token') @api.model def _get_authorize_uri(self, from_url, service, scope): """ This method return the url needed to allow this instance of Odoo to access to the scope of gmail specified as parameters """ state = { 'd': self.env.cr.dbname, 's': service, 'f': from_url } get_param = self.env['ir.config_parameter'].sudo().get_param base_url = get_param('web.base.url', default='http://www.odoo.com?NoBaseUrl') client_id = get_param('microsoft_%s_client_id' % (service,), default=False) encoded_params = urls.url_encode({ 'response_type': 'code', 'client_id': client_id, 'state': json.dumps(state), 'scope': scope, 'redirect_uri': base_url + '/microsoft_account/authentication', 'prompt': 'consent', 'access_type': 'offline' }) return "%s?%s" % (self._get_auth_endpoint(), encoded_params) @api.model def _get_microsoft_tokens(self, authorize_code, service): """ Call Microsoft API to exchange authorization code against token, with POST request, to not be redirected. """ get_param = self.env['ir.config_parameter'].sudo().get_param base_url = get_param('web.base.url', default='http://www.odoo.com?NoBaseUrl') client_id = get_param('microsoft_%s_client_id' % (service,), default=False) client_secret = get_param('microsoft_%s_client_secret' % (service,), default=False) scope = self._get_calendar_scope() headers = {"content-type": "application/x-www-form-urlencoded"} data = { 'code': authorize_code, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'scope': scope, 'redirect_uri': base_url + '/microsoft_account/authentication' } try: dummy, response, dummy = self._do_request(self._get_token_endpoint(), params=data, headers=headers, method='POST', preuri='') access_token = response.get('access_token') refresh_token = response.get('refresh_token') ttl = response.get('expires_in') return access_token, refresh_token, ttl except requests.HTTPError: error_msg = _("Something went wrong during your token generation. Maybe your Authorization Code is invalid") raise self.env['res.config.settings'].get_config_warning(error_msg) @api.model def _do_request(self, uri, params=None, headers=None, method='POST', preuri="https://graph.microsoft.com", timeout=TIMEOUT): """ Execute the request to Microsoft API. Return a tuple ('HTTP_CODE', 'HTTP_RESPONSE') :param uri : the url to contact :param params : dict or already encoded parameters for the request to make :param headers : headers of request :param method : the method to use to make the request :param preuri : pre url to prepend to param uri. """ if params is None: params = {} if headers is None: headers = {} _logger.debug("Uri: %s - Type : %s - Headers: %s - Params : %s !" % (uri, method, headers, params)) ask_time = fields.Datetime.now() try: if method.upper() in ('GET', 'DELETE'): res = requests.request(method.lower(), preuri + uri, headers=headers, params=params, timeout=timeout) elif method.upper() in ('POST', 'PATCH', 'PUT'): res = requests.request(method.lower(), preuri + uri, data=params, headers=headers, timeout=timeout) else: raise Exception(_('Method not supported [%s] not in [GET, POST, PUT, PATCH or DELETE]!', method)) res.raise_for_status() status = res.status_code if int(status) in RESOURCE_NOT_FOUND_STATUSES: response = False else: # Some answers return empty content response = res.content and res.json() or {} try: ask_time = datetime.strptime(res.headers.get('date'), "%a, %d %b %Y %H:%M:%S %Z") except: pass except requests.HTTPError as error: if error.response.status_code in RESOURCE_NOT_FOUND_STATUSES: status = error.response.status_code response = "" else: _logger.exception("Bad microsoft request : %s !", error.response.content) raise error return (status, response, ask_time)
43.458824
7,388
877
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from odoo import api, fields, models, _ class User(models.Model): _inherit = 'res.users' microsoft_calendar_rtoken = fields.Char('Microsoft Refresh Token', copy=False, groups="base.group_system") microsoft_calendar_token = fields.Char('Microsoft User token', copy=False, groups="base.group_system") microsoft_calendar_token_validity = fields.Datetime('Microsoft Token Validity', copy=False) def _set_microsoft_auth_tokens(self, access_token, refresh_token, ttl): self.write({ 'microsoft_calendar_rtoken': refresh_token, 'microsoft_calendar_token': access_token, 'microsoft_calendar_token_validity': fields.Datetime.now() + timedelta(seconds=ttl) if ttl else False, })
39.863636
877
1,073
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json from odoo import http from odoo.http import request class MicrosoftAuth(http.Controller): @http.route('/microsoft_account/authentication', type='http', auth="public") def oauth2callback(self, **kw): """ This route/function is called by Microsoft when user Accept/Refuse the consent of Microsoft """ state = json.loads(kw['state']) dbname = state.get('d') service = state.get('s') url_return = state.get('f') if kw.get('code'): access_token, refresh_token, ttl = request.env['microsoft.service']._get_microsoft_tokens(kw['code'], service) request.env.user._set_microsoft_auth_tokens(access_token, refresh_token, ttl) return request.redirect(url_return) elif kw.get('error'): return request.redirect("%s%s%s" % (url_return, "?error=", kw['error'])) else: return request.redirect("%s%s" % (url_return, "?error=Unknown_error"))
39.740741
1,073
1,160
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'Slovak - Accounting', 'version': '1.0', 'author': '26HOUSE', 'website': 'http://www.26house.com', 'category': 'Accounting/Localizations/Account Charts', 'description': """ Slovakia accounting chart and localization: Chart of Accounts 2020, basic VAT rates + fiscal positions. Tento modul definuje: • Slovenskú účtovú osnovu za rok 2020 • Základné sadzby pre DPH z predaja a nákupu • Základné fiškálne pozície pre slovenskú legislatívu Pre viac informácií kontaktujte info@26house.com alebo navštívte https://www.26house.com. """, 'depends': [ 'account', 'base_iban', 'base_vat', ], 'data': [ 'data/l10n_sk_coa_data.xml', 'data/account.account.template.csv', 'data/account.group.template.csv', 'data/l10n_sk_coa_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_data.xml', 'data/account_fiscal_position_data.xml', 'data/account_chart_template_data.xml' ], 'demo': ['data/demo_company.xml'], 'license': 'LGPL-3', }
27.707317
1,136
2,413
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Employees', 'version': '1.1', 'category': 'Human Resources/Employees', 'sequence': 95, 'summary': 'Centralize employee information', 'description': "", 'website': 'https://www.odoo.com/app/employees', 'images': [ 'images/hr_department.jpeg', 'images/hr_employee.jpeg', 'images/hr_job_position.jpeg', 'static/src/img/default_image.png', ], 'depends': [ 'base_setup', 'mail', 'resource', 'web', ], 'data': [ 'security/hr_security.xml', 'security/ir.model.access.csv', 'wizard/hr_plan_wizard_views.xml', 'wizard/hr_departure_wizard_views.xml', 'views/hr_departure_reason_views.xml', 'views/hr_job_views.xml', 'views/hr_plan_views.xml', 'views/hr_employee_category_views.xml', 'views/hr_employee_public_views.xml', 'report/hr_employee_badge.xml', 'views/hr_employee_views.xml', 'views/hr_department_views.xml', 'views/hr_work_location_views.xml', 'views/hr_views.xml', 'views/res_config_settings_views.xml', 'views/mail_channel_views.xml', 'views/res_users.xml', 'views/res_partner_views.xml', 'data/hr_data.xml', ], 'demo': [ 'data/hr_demo.xml' ], 'installable': True, 'application': True, 'auto_install': False, 'assets': { 'mail.assets_discuss_public': [ 'hr/static/src/models/*/*.js', ], 'web.assets_backend': [ 'hr/static/src/scss/hr.scss', 'hr/static/src/js/chat_mixin.js', 'hr/static/src/js/hr_employee.js', 'hr/static/src/js/language.js', 'hr/static/src/js/m2x_avatar_employee.js', 'hr/static/src/js/standalone_m2o_avatar_employee.js', 'hr/static/src/js/user_menu.js', 'hr/static/src/models/*/*.js', ], 'web.qunit_suite_tests': [ 'hr/static/tests/helpers/mock_models.js', 'hr/static/tests/m2x_avatar_employee_tests.js', 'hr/static/tests/standalone_m2o_avatar_employee_tests.js', ], 'web.assets_qweb': [ 'hr/static/src/xml/hr_templates.xml', ], }, 'license': 'LGPL-3', }
32.173333
2,413
10,242
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import OrderedDict from itertools import chain from odoo.addons.hr.tests.common import TestHrCommon from odoo.tests import new_test_user, tagged, Form from odoo.exceptions import AccessError @tagged('post_install', '-at_install') class TestSelfAccessProfile(TestHrCommon): def test_access_my_profile(self): """ A simple user should be able to read all fields in his profile """ james = new_test_user(self.env, login='hel', groups='base.group_user', name='Simple employee', email='ric@example.com') james = james.with_user(james) self.env['hr.employee'].create({ 'name': 'James', 'user_id': james.id, }) view = self.env.ref('hr.res_users_view_form_profile') view_infos = james.fields_view_get(view_id=view.id) fields = view_infos['fields'].keys() james.read(fields) def test_readonly_fields(self): """ Employee related fields should be readonly if self editing is not allowed """ self.env['ir.config_parameter'].sudo().set_param('hr.hr_employee_self_edit', False) james = new_test_user(self.env, login='hel', groups='base.group_user', name='Simple employee', email='ric@example.com') james = james.with_user(james) self.env['hr.employee'].create({ 'name': 'James', 'user_id': james.id, }) view = self.env.ref('hr.res_users_view_form_profile') view_infos = james.fields_view_get(view_id=view.id) employee_related_fields = { field_name for field_name, field_attrs in view_infos['fields'].items() if field_attrs.get('related', (None,))[0] == 'employee_id' } form = Form(james, view=view) for field in employee_related_fields: with self.assertRaises(AssertionError, msg="Field '%s' should be readonly in the employee profile when self editing is not allowed." % field): form.__setattr__(field, 'some value') def test_profile_view_fields(self): """ A simple user should see all fields in profile view, even if they are protected by groups """ view = self.env.ref('hr.res_users_view_form_profile') # For reference, check the view with user with every groups protecting user fields all_groups_xml_ids = chain(*[ field.groups.split(',') for field in self.env['res.users']._fields.values() if field.groups if field.groups != '.' # "no-access" group on purpose ]) all_groups = self.env['res.groups'] for xml_id in all_groups_xml_ids: all_groups |= self.env.ref(xml_id.strip()) user_all_groups = new_test_user(self.env, groups='base.group_user', login='hel', name='God') user_all_groups.write({'groups_id': [(4, group.id, False) for group in all_groups]}) view_infos = self.env['res.users'].with_user(user_all_groups).fields_view_get(view_id=view.id) full_fields = view_infos['fields'] # Now check the view for a simple user user = new_test_user(self.env, login='gro', name='Grouillot') view_infos = self.env['res.users'].with_user(user).fields_view_get(view_id=view.id) fields = view_infos['fields'] # Compare both self.assertEqual(full_fields.keys(), fields.keys(), "View fields should not depend on user's groups") def test_access_my_profile_toolbar(self): """ A simple user shouldn't have the possibilities to see the 'Change Password' action""" james = new_test_user(self.env, login='jam', groups='base.group_user', name='Simple employee', email='jam@example.com') james = james.with_user(james) self.env['hr.employee'].create({ 'name': 'James', 'user_id': james.id, }) view = self.env.ref('hr.res_users_view_form_profile') available_actions = james.fields_view_get(view_id=view.id, toolbar=True)['toolbar']['action'] change_password_action = self.env.ref("base.change_password_wizard_action") self.assertFalse(any(x['id'] == change_password_action.id for x in available_actions)) """ An ERP manager should have the possibilities to see the 'Change Password' """ john = new_test_user(self.env, login='joh', groups='base.group_erp_manager', name='ERP Manager', email='joh@example.com') john = john.with_user(john) self.env['hr.employee'].create({ 'name': 'John', 'user_id': john.id, }) view = self.env.ref('hr.res_users_view_form_profile') available_actions = john.fields_view_get(view_id=view.id, toolbar=True)['toolbar']['action'] self.assertTrue(any(x['id'] == change_password_action.id for x in available_actions)) class TestSelfAccessRights(TestHrCommon): def setUp(self): super(TestSelfAccessRights, self).setUp() self.richard = new_test_user(self.env, login='ric', groups='base.group_user', name='Simple employee', email='ric@example.com') self.richard_emp = self.env['hr.employee'].create({ 'name': 'Richard', 'user_id': self.richard.id, 'address_home_id': self.env['res.partner'].create({'name': 'Richard', 'phone': '21454', 'type': 'private'}).id, }) self.hubert = new_test_user(self.env, login='hub', groups='base.group_user', name='Simple employee', email='hub@example.com') self.hubert_emp = self.env['hr.employee'].create({ 'name': 'Hubert', 'user_id': self.hubert.id, 'address_home_id': self.env['res.partner'].create({'name': 'Hubert', 'type': 'private'}).id, }) self.protected_fields_emp = OrderedDict([(k, v) for k, v in self.env['hr.employee']._fields.items() if v.groups == 'hr.group_hr_user']) # Compute fields and id field are always readable by everyone self.read_protected_fields_emp = OrderedDict([(k, v) for k, v in self.env['hr.employee']._fields.items() if not v.compute and k != 'id']) self.self_protected_fields_user = OrderedDict([ (k, v) for k, v in self.env['res.users']._fields.items() if v.groups == 'hr.group_hr_user' and k in self.env['res.users'].SELF_READABLE_FIELDS ]) # Read hr.employee # def testReadSelfEmployee(self): with self.assertRaises(AccessError): self.hubert_emp.with_user(self.richard).read(self.protected_fields_emp.keys()) def testReadOtherEmployee(self): with self.assertRaises(AccessError): self.hubert_emp.with_user(self.richard).read(self.protected_fields_emp.keys()) # Write hr.employee # def testWriteSelfEmployee(self): for f in self.protected_fields_emp: with self.assertRaises(AccessError): self.richard_emp.with_user(self.richard).write({f: 'dummy'}) def testWriteOtherEmployee(self): for f in self.protected_fields_emp: with self.assertRaises(AccessError): self.hubert_emp.with_user(self.richard).write({f: 'dummy'}) # Read res.users # def testReadSelfUserEmployee(self): for f in self.self_protected_fields_user: self.richard.with_user(self.richard).read([f]) # should not raise def testReadOtherUserEmployee(self): with self.assertRaises(AccessError): self.hubert.with_user(self.richard).read(self.self_protected_fields_user) # Write res.users # def testWriteSelfUserEmployeeSettingFalse(self): for f, v in self.self_protected_fields_user.items(): with self.assertRaises(AccessError): self.richard.with_user(self.richard).write({f: 'dummy'}) def testWriteSelfUserEmployee(self): self.env['ir.config_parameter'].set_param('hr.hr_employee_self_edit', True) for f, v in self.self_protected_fields_user.items(): val = None if v.type == 'char' or v.type == 'text': val = '0000' if f == 'pin' else 'dummy' if val is not None: self.richard.with_user(self.richard).write({f: val}) def testWriteSelfUserPreferencesEmployee(self): # self should always be able to update non hr.employee fields if # they are in SELF_READABLE_FIELDS self.env['ir.config_parameter'].set_param('hr.hr_employee_self_edit', False) # should not raise vals = [ {'tz': "Australia/ACT"}, {'email': "new@example.com"}, {'signature': "<p>I'm Richard!</p>"}, {'notification_type': "email"}, ] for v in vals: # should not raise self.richard.with_user(self.richard).write(v) def testWriteOtherUserPreferencesEmployee(self): # self should always be able to update non hr.employee fields if # they are in SELF_READABLE_FIELDS self.env['ir.config_parameter'].set_param('hr.hr_employee_self_edit', False) vals = [ {'tz': "Australia/ACT"}, {'email': "new@example.com"}, {'signature': "<p>I'm Richard!</p>"}, {'notification_type': "email"}, ] for v in vals: with self.assertRaises(AccessError): self.hubert.with_user(self.richard).write(v) def testWriteSelfPhoneEmployee(self): # phone is a related from res.partner (from base) but added in SELF_READABLE_FIELDS self.env['ir.config_parameter'].set_param('hr.hr_employee_self_edit', False) with self.assertRaises(AccessError): self.richard.with_user(self.richard).write({'phone': '2154545'}) def testWriteOtherUserEmployee(self): for f in self.self_protected_fields_user: with self.assertRaises(AccessError): self.hubert.with_user(self.richard).write({f: 'dummy'}) def testSearchUserEMployee(self): # Searching user based on employee_id field should not raise bad query error self.env['res.users'].with_user(self.richard).search([('employee_id', 'ilike', 'Hubert')])
47.198157
10,242
1,779
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.addons.hr.tests.common import TestHrCommon from odoo.addons.base.models.qweb import QWebException class TestMultiCompany(TestHrCommon): def setUp(self): super().setUp() self.company_1 = self.env['res.company'].create({'name': 'Opoo'}) self.company_2 = self.env['res.company'].create({'name': 'Otoo'}) self.employees = self.env['hr.employee'].create([ {'name': 'Bidule', 'company_id': self.company_1.id}, {'name': 'Machin', 'company_id': self.company_2.id}, ]) self.res_users_hr_officer.company_ids = [ (4, self.company_1.id), (4, self.company_2.id), ] self.res_users_hr_officer.company_id = self.company_1.id # flush and invalidate the cache, otherwise a full cache may prevent # access rights to be checked self.employees.flush() self.employees.invalidate_cache() def test_multi_company_report(self): content, content_type = self.env.ref('hr.hr_employee_print_badge').with_user(self.res_users_hr_officer).with_context( allowed_company_ids=[self.company_1.id, self.company_2.id] )._render_qweb_pdf(res_ids=self.employees.ids) self.assertIn(b'Bidule', content) self.assertIn(b'Machin', content) def test_single_company_report(self): with self.assertRaises(QWebException): # CacheMiss followed by AccessError content, content_type = self.env.ref('hr.hr_employee_print_badge').with_user(self.res_users_hr_officer).with_company( self.company_1 )._render_qweb_pdf(res_ids=self.employees.ids)
44.475
1,779
949
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr.tests.common import TestHrCommon class TestChannel(TestHrCommon): def setUp(self): super(TestChannel, self).setUp() self.channel = self.env['mail.channel'].create({'name': 'Test'}) emp0 = self.env['hr.employee'].create({ 'user_id': self.res_users_hr_officer.id, }) self.department = self.env['hr.department'].create({ 'name': 'Test Department', 'member_ids': [(4, emp0.id)], }) def test_auto_subscribe_department(self): self.assertEqual(self.channel.channel_partner_ids, self.env['res.partner']) self.channel.write({ 'subscription_department_ids': [(4, self.department.id)] }) self.assertEqual(self.channel.channel_partner_ids, self.department.mapped('member_ids.user_id.partner_id'))
32.724138
949
467
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mail.tests.common import mail_new_test_user from odoo.tests import common class TestHrCommon(common.TransactionCase): def setUp(self): super(TestHrCommon, self).setUp() self.res_users_hr_officer = mail_new_test_user(self.env, login='hro', groups='base.group_user,hr.group_hr_user', name='HR Officer', email='hro@example.com')
35.923077
467
2,396
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr.tests.common import TestHrCommon class TestHrFlow(TestHrCommon): def setUp(self): super(TestHrFlow, self).setUp() self.dep_rd = self.env['hr.department'].create({ 'name': 'Research & Development', }) self.job_developer = self.env['hr.job'].create({ 'name': 'Experienced Developer', 'department_id': self.dep_rd.id, 'no_of_recruitment': 5, }) self.employee_niv = self.env['hr.employee'].create({ 'name': 'Sharlene Rhodes', }) self.job_developer = self.job_developer.with_user(self.res_users_hr_officer.id) self.employee_niv = self.employee_niv.with_user(self.res_users_hr_officer.id) def test_open2recruit2close_job(self): """ Opening the job position for "Developer" and checking the job status and recruitment count. """ self.job_developer.set_open() self.assertEqual(self.job_developer.state, 'open', "Job position of 'Job Developer' is in 'open' state.") self.assertEqual(self.job_developer.no_of_recruitment, 0, "Wrong number of recruitment for the job 'Job Developer'(%s found instead of 0)." % self.job_developer.no_of_recruitment) """ Recruiting employee "NIV" for the job position "Developer" and checking the job status and recruitment count. """ self.job_developer.set_recruit() self.assertEqual(self.job_developer.state, 'recruit', "Job position of 'Job Developer' is in 'recruit' state.") self.assertEqual(self.job_developer.no_of_recruitment, 1, "Wrong number of recruitment for the job 'Job Developer'(%s found instead of 1.0)." % self.job_developer.no_of_recruitment) self.employee_niv.write({'job_id': self.job_developer.id}) """ Closing the recruitment for the job position "Developer" by marking it as open. """ self.job_developer.set_open() self.assertEqual(self.job_developer.state, 'open', "Job position of 'Job Developer' is in 'open' state.") self.assertEqual(self.job_developer.no_of_recruitment, 0, "Wrong number of recruitment for the job 'Job Developer'(%s found instead of 0)." % self.job_developer.no_of_recruitment)
49.916667
2,396
3,095
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.addons.hr.tests.common import TestHrCommon class TestHrEmployee(TestHrCommon): def setUp(self): super().setUp() self.user_without_image = self.env['res.users'].create({ 'name': 'Marc Demo', 'email': 'mark.brown23@example.com', 'image_1920': False, 'login': 'demo_1', 'password': 'demo_123' }) self.employee_without_image = self.env['hr.employee'].create({ 'user_id': self.user_without_image.id, 'image_1920': False }) def test_employee_resource(self): _tz = 'Pacific/Apia' self.res_users_hr_officer.company_id.resource_calendar_id.tz = _tz Employee = self.env['hr.employee'].with_user(self.res_users_hr_officer) employee_form = Form(Employee) employee_form.name = 'Raoul Grosbedon' employee_form.work_email = 'raoul@example.com' employee = employee_form.save() self.assertEqual(employee.tz, _tz) def test_employee_from_user(self): _tz = 'Pacific/Apia' _tz2 = 'America/Tijuana' self.res_users_hr_officer.company_id.resource_calendar_id.tz = _tz self.res_users_hr_officer.tz = _tz2 Employee = self.env['hr.employee'].with_user(self.res_users_hr_officer) employee_form = Form(Employee) employee_form.name = 'Raoul Grosbedon' employee_form.work_email = 'raoul@example.com' employee_form.user_id = self.res_users_hr_officer employee = employee_form.save() self.assertEqual(employee.name, 'Raoul Grosbedon') self.assertEqual(employee.work_email, self.res_users_hr_officer.email) self.assertEqual(employee.tz, self.res_users_hr_officer.tz) def test_employee_from_user_tz_no_reset(self): _tz = 'Pacific/Apia' self.res_users_hr_officer.tz = False Employee = self.env['hr.employee'].with_user(self.res_users_hr_officer) employee_form = Form(Employee) employee_form.name = 'Raoul Grosbedon' employee_form.work_email = 'raoul@example.com' employee_form.tz = _tz employee_form.user_id = self.res_users_hr_officer employee = employee_form.save() self.assertEqual(employee.name, 'Raoul Grosbedon') self.assertEqual(employee.work_email, self.res_users_hr_officer.email) self.assertEqual(employee.tz, _tz) def test_employee_has_avatar_even_if_it_has_no_image(self): self.assertTrue(self.employee_without_image.avatar_128) self.assertTrue(self.employee_without_image.avatar_256) self.assertTrue(self.employee_without_image.avatar_512) self.assertTrue(self.employee_without_image.avatar_1024) self.assertTrue(self.employee_without_image.avatar_1920) def test_employee_has_same_avatar_as_corresponding_user(self): self.assertEqual(self.employee_without_image.avatar_1920, self.user_without_image.avatar_1920)
43.591549
3,095
1,870
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class HrDepartureWizard(models.TransientModel): _name = 'hr.departure.wizard' _description = 'Departure Wizard' def _get_default_departure_date(self): departure_date = False if self.env.context.get('active_id'): departure_date = self.env['hr.employee'].browse(self.env.context['active_id']).departure_date return departure_date or fields.Date.today() departure_reason_id = fields.Many2one("hr.departure.reason", default=lambda self: self.env['hr.departure.reason'].search([], limit=1), required=True) departure_description = fields.Html(string="Additional Information") departure_date = fields.Date(string="Departure Date", required=True, default=_get_default_departure_date) employee_id = fields.Many2one( 'hr.employee', string='Employee', required=True, default=lambda self: self.env.context.get('active_id', None), ) archive_private_address = fields.Boolean('Archive Private Address', default=True) def action_register_departure(self): employee = self.employee_id if self.env.context.get('toggle_active', False) and employee.active: employee.with_context(no_wizard=True).toggle_active() employee.departure_reason_id = self.departure_reason_id employee.departure_description = self.departure_description employee.departure_date = self.departure_date if self.archive_private_address: # ignore contact links to internal users private_address = employee.address_home_id if private_address and private_address.active and not self.env['res.users'].search([('partner_id', '=', private_address.id)]): private_address.toggle_active()
49.210526
1,870
1,524
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class HrPlanWizard(models.TransientModel): _name = 'hr.plan.wizard' _description = 'Plan Wizard' plan_id = fields.Many2one('hr.plan', default=lambda self: self.env['hr.plan'].search([], limit=1)) employee_id = fields.Many2one( 'hr.employee', string='Employee', required=True, default=lambda self: self.env.context.get('active_id', None), ) def action_launch(self): for activity_type in self.plan_id.plan_activity_type_ids: responsible = activity_type.get_responsible_id(self.employee_id) if self.env['hr.employee'].with_user(responsible).check_access_rights('read', raise_exception=False): date_deadline = self.env['mail.activity']._calculate_date_deadline(activity_type.activity_type_id) self.employee_id.activity_schedule( activity_type_id=activity_type.activity_type_id.id, summary=activity_type.summary, note=activity_type.note, user_id=responsible.id, date_deadline=date_deadline ) return { 'type': 'ir.actions.act_window', 'res_model': 'hr.employee', 'res_id': self.employee_id.id, 'name': self.employee_id.display_name, 'view_mode': 'form', 'views': [(False, "form")], }
40.105263
1,524
1,008
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class DepartureReason(models.Model): _name = "hr.departure.reason" _description = "Departure Reason" _order = "sequence" sequence = fields.Integer("Sequence", default=10) name = fields.Char(string="Reason", required=True, translate=True) def _get_default_departure_reasons(self): return { 'fired': self.env.ref('hr.departure_fired', False), 'resigned': self.env.ref('hr.departure_resigned', False), 'retired': self.env.ref('hr.departure_retired', False), } @api.ondelete(at_uninstall=False) def _unlink_except_default_departure_reasons(self): ids = set(map(lambda a: a.id, self._get_default_departure_reasons().values())) if set(self.ids) & ids: raise UserError(_('Default departure reasons cannot be deleted.'))
37.333333
1,008
3,470
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, tools class HrEmployeePublic(models.Model): _name = "hr.employee.public" _inherit = ["hr.employee.base"] _description = 'Public Employee' _order = 'name' _auto = False _log_access = True # Include magic fields # Fields coming from hr.employee.base create_date = fields.Datetime(readonly=True) name = fields.Char(readonly=True) active = fields.Boolean(readonly=True) department_id = fields.Many2one(readonly=True) job_id = fields.Many2one(readonly=True) job_title = fields.Char(readonly=True) company_id = fields.Many2one(readonly=True) address_id = fields.Many2one(readonly=True) mobile_phone = fields.Char(readonly=True) work_phone = fields.Char(readonly=True) work_email = fields.Char(readonly=True) work_location_id = fields.Many2one(readonly=True) user_id = fields.Many2one(readonly=True) resource_id = fields.Many2one(readonly=True) resource_calendar_id = fields.Many2one(readonly=True) tz = fields.Selection(readonly=True) color = fields.Integer(readonly=True) employee_type = fields.Selection(readonly=True) employee_id = fields.Many2one('hr.employee', 'Employee', compute="_compute_employee_id", search="_search_employee_id", compute_sudo=True) # hr.employee.public specific fields child_ids = fields.One2many('hr.employee.public', 'parent_id', string='Direct subordinates', readonly=True) image_1920 = fields.Image("Image", related='employee_id.image_1920', compute_sudo=True) image_1024 = fields.Image("Image 1024", related='employee_id.image_1024', compute_sudo=True) image_512 = fields.Image("Image 512", related='employee_id.image_512', compute_sudo=True) image_256 = fields.Image("Image 256", related='employee_id.image_256', compute_sudo=True) image_128 = fields.Image("Image 128", related='employee_id.image_128', compute_sudo=True) avatar_1920 = fields.Image("Avatar", related='employee_id.avatar_1920', compute_sudo=True) avatar_1024 = fields.Image("Avatar 1024", related='employee_id.avatar_1024', compute_sudo=True) avatar_512 = fields.Image("Avatar 512", related='employee_id.avatar_512', compute_sudo=True) avatar_256 = fields.Image("Avatar 256", related='employee_id.avatar_256', compute_sudo=True) avatar_128 = fields.Image("Avatar 128", related='employee_id.avatar_128', compute_sudo=True) parent_id = fields.Many2one('hr.employee.public', 'Manager', readonly=True) coach_id = fields.Many2one('hr.employee.public', 'Coach', readonly=True) user_partner_id = fields.Many2one(related='user_id.partner_id', related_sudo=False, string="User's partner") def _search_employee_id(self, operator, value): return [('id', operator, value)] def _compute_employee_id(self): for employee in self: employee.employee_id = self.env['hr.employee'].browse(employee.id) @api.model def _get_fields(self): return ','.join('emp.%s' % name for name, field in self._fields.items() if field.store and field.type not in ['many2many', 'one2many']) def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute("""CREATE or REPLACE VIEW %s as ( SELECT %s FROM hr_employee emp )""" % (self._table, self._get_fields()))
50.289855
3,470
891
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, tools, _ class BaseModel(models.AbstractModel): _inherit = 'base' def _alias_get_error_message(self, message, message_dict, alias): if alias.alias_contact == 'employees': email_from = tools.decode_message_header(message, 'From') email_address = tools.email_split(email_from)[0] employee = self.env['hr.employee'].search([('work_email', 'ilike', email_address)], limit=1) if not employee: employee = self.env['hr.employee'].search([('user_id.email', 'ilike', email_address)], limit=1) if not employee: return _('restricted to employees') return False return super(BaseModel, self)._alias_get_error_message(message, message_dict, alias)
44.55
891
660
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class WorkLocation(models.Model): _name = "hr.work.location" _description = "Work Location" _order = 'name' active = fields.Boolean(default=True) name = fields.Char(string="Work Location", required=True) company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company) address_id = fields.Many2one('res.partner', required=True, string="Work Address", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") location_number = fields.Char()
41.25
660
697
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from random import randint from odoo import fields, models class EmployeeCategory(models.Model): _name = "hr.employee.category" _description = "Employee Category" def _get_default_color(self): return randint(1, 11) name = fields.Char(string="Tag Name", required=True) color = fields.Integer(string='Color Index', default=_get_default_color) employee_ids = fields.Many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', string='Employees') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ]
30.304348
697
4,642
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class Department(models.Model): _name = "hr.department" _description = "Department" _inherit = ['mail.thread'] _order = "name" _rec_name = 'complete_name' name = fields.Char('Department Name', required=True) complete_name = fields.Char('Complete Name', compute='_compute_complete_name', recursive=True, store=True) active = fields.Boolean('Active', default=True) company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.company) parent_id = fields.Many2one('hr.department', string='Parent Department', index=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") child_ids = fields.One2many('hr.department', 'parent_id', string='Child Departments') manager_id = fields.Many2one('hr.employee', string='Manager', tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") member_ids = fields.One2many('hr.employee', 'department_id', string='Members', readonly=True) total_employee = fields.Integer(compute='_compute_total_employee', string='Total Employee') jobs_ids = fields.One2many('hr.job', 'department_id', string='Jobs') note = fields.Text('Note') color = fields.Integer('Color Index') def name_get(self): if not self.env.context.get('hierarchical_naming', True): return [(record.id, record.name) for record in self] return super(Department, self).name_get() @api.model def name_create(self, name): return self.create({'name': name}).name_get()[0] @api.depends('name', 'parent_id.complete_name') def _compute_complete_name(self): for department in self: if department.parent_id: department.complete_name = '%s / %s' % (department.parent_id.complete_name, department.name) else: department.complete_name = department.name def _compute_total_employee(self): emp_data = self.env['hr.employee'].read_group([('department_id', 'in', self.ids)], ['department_id'], ['department_id']) result = dict((data['department_id'][0], data['department_id_count']) for data in emp_data) for department in self: department.total_employee = result.get(department.id, 0) @api.constrains('parent_id') def _check_parent_id(self): if not self._check_recursion(): raise ValidationError(_('You cannot create recursive departments.')) @api.model def create(self, vals): # TDE note: auto-subscription of manager done by hand, because currently # the tracking allows to track+subscribe fields linked to a res.user record # An update of the limited behavior should come, but not currently done. department = super(Department, self.with_context(mail_create_nosubscribe=True)).create(vals) manager = self.env['hr.employee'].browse(vals.get("manager_id")) if manager.user_id: department.message_subscribe(partner_ids=manager.user_id.partner_id.ids) return department def write(self, vals): """ If updating manager of a department, we need to update all the employees of department hierarchy, and subscribe the new manager. """ # TDE note: auto-subscription of manager done by hand, because currently # the tracking allows to track+subscribe fields linked to a res.user record # An update of the limited behavior should come, but not currently done. if 'manager_id' in vals: manager_id = vals.get("manager_id") if manager_id: manager = self.env['hr.employee'].browse(manager_id) # subscribe the manager user if manager.user_id: self.message_subscribe(partner_ids=manager.user_id.partner_id.ids) # set the employees's parent to the new manager self._update_employee_manager(manager_id) return super(Department, self).write(vals) def _update_employee_manager(self, manager_id): employees = self.env['hr.employee'] for department in self: employees = employees | self.env['hr.employee'].search([ ('id', '!=', manager_id), ('department_id', '=', department.id), ('parent_id', '=', department.manager_id.id) ]) employees.write({'parent_id': manager_id})
49.913978
4,642
250
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ResourceResource(models.Model): _inherit = "resource.resource" user_id = fields.Many2one(copy=False)
25
250
3,906
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.addons.web_editor.controllers.main import handle_history_divergence class Job(models.Model): _name = "hr.job" _description = "Job Position" _inherit = ['mail.thread'] _order = 'sequence' name = fields.Char(string='Job Position', required=True, index=True, translate=True) sequence = fields.Integer(default=10) expected_employees = fields.Integer(compute='_compute_employees', string='Total Forecasted Employees', store=True, help='Expected number of employees for this job position after new recruitment.') no_of_employee = fields.Integer(compute='_compute_employees', string="Current Number of Employees", store=True, help='Number of employees currently occupying this job position.') no_of_recruitment = fields.Integer(string='Expected New Employees', copy=False, help='Number of new employees you expect to recruit.', default=1) no_of_hired_employee = fields.Integer(string='Hired Employees', copy=False, help='Number of hired employees for this job position during recruitment phase.') employee_ids = fields.One2many('hr.employee', 'job_id', string='Employees', groups='base.group_user') description = fields.Html(string='Job Description', sanitize_attributes=False) requirements = fields.Text('Requirements') department_id = fields.Many2one('hr.department', string='Department', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) state = fields.Selection([ ('recruit', 'Recruitment in Progress'), ('open', 'Not Recruiting') ], string='Status', readonly=True, required=True, tracking=True, copy=False, default='recruit', help="Set whether the recruitment process is open or closed for this job position.") _sql_constraints = [ ('name_company_uniq', 'unique(name, company_id, department_id)', 'The name of the job position must be unique per department in company!'), ('no_of_recruitment_positive', 'CHECK(no_of_recruitment >= 0)', 'The expected number of new employees must be positive.') ] @api.depends('no_of_recruitment', 'employee_ids.job_id', 'employee_ids.active') def _compute_employees(self): employee_data = self.env['hr.employee'].read_group([('job_id', 'in', self.ids)], ['job_id'], ['job_id']) result = dict((data['job_id'][0], data['job_id_count']) for data in employee_data) for job in self: job.no_of_employee = result.get(job.id, 0) job.expected_employees = result.get(job.id, 0) + job.no_of_recruitment @api.model def create(self, values): """ We don't want the current user to be follower of all created job """ return super(Job, self.with_context(mail_create_nosubscribe=True)).create(values) @api.returns('self', lambda value: value.id) def copy(self, default=None): self.ensure_one() default = dict(default or {}) if 'name' not in default: default['name'] = _("%s (copy)") % (self.name) return super(Job, self).copy(default=default) def set_recruit(self): for record in self: no_of_recruitment = 1 if record.no_of_recruitment == 0 else record.no_of_recruitment record.write({'state': 'recruit', 'no_of_recruitment': no_of_recruitment}) return True def set_open(self): return self.write({ 'state': 'open', 'no_of_recruitment': 0, 'no_of_hired_employee': 0 }) def write(self, vals): if len(self) == 1: handle_history_divergence(self, 'description', vals) return super(Job, self).write(vals)
50.727273
3,906
418
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, api, tools class IrUiMenu(models.Model): _inherit = 'ir.ui.menu' def _load_menus_blacklist(self): res = super()._load_menus_blacklist() if self.env.user.has_group('hr.group_hr_user'): res.append(self.env.ref('hr.menu_hr_employee').id) return res
29.857143
418
2,899
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class HrPlanActivityType(models.Model): _name = 'hr.plan.activity.type' _description = 'Plan activity type' _rec_name = 'summary' activity_type_id = fields.Many2one( 'mail.activity.type', 'Activity Type', default=lambda self: self.env.ref('mail.mail_activity_data_todo'), domain=lambda self: ['|', ('res_model', '=', False), ('res_model', '=', 'hr.employee')], ondelete='restrict' ) summary = fields.Char('Summary', compute="_compute_default_summary", store=True, readonly=False) responsible = fields.Selection([ ('coach', 'Coach'), ('manager', 'Manager'), ('employee', 'Employee'), ('other', 'Other')], default='employee', string='Responsible', required=True) # sgv todo change back to 'Responsible Person' responsible_id = fields.Many2one('res.users', 'Name', help='Specific responsible of activity if not linked to the employee.') note = fields.Html('Note') @api.depends('activity_type_id') def _compute_default_summary(self): for plan_type in self: if not plan_type.summary and plan_type.activity_type_id and plan_type.activity_type_id.summary: plan_type.summary = plan_type.activity_type_id.summary def get_responsible_id(self, employee): if self.responsible == 'coach': if not employee.coach_id: raise UserError(_('Coach of employee %s is not set.', employee.name)) responsible = employee.coach_id.user_id if not responsible: raise UserError(_('User of coach of employee %s is not set.', employee.name)) elif self.responsible == 'manager': if not employee.parent_id: raise UserError(_('Manager of employee %s is not set.', employee.name)) responsible = employee.parent_id.user_id if not responsible: raise UserError(_('User of manager of employee %s is not set.', employee.name)) elif self.responsible == 'employee': responsible = employee.user_id if not responsible: raise UserError(_('User linked to employee %s is required.', employee.name)) elif self.responsible == 'other': responsible = self.responsible_id if not responsible: raise UserError(_('No specific user given on activity %s.', self.activity_type_id.name)) return responsible class HrPlan(models.Model): _name = 'hr.plan' _description = 'plan' name = fields.Char('Name', required=True) plan_activity_type_ids = fields.Many2many('hr.plan.activity.type', string='Activities') active = fields.Boolean(default=True)
43.268657
2,899
349
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Company(models.Model): _inherit = 'res.company' hr_presence_control_email_amount = fields.Integer(string="# emails to send") hr_presence_control_ip_list = fields.Char(string="Valid IP addresses")
31.727273
349
24,014
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import pytz from datetime import datetime, time from dateutil.rrule import rrule, DAILY from random import choice from string import digits from werkzeug.urls import url_encode from dateutil.relativedelta import relativedelta from collections import defaultdict from odoo import api, fields, models, _ from odoo.osv.query import Query from odoo.exceptions import ValidationError, AccessError, UserError from odoo.osv import expression from odoo.tools.misc import format_date class HrEmployeePrivate(models.Model): """ NB: Any field only available on the model hr.employee (i.e. not on the hr.employee.public model) should have `groups="hr.group_hr_user"` on its definition to avoid being prefetched when the user hasn't access to the hr.employee model. Indeed, the prefetch loads the data for all the fields that are available according to the group defined on them. """ _name = "hr.employee" _description = "Employee" _order = 'name' _inherit = ['hr.employee.base', 'mail.thread', 'mail.activity.mixin', 'resource.mixin', 'avatar.mixin'] _mail_post_access = 'read' # resource and user # required on the resource, make sure required="True" set in the view name = fields.Char(string="Employee Name", related='resource_id.name', store=True, readonly=False, tracking=True) user_id = fields.Many2one('res.users', 'User', related='resource_id.user_id', store=True, readonly=False) user_partner_id = fields.Many2one(related='user_id.partner_id', related_sudo=False, string="User's partner") active = fields.Boolean('Active', related='resource_id.active', default=True, store=True, readonly=False) company_id = fields.Many2one('res.company',required=True) company_country_id = fields.Many2one('res.country', 'Company Country', related='company_id.country_id', readonly=True) company_country_code = fields.Char(related='company_country_id.code', readonly=True) # private partner address_home_id = fields.Many2one( 'res.partner', 'Address', help='Enter here the private address of the employee, not the one linked to your company.', groups="hr.group_hr_user", tracking=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") is_address_home_a_company = fields.Boolean( 'The employee address has a company linked', compute='_compute_is_address_home_a_company', ) private_email = fields.Char(related='address_home_id.email', string="Private Email", groups="hr.group_hr_user") lang = fields.Selection(related='address_home_id.lang', string="Lang", groups="hr.group_hr_user", readonly=False) country_id = fields.Many2one( 'res.country', 'Nationality (Country)', groups="hr.group_hr_user", tracking=True) gender = fields.Selection([ ('male', 'Male'), ('female', 'Female'), ('other', 'Other') ], groups="hr.group_hr_user", tracking=True) marital = fields.Selection([ ('single', 'Single'), ('married', 'Married'), ('cohabitant', 'Legal Cohabitant'), ('widower', 'Widower'), ('divorced', 'Divorced') ], string='Marital Status', groups="hr.group_hr_user", default='single', tracking=True) spouse_complete_name = fields.Char(string="Spouse Complete Name", groups="hr.group_hr_user", tracking=True) spouse_birthdate = fields.Date(string="Spouse Birthdate", groups="hr.group_hr_user", tracking=True) children = fields.Integer(string='Number of Children', groups="hr.group_hr_user", tracking=True) place_of_birth = fields.Char('Place of Birth', groups="hr.group_hr_user", tracking=True) country_of_birth = fields.Many2one('res.country', string="Country of Birth", groups="hr.group_hr_user", tracking=True) birthday = fields.Date('Date of Birth', groups="hr.group_hr_user", tracking=True) ssnid = fields.Char('SSN No', help='Social Security Number', groups="hr.group_hr_user", tracking=True) sinid = fields.Char('SIN No', help='Social Insurance Number', groups="hr.group_hr_user", tracking=True) identification_id = fields.Char(string='Identification No', groups="hr.group_hr_user", tracking=True) passport_id = fields.Char('Passport No', groups="hr.group_hr_user", tracking=True) bank_account_id = fields.Many2one( 'res.partner.bank', 'Bank Account Number', domain="[('partner_id', '=', address_home_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", groups="hr.group_hr_user", tracking=True, help='Employee bank salary account') permit_no = fields.Char('Work Permit No', groups="hr.group_hr_user", tracking=True) visa_no = fields.Char('Visa No', groups="hr.group_hr_user", tracking=True) visa_expire = fields.Date('Visa Expire Date', groups="hr.group_hr_user", tracking=True) work_permit_expiration_date = fields.Date('Work Permit Expiration Date', groups="hr.group_hr_user", tracking=True) has_work_permit = fields.Binary(string="Work Permit", groups="hr.group_hr_user", tracking=True) work_permit_scheduled_activity = fields.Boolean(default=False, groups="hr.group_hr_user") additional_note = fields.Text(string='Additional Note', groups="hr.group_hr_user", tracking=True) certificate = fields.Selection([ ('graduate', 'Graduate'), ('bachelor', 'Bachelor'), ('master', 'Master'), ('doctor', 'Doctor'), ('other', 'Other'), ], 'Certificate Level', default='other', groups="hr.group_hr_user", tracking=True) study_field = fields.Char("Field of Study", groups="hr.group_hr_user", tracking=True) study_school = fields.Char("School", groups="hr.group_hr_user", tracking=True) emergency_contact = fields.Char("Emergency Contact", groups="hr.group_hr_user", tracking=True) emergency_phone = fields.Char("Emergency Phone", groups="hr.group_hr_user", tracking=True) km_home_work = fields.Integer(string="Home-Work Distance", groups="hr.group_hr_user", tracking=True) job_id = fields.Many2one(tracking=True) phone = fields.Char(related='address_home_id.phone', related_sudo=False, readonly=False, string="Private Phone", groups="hr.group_hr_user") # employee in company child_ids = fields.One2many('hr.employee', 'parent_id', string='Direct subordinates') category_ids = fields.Many2many( 'hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', groups="hr.group_hr_manager", string='Tags') # misc notes = fields.Text('Notes', groups="hr.group_hr_user") color = fields.Integer('Color Index', default=0) barcode = fields.Char(string="Badge ID", help="ID used for employee identification.", groups="hr.group_hr_user", copy=False) pin = fields.Char(string="PIN", groups="hr.group_hr_user", copy=False, help="PIN used to Check In/Out in the Kiosk Mode of the Attendance application (if enabled in Configuration) and to change the cashier in the Point of Sale application.") departure_reason_id = fields.Many2one("hr.departure.reason", string="Departure Reason", groups="hr.group_hr_user", copy=False, tracking=True, ondelete='restrict') departure_description = fields.Html(string="Additional Information", groups="hr.group_hr_user", copy=False, tracking=True) departure_date = fields.Date(string="Departure Date", groups="hr.group_hr_user", copy=False, tracking=True) message_main_attachment_id = fields.Many2one(groups="hr.group_hr_user") id_card = fields.Binary(string="ID Card Copy", groups="hr.group_hr_user") driving_license = fields.Binary(string="Driving License", groups="hr.group_hr_user") _sql_constraints = [ ('barcode_uniq', 'unique (barcode)', "The Badge ID must be unique, this one is already assigned to another employee."), ('user_uniq', 'unique (user_id, company_id)', "A user cannot be linked to multiple employees in the same company.") ] @api.depends('name', 'user_id.avatar_1920', 'image_1920') def _compute_avatar_1920(self): super()._compute_avatar_1920() @api.depends('name', 'user_id.avatar_1024', 'image_1024') def _compute_avatar_1024(self): super()._compute_avatar_1024() @api.depends('name', 'user_id.avatar_512', 'image_512') def _compute_avatar_512(self): super()._compute_avatar_512() @api.depends('name', 'user_id.avatar_256', 'image_256') def _compute_avatar_256(self): super()._compute_avatar_256() @api.depends('name', 'user_id.avatar_128', 'image_128') def _compute_avatar_128(self): super()._compute_avatar_128() def _compute_avatar(self, avatar_field, image_field): for employee in self: avatar = employee._origin[image_field] if not avatar: if employee.user_id: avatar = employee.user_id[avatar_field] else: avatar = employee._avatar_get_placeholder() employee[avatar_field] = avatar def name_get(self): if self.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self).name_get() return self.env['hr.employee.public'].browse(self.ids).name_get() def _read(self, fields): if self.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self)._read(fields) res = self.env['hr.employee.public'].browse(self.ids).read(fields) for r in res: record = self.browse(r['id']) record._update_cache({k:v for k,v in r.items() if k in fields}, validate=False) @api.model def _cron_check_work_permit_validity(self): # Called by a cron # Schedule an activity 1 month before the work permit expires outdated_days = fields.Date.today() + relativedelta(months=+1) nearly_expired_work_permits = self.search([('work_permit_scheduled_activity', '=', False), ('work_permit_expiration_date', '<', outdated_days)]) employees_scheduled = self.env['hr.employee'] for employee in nearly_expired_work_permits.filtered(lambda employee: employee.parent_id): responsible_user_id = employee.parent_id.user_id.id if responsible_user_id: employees_scheduled |= employee lang = self.env['res.users'].browse(responsible_user_id).lang formated_date = format_date(employee.env, employee.work_permit_expiration_date, date_format="dd MMMM y", lang_code=lang) employee.activity_schedule( 'mail.mail_activity_data_todo', note=_('The work permit of %(employee)s expires at %(date)s.', employee=employee.name, date=formated_date), user_id=responsible_user_id) employees_scheduled.write({'work_permit_scheduled_activity': True}) def read(self, fields, load='_classic_read'): if self.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self).read(fields, load=load) private_fields = set(fields).difference(self.env['hr.employee.public']._fields.keys()) if private_fields: raise AccessError(_('The fields "%s" you try to read is not available on the public employee profile.') % (','.join(private_fields))) return self.env['hr.employee.public'].browse(self.ids).read(fields, load=load) @api.model def load_views(self, views, options=None): if self.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self).load_views(views, options=options) return self.env['hr.employee.public'].load_views(views, options=options) @api.model def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None): """ We override the _search because it is the method that checks the access rights This is correct to override the _search. That way we enforce the fact that calling search on an hr.employee returns a hr.employee recordset, even if you don't have access to this model, as the result of _search (the ids of the public employees) is to be browsed on the hr.employee model. This can be trusted as the ids of the public employees exactly match the ids of the related hr.employee. """ if self.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid) try: ids = self.env['hr.employee.public']._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid) except ValueError: raise AccessError(_('You do not have access to this document.')) if not count and isinstance(ids, Query): # the result is expected from this table, so we should link tables ids = super(HrEmployeePrivate, self.sudo())._search([('id', 'in', ids)]) return ids def get_formview_id(self, access_uid=None): """ Override this method in order to redirect many2one towards the right model depending on access_uid """ if access_uid: self_sudo = self.with_user(access_uid) else: self_sudo = self if self_sudo.check_access_rights('read', raise_exception=False): return super(HrEmployeePrivate, self).get_formview_id(access_uid=access_uid) # Hardcode the form view for public employee return self.env.ref('hr.hr_employee_public_view_form').id def get_formview_action(self, access_uid=None): """ Override this method in order to redirect many2one towards the right model depending on access_uid """ res = super(HrEmployeePrivate, self).get_formview_action(access_uid=access_uid) if access_uid: self_sudo = self.with_user(access_uid) else: self_sudo = self if not self_sudo.check_access_rights('read', raise_exception=False): res['res_model'] = 'hr.employee.public' return res @api.constrains('pin') def _verify_pin(self): for employee in self: if employee.pin and not employee.pin.isdigit(): raise ValidationError(_("The PIN must be a sequence of digits.")) @api.onchange('user_id') def _onchange_user(self): if self.user_id: self.update(self._sync_user(self.user_id, (bool(self.image_1920)))) if not self.name: self.name = self.user_id.name @api.onchange('resource_calendar_id') def _onchange_timezone(self): if self.resource_calendar_id and not self.tz: self.tz = self.resource_calendar_id.tz def _sync_user(self, user, employee_has_image=False): vals = dict( work_email=user.email, user_id=user.id, ) if not employee_has_image: vals['image_1920'] = user.image_1920 if user.tz: vals['tz'] = user.tz return vals @api.model def create(self, vals): if vals.get('user_id'): user = self.env['res.users'].browse(vals['user_id']) vals.update(self._sync_user(user, bool(vals.get('image_1920')))) vals['name'] = vals.get('name', user.name) employee = super(HrEmployeePrivate, self).create(vals) if employee.department_id: self.env['mail.channel'].sudo().search([ ('subscription_department_ids', 'in', employee.department_id.id) ])._subscribe_users_automatically() employee._message_subscribe(employee.address_home_id.ids) # Launch onboarding plans url = '/web#%s' % url_encode({ 'action': 'hr.plan_wizard_action', 'active_id': employee.id, 'active_model': 'hr.employee', 'menu_id': self.env.ref('hr.menu_hr_root').id, }) employee._message_log(body=_('<b>Congratulations!</b> May I recommend you to setup an <a href="%s">onboarding plan?</a>') % (url)) return employee def write(self, vals): if 'address_home_id' in vals: account_id = vals.get('bank_account_id') or self.bank_account_id.id if account_id: self.env['res.partner.bank'].browse(account_id).partner_id = vals['address_home_id'] self.message_unsubscribe(self.address_home_id.ids) if vals['address_home_id']: self._message_subscribe([vals['address_home_id']]) if vals.get('user_id'): # Update the profile pictures with user, except if provided vals.update(self._sync_user(self.env['res.users'].browse(vals['user_id']), (bool(self.image_1920)))) if 'work_permit_expiration_date' in vals: vals['work_permit_scheduled_activity'] = False res = super(HrEmployeePrivate, self).write(vals) if vals.get('department_id') or vals.get('user_id'): department_id = vals['department_id'] if vals.get('department_id') else self[:1].department_id.id # When added to a department or changing user, subscribe to the channels auto-subscribed by department self.env['mail.channel'].sudo().search([ ('subscription_department_ids', 'in', department_id) ])._subscribe_users_automatically() return res def unlink(self): resources = self.mapped('resource_id') super(HrEmployeePrivate, self).unlink() return resources.unlink() def _get_employee_m2o_to_empty_on_archived_employees(self): return ['parent_id', 'coach_id'] def _get_user_m2o_to_empty_on_archived_employees(self): return [] def toggle_active(self): res = super(HrEmployeePrivate, self).toggle_active() unarchived_employees = self.filtered(lambda employee: employee.active) unarchived_employees.write({ 'departure_reason_id': False, 'departure_description': False, 'departure_date': False }) archived_addresses = unarchived_employees.mapped('address_home_id').filtered(lambda addr: not addr.active) archived_addresses.toggle_active() archived_employees = self.filtered(lambda e: not e.active) if archived_employees: # Empty links to this employees (example: manager, coach, time off responsible, ...) employee_fields_to_empty = self._get_employee_m2o_to_empty_on_archived_employees() user_fields_to_empty = self._get_user_m2o_to_empty_on_archived_employees() employee_domain = [[(field, 'in', archived_employees.ids)] for field in employee_fields_to_empty] user_domain = [[(field, 'in', archived_employees.user_id.ids) for field in user_fields_to_empty]] employees = self.env['hr.employee'].search(expression.OR(employee_domain + user_domain)) for employee in employees: for field in employee_fields_to_empty: if employee[field] in archived_employees: employee[field] = False for field in user_fields_to_empty: if employee[field] in archived_employees.user_id: employee[field] = False if len(self) == 1 and not self.active and not self.env.context.get('no_wizard', False): return { 'type': 'ir.actions.act_window', 'name': _('Register Departure'), 'res_model': 'hr.departure.wizard', 'view_mode': 'form', 'target': 'new', 'context': {'active_id': self.id}, 'views': [[False, 'form']] } return res @api.onchange('company_id') def _onchange_company_id(self): if self._origin: return {'warning': { 'title': _("Warning"), 'message': _("To avoid multi company issues (loosing the access to your previous contracts, leaves, ...), you should create another employee in the new company instead.") }} def generate_random_barcode(self): for employee in self: employee.barcode = '041'+"".join(choice(digits) for i in range(9)) @api.depends('address_home_id.parent_id') def _compute_is_address_home_a_company(self): """Checks that chosen address (res.partner) is not linked to a company. """ for employee in self: try: employee.is_address_home_a_company = employee.address_home_id.parent_id.id is not False except AccessError: employee.is_address_home_a_company = False def _get_tz(self): # Finds the first valid timezone in his tz, his work hours tz, # the company calendar tz or UTC and returns it as a string self.ensure_one() return self.tz or\ self.resource_calendar_id.tz or\ self.company_id.resource_calendar_id.tz or\ 'UTC' def _get_tz_batch(self): # Finds the first valid timezone in his tz, his work hours tz, # the company calendar tz or UTC # Returns a dict {employee_id: tz} return {emp.id: emp._get_tz() for emp in self} # --------------------------------------------------------- # Business Methods # --------------------------------------------------------- @api.model def get_import_templates(self): return [{ 'label': _('Import Template for Employees'), 'template': '/hr/static/xls/hr_employee.xls' }] def _post_author(self): """ When a user updates his own employee's data, all operations are performed by super user. However, tracking messages should not be posted as OdooBot but as the actual user. This method is used in the overrides of `_message_log` and `message_post` to post messages as the correct user. """ real_user = self.env.context.get('binary_field_real_user') if self.env.is_superuser() and real_user: self = self.with_user(real_user) return self def _get_unusual_days(self, date_from, date_to=None): # Checking the calendar directly allows to not grey out the leaves taken # by the employee # Prevents a traceback when loading calendar views and no employee is linked to the user. if not self: return {} self.ensure_one() calendar = self.resource_calendar_id if not calendar: return {} dfrom = datetime.combine(fields.Date.from_string(date_from), time.min).replace(tzinfo=pytz.UTC) dto = datetime.combine(fields.Date.from_string(date_to), time.max).replace(tzinfo=pytz.UTC) works = {d[0].date() for d in calendar._work_intervals_batch(dfrom, dto)[False]} return {fields.Date.to_string(day.date()): (day.date() not in works) for day in rrule(DAILY, dfrom, until=dto)} # --------------------------------------------------------- # Messaging # --------------------------------------------------------- def _message_log(self, **kwargs): return super(HrEmployeePrivate, self._post_author())._message_log(**kwargs) @api.returns('mail.message', lambda value: value.id) def message_post(self, **kwargs): return super(HrEmployeePrivate, self._post_author()).message_post(**kwargs) def _sms_get_partner_fields(self): return ['user_partner_id'] def _sms_get_number_fields(self): return ['mobile_phone']
50.769556
24,014
563
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ class Alias(models.Model): _inherit = 'mail.alias' alias_contact = fields.Selection(selection_add=[ ('employees', 'Authenticated Employees'), ], ondelete={'employees': 'cascade'}) def _get_alias_contact_description(self): if self.alias_contact == 'employees': return _('addresses linked to registered employees') return super(Alias, self)._get_alias_contact_description()
33.117647
563
13,509
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields, _, SUPERUSER_ID from odoo.exceptions import AccessError HR_READABLE_FIELDS = [ 'active', 'child_ids', 'employee_id', 'address_home_id', 'employee_ids', 'employee_parent_id', 'hr_presence_state', 'last_activity', 'last_activity_time', 'can_edit', 'is_system', ] HR_WRITABLE_FIELDS = [ 'additional_note', 'private_street', 'private_street2', 'private_city', 'private_state_id', 'private_zip', 'private_country_id', 'address_id', 'barcode', 'birthday', 'category_ids', 'children', 'coach_id', 'country_of_birth', 'department_id', 'display_name', 'emergency_contact', 'emergency_phone', 'employee_bank_account_id', 'employee_country_id', 'gender', 'identification_id', 'is_address_home_a_company', 'job_title', 'private_email', 'km_home_work', 'marital', 'mobile_phone', 'notes', 'employee_parent_id', 'passport_id', 'permit_no', 'employee_phone', 'pin', 'place_of_birth', 'spouse_birthdate', 'spouse_complete_name', 'visa_expire', 'visa_no', 'work_email', 'work_location_id', 'work_phone', 'certificate', 'study_field', 'study_school', 'private_lang', 'employee_type', ] class User(models.Model): _inherit = ['res.users'] def _employee_ids_domain(self): # employee_ids is considered a safe field and as such will be fetched as sudo. # So try to enforce the security rules on the field to make sure we do not load employees outside of active companies return [('company_id', 'in', self.env.company.ids + self.env.context.get('allowed_company_ids', []))] # note: a user can only be linked to one employee per company (see sql constraint in ´hr.employee´) employee_ids = fields.One2many('hr.employee', 'user_id', string='Related employee', domain=_employee_ids_domain) employee_id = fields.Many2one('hr.employee', string="Company employee", compute='_compute_company_employee', search='_search_company_employee', store=False) job_title = fields.Char(related='employee_id.job_title', readonly=False, related_sudo=False) work_phone = fields.Char(related='employee_id.work_phone', readonly=False, related_sudo=False) mobile_phone = fields.Char(related='employee_id.mobile_phone', readonly=False, related_sudo=False) employee_phone = fields.Char(related='employee_id.phone', readonly=False, related_sudo=False) work_email = fields.Char(related='employee_id.work_email', readonly=False, related_sudo=False) category_ids = fields.Many2many(related='employee_id.category_ids', string="Employee Tags", readonly=False, related_sudo=False) department_id = fields.Many2one(related='employee_id.department_id', readonly=False, related_sudo=False) address_id = fields.Many2one(related='employee_id.address_id', readonly=False, related_sudo=False) work_location_id = fields.Many2one(related='employee_id.work_location_id', readonly=False, related_sudo=False) employee_parent_id = fields.Many2one(related='employee_id.parent_id', readonly=False, related_sudo=False) coach_id = fields.Many2one(related='employee_id.coach_id', readonly=False, related_sudo=False) address_home_id = fields.Many2one(related='employee_id.address_home_id', readonly=False, related_sudo=False) private_street = fields.Char(related='address_home_id.street', string="Private Street", readonly=False, related_sudo=False) private_street2 = fields.Char(related='address_home_id.street2', string="Private Street2", readonly=False, related_sudo=False) private_city = fields.Char(related='address_home_id.city', string="Private City", readonly=False, related_sudo=False) private_state_id = fields.Many2one( related='address_home_id.state_id', string="Private State", readonly=False, related_sudo=False, domain="[('country_id', '=?', private_country_id)]") private_zip = fields.Char(related='address_home_id.zip', readonly=False, string="Private Zip", related_sudo=False) private_country_id = fields.Many2one(related='address_home_id.country_id', string="Private Country", readonly=False, related_sudo=False) is_address_home_a_company = fields.Boolean(related='employee_id.is_address_home_a_company', readonly=False, related_sudo=False) private_email = fields.Char(related='address_home_id.email', string="Private Email", readonly=False) private_lang = fields.Selection(related='address_home_id.lang', string="Employee Lang", readonly=False) km_home_work = fields.Integer(related='employee_id.km_home_work', readonly=False, related_sudo=False) # res.users already have a field bank_account_id and country_id from the res.partner inheritance: don't redefine them employee_bank_account_id = fields.Many2one(related='employee_id.bank_account_id', string="Employee's Bank Account Number", related_sudo=False, readonly=False) employee_country_id = fields.Many2one(related='employee_id.country_id', string="Employee's Country", readonly=False, related_sudo=False) identification_id = fields.Char(related='employee_id.identification_id', readonly=False, related_sudo=False) passport_id = fields.Char(related='employee_id.passport_id', readonly=False, related_sudo=False) gender = fields.Selection(related='employee_id.gender', readonly=False, related_sudo=False) birthday = fields.Date(related='employee_id.birthday', readonly=False, related_sudo=False) place_of_birth = fields.Char(related='employee_id.place_of_birth', readonly=False, related_sudo=False) country_of_birth = fields.Many2one(related='employee_id.country_of_birth', readonly=False, related_sudo=False) marital = fields.Selection(related='employee_id.marital', readonly=False, related_sudo=False) spouse_complete_name = fields.Char(related='employee_id.spouse_complete_name', readonly=False, related_sudo=False) spouse_birthdate = fields.Date(related='employee_id.spouse_birthdate', readonly=False, related_sudo=False) children = fields.Integer(related='employee_id.children', readonly=False, related_sudo=False) emergency_contact = fields.Char(related='employee_id.emergency_contact', readonly=False, related_sudo=False) emergency_phone = fields.Char(related='employee_id.emergency_phone', readonly=False, related_sudo=False) visa_no = fields.Char(related='employee_id.visa_no', readonly=False, related_sudo=False) permit_no = fields.Char(related='employee_id.permit_no', readonly=False, related_sudo=False) visa_expire = fields.Date(related='employee_id.visa_expire', readonly=False, related_sudo=False) additional_note = fields.Text(related='employee_id.additional_note', readonly=False, related_sudo=False) barcode = fields.Char(related='employee_id.barcode', readonly=False, related_sudo=False) pin = fields.Char(related='employee_id.pin', readonly=False, related_sudo=False) certificate = fields.Selection(related='employee_id.certificate', readonly=False, related_sudo=False) study_field = fields.Char(related='employee_id.study_field', readonly=False, related_sudo=False) study_school = fields.Char(related='employee_id.study_school', readonly=False, related_sudo=False) employee_count = fields.Integer(compute='_compute_employee_count') hr_presence_state = fields.Selection(related='employee_id.hr_presence_state') last_activity = fields.Date(related='employee_id.last_activity') last_activity_time = fields.Char(related='employee_id.last_activity_time') employee_type = fields.Selection(related='employee_id.employee_type', readonly=False, related_sudo=False) can_edit = fields.Boolean(compute='_compute_can_edit') is_system = fields.Boolean(compute="_compute_is_system") @api.depends_context('uid') def _compute_is_system(self): self.is_system = self.env.user._is_system() def _compute_can_edit(self): can_edit = self.env['ir.config_parameter'].sudo().get_param('hr.hr_employee_self_edit') or self.env.user.has_group('hr.group_hr_user') for user in self: user.can_edit = can_edit @api.depends('employee_ids') def _compute_employee_count(self): for user in self.with_context(active_test=False): user.employee_count = len(user.employee_ids) @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + HR_READABLE_FIELDS + HR_WRITABLE_FIELDS @property def SELF_WRITEABLE_FIELDS(self): return super().SELF_WRITEABLE_FIELDS + HR_WRITABLE_FIELDS @api.model def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): # When the front-end loads the views it gets the list of available fields # for the user (according to its access rights). Later, when the front-end wants to # populate the view with data, it only asks to read those available fields. # However, in this case, we want the user to be able to read/write its own data, # even if they are protected by groups. # We make the front-end aware of those fields by sending all field definitions. # Note: limit the `sudo` to the only action of "editing own profile" action in order to # avoid breaking `groups` mecanism on res.users form view. profile_view = self.env.ref("hr.res_users_view_form_profile") original_user = self.env.user if profile_view and view_id == profile_view.id: self = self.with_user(SUPERUSER_ID) result = super(User, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) # Due to using the SUPERUSER the result will contain action that the user may not have access too # here we filter out actions that requires special implicit rights to avoid having unusable actions # in the dropdown menu. if toolbar and self.env.user != original_user: self = self.with_user(original_user.id) if not self.user_has_groups("base.group_erp_manager"): change_password_action = self.env.ref("base.change_password_wizard_action") result['toolbar']['action'] = [act for act in result['toolbar']['action'] if act['id'] != change_password_action.id] return result def _get_employee_fields_to_sync(self): """Get values to sync to the related employee when the User is changed. """ return ['name', 'email', 'image_1920', 'tz'] def write(self, vals): """ Synchronize user and its related employee and check access rights if employees are not allowed to update their own data (otherwise sudo is applied for self data). """ hr_fields = { field for field_name, field in self._fields.items() if field.related_field and field.related_field.model_name == 'hr.employee' and field_name in vals } can_edit_self = self.env['ir.config_parameter'].sudo().get_param('hr.hr_employee_self_edit') or self.env.user.has_group('hr.group_hr_user') if hr_fields and not can_edit_self: # Raise meaningful error message raise AccessError(_("You are only allowed to update your preferences. Please contact a HR officer to update other information.")) result = super(User, self).write(vals) employee_values = {} for fname in [f for f in self._get_employee_fields_to_sync() if f in vals]: employee_values[fname] = vals[fname] if employee_values: if 'email' in employee_values: employee_values['work_email'] = employee_values.pop('email') if 'image_1920' in vals: without_image = self.env['hr.employee'].sudo().search([('user_id', 'in', self.ids), ('image_1920', '=', False)]) with_image = self.env['hr.employee'].sudo().search([('user_id', 'in', self.ids), ('image_1920', '!=', False)]) without_image.write(employee_values) if not can_edit_self: employee_values.pop('image_1920') with_image.write(employee_values) else: self.env['hr.employee'].sudo().search([('user_id', 'in', self.ids)]).write(employee_values) return result @api.model def action_get(self): if self.env.user.employee_id: return self.env['ir.actions.act_window']._for_xml_id('hr.res_users_action_my') return super(User, self).action_get() @api.depends('employee_ids') @api.depends_context('company') def _compute_company_employee(self): employee_per_user = { employee.user_id: employee for employee in self.env['hr.employee'].search([('user_id', 'in', self.ids), ('company_id', '=', self.env.company.id)]) } for user in self: user.employee_id = employee_per_user.get(user) def _search_company_employee(self, operator, value): return [('employee_ids', operator, value)] def action_create_employee(self): self.ensure_one() self.env['hr.employee'].create(dict( name=self.name, company_id=self.env.company.id, **self.env['hr.employee']._sync_user(self) ))
52.761719
13,507
1,958
py
PYTHON
15.0
# -*- coding: utf-8 -*- import threading from odoo import fields, models, api, _ from odoo.exceptions import ValidationError class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' resource_calendar_id = fields.Many2one( 'resource.calendar', 'Company Working Hours', related='company_id.resource_calendar_id', readonly=False) module_hr_presence = fields.Boolean(string="Advanced Presence Control") module_hr_skills = fields.Boolean(string="Skills Management") hr_presence_control_login = fields.Boolean(string="Based on user status in system", config_parameter='hr.hr_presence_control_login') hr_presence_control_email = fields.Boolean(string="Based on number of emails sent", config_parameter='hr_presence.hr_presence_control_email') hr_presence_control_ip = fields.Boolean(string="Based on IP Address", config_parameter='hr_presence.hr_presence_control_ip') module_hr_attendance = fields.Boolean(string="Based on attendances") hr_presence_control_email_amount = fields.Integer(related="company_id.hr_presence_control_email_amount", readonly=False) hr_presence_control_ip_list = fields.Char(related="company_id.hr_presence_control_ip_list", readonly=False) hr_employee_self_edit = fields.Boolean(string="Employee Editing", config_parameter='hr.hr_employee_self_edit') @api.constrains('module_hr_presence', 'hr_presence_control_email', 'hr_presence_control_ip') def _check_advanced_presence(self): test_mode = self.env.registry.in_test_mode() or getattr(threading.current_thread(), 'testing', False) if self.env.context.get('install_mode', False) or test_mode: return for settings in self: if settings.module_hr_presence and not (settings.hr_presence_control_email or settings.hr_presence_control_ip): raise ValidationError(_('You should select at least one Advanced Presence Control option.'))
61.1875
1,958
1,637
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import AccessError class Partner(models.Model): _inherit = ['res.partner'] employee_ids = fields.One2many( 'hr.employee', 'address_home_id', string='Employees', groups="hr.group_hr_user", help="Related employees based on their private address") employees_count = fields.Integer(compute='_compute_employees_count', groups="hr.group_hr_user") def name_get(self): """ Override to allow an employee to see its private address in his profile. This avoids to relax access rules on `res.parter` and to add an `ir.rule`. (advantage in both security and performance). Use a try/except instead of systematically checking to minimize the impact on performance. """ try: return super(Partner, self).name_get() except AccessError as e: if len(self) == 1 and self in self.env.user.employee_ids.mapped('address_home_id'): return super(Partner, self.sudo()).name_get() raise e def _compute_employees_count(self): for partner in self: partner.employees_count = len(partner.employee_ids) def action_open_employees(self): self.ensure_one() return { 'name': _('Related Employees'), 'type': 'ir.actions.act_window', 'res_model': 'hr.employee', 'view_mode': 'kanban,tree,form', 'domain': [('id', 'in', self.employee_ids.ids)], }
39.926829
1,637
10,125
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from ast import literal_eval from odoo import api, fields, models from pytz import timezone, UTC, utc from datetime import timedelta from odoo.tools import format_time class HrEmployeeBase(models.AbstractModel): _name = "hr.employee.base" _description = "Basic Employee" _order = 'name' name = fields.Char() active = fields.Boolean("Active") color = fields.Integer('Color Index', default=0) department_id = fields.Many2one('hr.department', 'Department', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") job_id = fields.Many2one('hr.job', 'Job Position', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") job_title = fields.Char("Job Title", compute="_compute_job_title", store=True, readonly=False) company_id = fields.Many2one('res.company', 'Company') address_id = fields.Many2one('res.partner', 'Work Address', compute="_compute_address_id", store=True, readonly=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") work_phone = fields.Char('Work Phone', compute="_compute_phones", store=True, readonly=False) mobile_phone = fields.Char('Work Mobile') work_email = fields.Char('Work Email') work_location_id = fields.Many2one('hr.work.location', 'Work Location', compute="_compute_work_location_id", store=True, readonly=False, domain="[('address_id', '=', address_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]") user_id = fields.Many2one('res.users') resource_id = fields.Many2one('resource.resource') resource_calendar_id = fields.Many2one('resource.calendar', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") parent_id = fields.Many2one('hr.employee', 'Manager', compute="_compute_parent_id", store=True, readonly=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") coach_id = fields.Many2one( 'hr.employee', 'Coach', compute='_compute_coach', store=True, readonly=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", help='Select the "Employee" who is the coach of this employee.\n' 'The "Coach" has no specific rights or responsibilities by default.') tz = fields.Selection( string='Timezone', related='resource_id.tz', readonly=False, help="This field is used in order to define in which timezone the resources will work.") hr_presence_state = fields.Selection([ ('present', 'Present'), ('absent', 'Absent'), ('to_define', 'To Define')], compute='_compute_presence_state', default='to_define') last_activity = fields.Date(compute="_compute_last_activity") last_activity_time = fields.Char(compute="_compute_last_activity") hr_icon_display = fields.Selection([ ('presence_present', 'Present'), ('presence_absent_active', 'Present but not active'), ('presence_absent', 'Absent'), ('presence_to_define', 'To define'), ('presence_undetermined', 'Undetermined')], compute='_compute_presence_icon') employee_type = fields.Selection([ ('employee', 'Employee'), ('student', 'Student'), ('trainee', 'Trainee'), ('contractor', 'Contractor'), ('freelance', 'Freelancer'), ], string='Employee Type', default='employee', required=True, help="The employee type. Although the primary purpose may seem to categorize employees, this field has also an impact in the Contract History. Only Employee type is supposed to be under contract and will have a Contract History.") @api.depends('user_id.im_status') def _compute_presence_state(self): """ This method is overritten in several other modules which add additional presence criterions. e.g. hr_attendance, hr_holidays """ # Check on login check_login = literal_eval(self.env['ir.config_parameter'].sudo().get_param('hr.hr_presence_control_login', 'False')) employee_to_check_working = self.filtered(lambda e: e.user_id.im_status == 'offline') working_now_list = employee_to_check_working._get_employee_working_now() for employee in self: state = 'to_define' if check_login: if employee.user_id.im_status == 'online': state = 'present' elif employee.user_id.im_status == 'offline' and employee.id not in working_now_list: state = 'absent' employee.hr_presence_state = state @api.depends('user_id') def _compute_last_activity(self): presences = self.env['bus.presence'].search_read([('user_id', 'in', self.mapped('user_id').ids)], ['user_id', 'last_presence']) # transform the result to a dict with this format {user.id: last_presence} presences = {p['user_id'][0]: p['last_presence'] for p in presences} for employee in self: tz = employee.tz last_presence = presences.get(employee.user_id.id, False) if last_presence: last_activity_datetime = last_presence.replace(tzinfo=UTC).astimezone(timezone(tz)).replace(tzinfo=None) employee.last_activity = last_activity_datetime.date() if employee.last_activity == fields.Date.today(): employee.last_activity_time = format_time(self.env, last_presence, time_format='short') else: employee.last_activity_time = False else: employee.last_activity = False employee.last_activity_time = False @api.depends('parent_id') def _compute_coach(self): for employee in self: manager = employee.parent_id previous_manager = employee._origin.parent_id if manager and (employee.coach_id == previous_manager or not employee.coach_id): employee.coach_id = manager elif not employee.coach_id: employee.coach_id = False @api.depends('job_id') def _compute_job_title(self): for employee in self.filtered('job_id'): employee.job_title = employee.job_id.name @api.depends('address_id') def _compute_phones(self): for employee in self: if employee.address_id and employee.address_id.phone: employee.work_phone = employee.address_id.phone else: employee.work_phone = False @api.depends('company_id') def _compute_address_id(self): for employee in self: address = employee.company_id.partner_id.address_get(['default']) employee.address_id = address['default'] if address else False @api.depends('department_id') def _compute_parent_id(self): for employee in self.filtered('department_id.manager_id'): employee.parent_id = employee.department_id.manager_id @api.depends('resource_calendar_id', 'hr_presence_state') def _compute_presence_icon(self): """ This method compute the state defining the display icon in the kanban view. It can be overriden to add other possibilities, like time off or attendances recordings. """ working_now_list = self.filtered(lambda e: e.hr_presence_state == 'present')._get_employee_working_now() for employee in self: if employee.hr_presence_state == 'present': if employee.id in working_now_list: icon = 'presence_present' else: icon = 'presence_absent_active' elif employee.hr_presence_state == 'absent': # employee is not in the working_now_list and he has a user_id icon = 'presence_absent' else: # without attendance, default employee state is 'to_define' without confirmed presence/absence # we need to check why they are not there if employee.user_id: # Display an orange icon on internal users. icon = 'presence_to_define' else: # We don't want non-user employee to have icon. icon = 'presence_undetermined' employee.hr_icon_display = icon @api.depends('address_id') def _compute_work_location_id(self): to_reset = self.filtered(lambda e: e.address_id != e.work_location_id.address_id) to_reset.work_location_id = False @api.model def _get_employee_working_now(self): working_now = [] # We loop over all the employee tz and the resource calendar_id to detect working hours in batch. all_employee_tz = set(self.mapped('tz')) for tz in all_employee_tz: employee_ids = self.filtered(lambda e: e.tz == tz) resource_calendar_ids = employee_ids.mapped('resource_calendar_id') for calendar_id in resource_calendar_ids: res_employee_ids = employee_ids.filtered(lambda e: e.resource_calendar_id.id == calendar_id.id) start_dt = fields.Datetime.now() stop_dt = start_dt + timedelta(hours=1) from_datetime = utc.localize(start_dt).astimezone(timezone(tz or 'UTC')) to_datetime = utc.localize(stop_dt).astimezone(timezone(tz or 'UTC')) # Getting work interval of the first is working. Functions called on resource_calendar_id # are waiting for singleton work_interval = res_employee_ids[0].resource_calendar_id._work_intervals_batch(from_datetime, to_datetime)[False] # Employee that is not supposed to work have empty items. if len(work_interval._items) > 0: # The employees should be working now according to their work schedule working_now += res_employee_ids.ids return working_now
52.46114
10,125
1,105
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Channel(models.Model): _inherit = 'mail.channel' subscription_department_ids = fields.Many2many( 'hr.department', string='HR Departments', help='Automatically subscribe members of those departments to the channel.') def _subscribe_users_automatically_get_members(self): """ Auto-subscribe members of a department to a channel """ new_members = super(Channel, self)._subscribe_users_automatically_get_members() for channel in self: new_members[channel.id] = list( set(new_members[channel.id]) | set((channel.subscription_department_ids.member_ids.user_id.partner_id.filtered(lambda p: p.active) - channel.channel_partner_ids).ids) ) return new_members def write(self, vals): res = super(Channel, self).write(vals) if vals.get('subscription_department_ids'): self._subscribe_users_automatically() return res
39.464286
1,105
731
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "pos_cache", 'summary': "Enable a cache on products for a lower POS loading time.", 'description': """ This creates a product cache per POS config. It drastically lowers the time it takes to load a POS session with a lot of products. """, 'category': 'Sales/Point of Sale', 'version': '1.0', 'depends': ['point_of_sale'], 'data': [ 'data/pos_cache_data.xml', 'security/ir.model.access.csv', 'views/pos_cache_views.xml', ], 'assets': { 'point_of_sale.assets': [ 'pos_cache/static/**/*', ], }, 'license': 'LGPL-3', }
27.074074
731
3,364
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import json from ast import literal_eval from odoo import models, fields, api from odoo.tools import date_utils class pos_cache(models.Model): _name = 'pos.cache' _description = 'Point of Sale Cache' cache = fields.Binary(attachment=True) product_domain = fields.Text(required=True) product_fields = fields.Text(required=True) config_id = fields.Many2one('pos.config', ondelete='cascade', required=True) compute_user_id = fields.Many2one('res.users', 'Cache compute user', required=True) @api.model def refresh_all_caches(self): self.env['pos.cache'].search([]).refresh_cache() def refresh_cache(self): for cache in self: Product = self.env['product.product'].with_user(cache.compute_user_id.id) products = Product.search(cache.get_product_domain()) prod_ctx = products.with_context(pricelist=cache.config_id.pricelist_id.id, display_default_code=False, lang=cache.compute_user_id.lang) res = prod_ctx.read(cache.get_product_fields()) cache.write({ 'cache': base64.encodebytes(json.dumps(res, default=date_utils.json_default).encode('utf-8')), }) @api.model def get_product_domain(self): return literal_eval(self.product_domain) @api.model def get_product_fields(self): return literal_eval(self.product_fields) def cache2json(self): return json.loads(base64.decodebytes(self.cache).decode('utf-8')) class pos_config(models.Model): _inherit = 'pos.config' @api.depends('cache_ids') def _get_oldest_cache_time(self): for cache in self: pos_cache = self.env['pos.cache'] oldest_cache = pos_cache.search([('config_id', '=', cache.id)], order='write_date', limit=1) cache.oldest_cache_time = oldest_cache.write_date cache_ids = fields.One2many('pos.cache', 'config_id') oldest_cache_time = fields.Datetime(compute='_get_oldest_cache_time', string='Oldest cache time', readonly=True) limit_products_per_request = fields.Integer(compute='_compute_limit_products_per_request') def _compute_limit_products_per_request(self): limit = self.env['ir.config_parameter'].sudo().get_param('pos_cache.limit_products_per_request', 0) self.update({'limit_products_per_request': int(limit)}) def get_products_from_cache(self, fields, domain): fields_str = str(fields) domain_str = str(domain) pos_cache = self.env['pos.cache'] cache_for_user = pos_cache.search([ ('id', 'in', self.cache_ids.ids), ('compute_user_id', '=', self.env.uid), ('product_domain', '=', domain_str), ('product_fields', '=', fields_str), ]) if not cache_for_user: cache_for_user = pos_cache.create({ 'config_id': self.id, 'product_domain': domain_str, 'product_fields': fields_str, 'compute_user_id': self.env.uid }) cache_for_user.refresh_cache() return cache_for_user.cache2json() def delete_cache(self): # throw away the old caches self.cache_ids.unlink()
36.967033
3,364