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
10,592
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.tools.float_utils import float_compare, float_is_zero class AccountMove(models.Model): _inherit = 'account.move' def _stock_account_prepare_anglo_saxon_in_lines_vals(self): ''' Prepare values used to create the journal items (account.move.line) corresponding to the price difference lines for vendor bills. Example: Buy a product having a cost of 9 and a supplier price of 10 and being a storable product and having a perpetual valuation in FIFO. The vendor bill's journal entries looks like: Account | Debit | Credit --------------------------------------------------------------- 101120 Stock Interim Account (Received) | 10.0 | --------------------------------------------------------------- 101100 Account Payable | | 10.0 --------------------------------------------------------------- This method computes values used to make two additional journal items: --------------------------------------------------------------- 101120 Stock Interim Account (Received) | | 1.0 --------------------------------------------------------------- xxxxxx Price Difference Account | 1.0 | --------------------------------------------------------------- :return: A list of Python dictionary to be passed to env['account.move.line'].create. ''' lines_vals_list = [] price_unit_prec = self.env['decimal.precision'].precision_get('Product Price') for move in self: if move.move_type not in ('in_invoice', 'in_refund', 'in_receipt') or not move.company_id.anglo_saxon_accounting: continue move = move.with_company(move.company_id) for line in move.invoice_line_ids: # Filter out lines being not eligible for price difference. if line.product_id.type != 'product' or line.product_id.valuation != 'real_time': continue # Retrieve accounts needed to generate the price difference. debit_pdiff_account = line.product_id.property_account_creditor_price_difference \ or line.product_id.categ_id.property_account_creditor_price_difference_categ debit_pdiff_account = move.fiscal_position_id.map_account(debit_pdiff_account) if not debit_pdiff_account: continue # Retrieve stock valuation moves. valuation_stock_moves = self.env['stock.move'].search([ ('purchase_line_id', '=', line.purchase_line_id.id), ('state', '=', 'done'), ('product_qty', '!=', 0.0), ]) if line.purchase_line_id else self.env['stock.move'] if move.move_type == 'in_refund': valuation_stock_moves = valuation_stock_moves.filtered(lambda stock_move: stock_move._is_out()) else: valuation_stock_moves = valuation_stock_moves.filtered(lambda stock_move: stock_move._is_in()) if line.product_id.cost_method != 'standard' and line.purchase_line_id: po_currency = line.purchase_line_id.currency_id po_company = line.purchase_line_id.company_id if valuation_stock_moves: valuation_price_unit_total, valuation_total_qty = valuation_stock_moves._get_valuation_price_and_qty(line, move.currency_id) valuation_price_unit = valuation_price_unit_total / valuation_total_qty valuation_price_unit = line.product_id.uom_id._compute_price(valuation_price_unit, line.product_uom_id) elif line.product_id.cost_method == 'fifo': # In this condition, we have a real price-valuated product which has not yet been received valuation_price_unit = po_currency._convert( line.purchase_line_id.price_unit, move.currency_id, po_company, move.date, round=False, ) else: # For average/fifo/lifo costing method, fetch real cost price from incoming moves. price_unit = line.purchase_line_id.product_uom._compute_price(line.purchase_line_id.price_unit, line.product_uom_id) valuation_price_unit = po_currency._convert( price_unit, move.currency_id, po_company, move.date, round=False ) else: # Valuation_price unit is always expressed in invoice currency, so that it can always be computed with the good rate price_unit = line.product_id.uom_id._compute_price(line.product_id.standard_price, line.product_uom_id) valuation_date = valuation_stock_moves and max(valuation_stock_moves.mapped('date')) or move.date valuation_price_unit = line.company_currency_id._convert( price_unit, move.currency_id, move.company_id, valuation_date, round=False ) price_unit = line.price_unit * (1 - (line.discount or 0.0) / 100.0) if line.tax_ids: # We do not want to round the price unit since : # - It does not follow the currency precision # - It may include a discount # Since compute_all still rounds the total, we use an ugly workaround: # shift the decimal part using a fixed quantity to avoid rounding issues prec = 1e+6 price_unit *= prec price_unit = line.tax_ids.with_context(round=False, force_sign=move._get_tax_force_sign()).compute_all( price_unit, currency=move.currency_id, quantity=1.0, is_refund=move.move_type == 'in_refund')['total_excluded'] price_unit /= prec price_unit_val_dif = price_unit - valuation_price_unit price_subtotal = line.quantity * price_unit_val_dif # We consider there is a price difference if: # - price unit is not zero with respect to product price decimal precision. # - subtotal is not zero with respect to move currency precision. # - no discount was applied, as we can't round the price unit anymore if ( not move.currency_id.is_zero(price_subtotal) and not float_is_zero(price_unit_val_dif, precision_digits=price_unit_prec) and float_compare(line["price_unit"], line.price_unit, precision_digits=price_unit_prec) == 0 ): # Add price difference account line. vals = { 'name': line.name[:64], 'move_id': move.id, 'partner_id': line.partner_id.id or move.commercial_partner_id.id, 'currency_id': line.currency_id.id, 'product_id': line.product_id.id, 'product_uom_id': line.product_uom_id.id, 'quantity': line.quantity, 'price_unit': price_unit_val_dif, 'price_subtotal': line.quantity * price_unit_val_dif, 'account_id': debit_pdiff_account.id, 'analytic_account_id': line.analytic_account_id.id, 'analytic_tag_ids': [(6, 0, line.analytic_tag_ids.ids)], 'exclude_from_invoice_tab': True, 'is_anglo_saxon_line': True, } vals.update(line._get_fields_onchange_subtotal(price_subtotal=vals['price_subtotal'])) lines_vals_list.append(vals) # Correct the amount of the current line. vals = { 'name': line.name[:64], 'move_id': move.id, 'partner_id': line.partner_id.id or move.commercial_partner_id.id, 'currency_id': line.currency_id.id, 'product_id': line.product_id.id, 'product_uom_id': line.product_uom_id.id, 'quantity': line.quantity, 'price_unit': -price_unit_val_dif, 'price_subtotal': line.quantity * -price_unit_val_dif, 'account_id': line.account_id.id, 'analytic_account_id': line.analytic_account_id.id, 'analytic_tag_ids': [(6, 0, line.analytic_tag_ids.ids)], 'exclude_from_invoice_tab': True, 'is_anglo_saxon_line': True, } vals.update(line._get_fields_onchange_subtotal(price_subtotal=vals['price_subtotal'])) lines_vals_list.append(vals) return lines_vals_list def _post(self, soft=True): # OVERRIDE # Create additional price difference lines for vendor bills. if self._context.get('move_reverse_cancel'): return super()._post(soft) self.env['account.move.line'].create(self._stock_account_prepare_anglo_saxon_in_lines_vals()) return super()._post(soft) def _stock_account_get_last_step_stock_moves(self): """ Overridden from stock_account. Returns the stock moves associated to this invoice.""" rslt = super(AccountMove, self)._stock_account_get_last_step_stock_moves() for invoice in self.filtered(lambda x: x.move_type == 'in_invoice'): rslt += invoice.mapped('invoice_line_ids.purchase_line_id.move_ids').filtered(lambda x: x.state == 'done' and x.location_id.usage == 'supplier') for invoice in self.filtered(lambda x: x.move_type == 'in_refund'): rslt += invoice.mapped('invoice_line_ids.purchase_line_id.move_ids').filtered(lambda x: x.state == 'done' and x.location_dest_id.usage == 'supplier') return rslt
57.879781
10,592
350
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 ResCompany(models.Model): _inherit = 'res.company' days_to_purchase = fields.Float( string='Days to Purchase', help="Days needed to confirm a PO, define when a PO should be validated")
29.166667
350
5,344
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.osv import expression class ProductTemplate(models.Model): _name = 'product.template' _inherit = 'product.template' @api.model def _get_buy_route(self): buy_route = self.env.ref('purchase_stock.route_warehouse0_buy', raise_if_not_found=False) if buy_route: return self.env['stock.location.route'].search([('id', '=', buy_route.id)]).ids return [] route_ids = fields.Many2many(default=lambda self: self._get_buy_route()) class ProductProduct(models.Model): _name = 'product.product' _inherit = 'product.product' purchase_order_line_ids = fields.One2many('purchase.order.line', 'product_id', help='Technical: used to compute quantities.') def _get_quantity_in_progress(self, location_ids=False, warehouse_ids=False): if not location_ids: location_ids = [] if not warehouse_ids: warehouse_ids = [] qty_by_product_location, qty_by_product_wh = super()._get_quantity_in_progress(location_ids, warehouse_ids) domain = self._get_lines_domain(location_ids, warehouse_ids) groups = self.env['purchase.order.line'].read_group(domain, ['product_id', 'product_qty', 'order_id', 'product_uom', 'orderpoint_id'], ['order_id', 'product_id', 'product_uom', 'orderpoint_id'], orderby='id', lazy=False) for group in groups: if group.get('orderpoint_id'): location = self.env['stock.warehouse.orderpoint'].browse(group['orderpoint_id'][:1]).location_id else: order = self.env['purchase.order'].browse(group['order_id'][0]) location = order.picking_type_id.default_location_dest_id product = self.env['product.product'].browse(group['product_id'][0]) uom = self.env['uom.uom'].browse(group['product_uom'][0]) product_qty = uom._compute_quantity(group['product_qty'], product.uom_id, round=False) qty_by_product_location[(product.id, location.id)] += product_qty qty_by_product_wh[(product.id, location.warehouse_id.id)] += product_qty return qty_by_product_location, qty_by_product_wh def _get_lines_domain(self, location_ids=False, warehouse_ids=False): domain = [] rfq_domain = [ ('state', 'in', ('draft', 'sent', 'to approve')), ('product_id', 'in', self.ids) ] if location_ids: domain = expression.AND([rfq_domain, [ '|', ('order_id.picking_type_id.default_location_dest_id', 'in', location_ids), '&', ('move_dest_ids', '=', False), ('orderpoint_id.location_id', 'in', location_ids) ]]) if warehouse_ids: wh_domain = expression.AND([rfq_domain, [ '|', ('order_id.picking_type_id.warehouse_id', 'in', warehouse_ids), '&', ('move_dest_ids', '=', False), ('orderpoint_id.warehouse_id', 'in', warehouse_ids) ]]) domain = expression.OR([domain, wh_domain]) return domain class SupplierInfo(models.Model): _inherit = 'product.supplierinfo' last_purchase_date = fields.Date('Last Purchase', compute='_compute_last_purchase_date') show_set_supplier_button = fields.Boolean( 'Show Set Supplier Button', compute='_compute_show_set_supplier_button') def _compute_last_purchase_date(self): self.last_purchase_date = False purchases = self.env['purchase.order'].search([ ('state', 'in', ('purchase', 'done')), ('order_line.product_id', 'in', self.product_tmpl_id.product_variant_ids.ids), ('partner_id', 'in', self.name.ids), ], order='date_order') for supplier in self: products = supplier.product_tmpl_id.product_variant_ids for purchase in purchases: if purchase.partner_id != supplier.name: continue if not (products & purchase.order_line.product_id): continue supplier.last_purchase_date = purchase.date_order break def _compute_show_set_supplier_button(self): self.show_set_supplier_button = True orderpoint_id = self.env.context.get('default_orderpoint_id') orderpoint = self.env['stock.warehouse.orderpoint'].browse(orderpoint_id) if orderpoint_id: self.filtered( lambda s: s.id == orderpoint.supplier_id.id ).show_set_supplier_button = False def action_set_supplier(self): self.ensure_one() orderpoint_id = self.env.context.get('orderpoint_id') orderpoint = self.env['stock.warehouse.orderpoint'].browse(orderpoint_id) if not orderpoint: return orderpoint.route_id = self.env['stock.rule'].search([('action', '=', 'buy')], limit=1).route_id.id orderpoint.supplier_id = self if orderpoint.qty_to_order < self.min_qty: orderpoint.qty_to_order = self.min_qty
44.165289
5,344
18,364
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 datetime from dateutil.relativedelta import relativedelta from itertools import groupby from odoo.tools import float_compare from odoo import api, fields, models, SUPERUSER_ID, _ from odoo.addons.stock.models.stock_rule import ProcurementException class StockRule(models.Model): _inherit = 'stock.rule' action = fields.Selection(selection_add=[ ('buy', 'Buy') ], ondelete={'buy': 'cascade'}) def _get_message_dict(self): message_dict = super(StockRule, self)._get_message_dict() dummy, destination, dummy = self._get_message_values() message_dict.update({ 'buy': _('When products are needed in <b>%s</b>, <br/> ' 'a request for quotation is created to fulfill the need.<br/>' 'Note: This rule will be used in combination with the rules<br/>' 'of the reception route(s)') % (destination) }) return message_dict @api.depends('action') def _compute_picking_type_code_domain(self): remaining = self.browse() for rule in self: if rule.action == 'buy': rule.picking_type_code_domain = 'incoming' else: remaining |= rule super(StockRule, remaining)._compute_picking_type_code_domain() @api.onchange('action') def _onchange_action(self): if self.action == 'buy': self.location_src_id = False @api.model def _run_buy(self, procurements): procurements_by_po_domain = defaultdict(list) errors = [] for procurement, rule in procurements: # Get the schedule date in order to find a valid seller procurement_date_planned = fields.Datetime.from_string(procurement.values['date_planned']) supplier = False if procurement.values.get('supplierinfo_id'): supplier = procurement.values['supplierinfo_id'] elif procurement.values.get('orderpoint_id') and procurement.values['orderpoint_id'].supplier_id: supplier = procurement.values['orderpoint_id'].supplier_id else: supplier = procurement.product_id.with_company(procurement.company_id.id)._select_seller( partner_id=procurement.values.get("supplierinfo_name"), quantity=procurement.product_qty, date=procurement_date_planned.date(), uom_id=procurement.product_uom) # Fall back on a supplier for which no price may be defined. Not ideal, but better than # blocking the user. supplier = supplier or procurement.product_id._prepare_sellers(False).filtered( lambda s: not s.company_id or s.company_id == procurement.company_id )[:1] if not supplier: msg = _('There is no matching vendor price to generate the purchase order for product %s (no vendor defined, minimum quantity not reached, dates not valid, ...). Go on the product form and complete the list of vendors.') % (procurement.product_id.display_name) errors.append((procurement, msg)) partner = supplier.name # we put `supplier_info` in values for extensibility purposes procurement.values['supplier'] = supplier procurement.values['propagate_cancel'] = rule.propagate_cancel domain = rule._make_po_get_domain(procurement.company_id, procurement.values, partner) procurements_by_po_domain[domain].append((procurement, rule)) if errors: raise ProcurementException(errors) for domain, procurements_rules in procurements_by_po_domain.items(): # Get the procurements for the current domain. # Get the rules for the current domain. Their only use is to create # the PO if it does not exist. procurements, rules = zip(*procurements_rules) # Get the set of procurement origin for the current domain. origins = set([p.origin for p in procurements]) # Check if a PO exists for the current domain. po = self.env['purchase.order'].sudo().search([dom for dom in domain], limit=1) company_id = procurements[0].company_id if not po: positive_values = [p.values for p in procurements if float_compare(p.product_qty, 0.0, precision_rounding=p.product_uom.rounding) >= 0] if positive_values: # We need a rule to generate the PO. However the rule generated # the same domain for PO and the _prepare_purchase_order method # should only uses the common rules's fields. vals = rules[0]._prepare_purchase_order(company_id, origins, positive_values) # The company_id is the same for all procurements since # _make_po_get_domain add the company in the domain. # We use SUPERUSER_ID since we don't want the current user to be follower of the PO. # Indeed, the current user may be a user without access to Purchase, or even be a portal user. po = self.env['purchase.order'].with_company(company_id).with_user(SUPERUSER_ID).create(vals) else: # If a purchase order is found, adapt its `origin` field. if po.origin: missing_origins = origins - set(po.origin.split(', ')) if missing_origins: po.write({'origin': po.origin + ', ' + ', '.join(missing_origins)}) else: po.write({'origin': ', '.join(origins)}) procurements_to_merge = self._get_procurements_to_merge(procurements) procurements = self._merge_procurements(procurements_to_merge) po_lines_by_product = {} grouped_po_lines = groupby(po.order_line.filtered(lambda l: not l.display_type and l.product_uom == l.product_id.uom_po_id).sorted(lambda l: l.product_id.id), key=lambda l: l.product_id.id) for product, po_lines in grouped_po_lines: po_lines_by_product[product] = self.env['purchase.order.line'].concat(*list(po_lines)) po_line_values = [] for procurement in procurements: po_lines = po_lines_by_product.get(procurement.product_id.id, self.env['purchase.order.line']) po_line = po_lines._find_candidate(*procurement) if po_line: # If the procurement can be merge in an existing line. Directly # write the new values on it. vals = self._update_purchase_order_line(procurement.product_id, procurement.product_qty, procurement.product_uom, company_id, procurement.values, po_line) po_line.sudo().write(vals) else: if float_compare(procurement.product_qty, 0, precision_rounding=procurement.product_uom.rounding) <= 0: # If procurement contains negative quantity, don't create a new line that would contain negative qty continue # If it does not exist a PO line for current procurement. # Generate the create values for it and add it to a list in # order to create it in batch. partner = procurement.values['supplier'].name po_line_values.append(self.env['purchase.order.line']._prepare_purchase_order_line_from_procurement( procurement.product_id, procurement.product_qty, procurement.product_uom, procurement.company_id, procurement.values, po)) # Check if we need to advance the order date for the new line order_date_planned = procurement.values['date_planned'] - relativedelta( days=procurement.values['supplier'].delay) if fields.Date.to_date(order_date_planned) < fields.Date.to_date(po.date_order): po.date_order = order_date_planned self.env['purchase.order.line'].sudo().create(po_line_values) def _get_lead_days(self, product, **values): """Add the company security lead time, days to purchase and the supplier delay to the cumulative delay and cumulative description. The days to purchase and company lead time are always displayed for onboarding purpose in order to indicate that those options are available. """ delay, delay_description = super()._get_lead_days(product, **values) bypass_delay_description = self.env.context.get('bypass_delay_description') buy_rule = self.filtered(lambda r: r.action == 'buy') seller = 'supplierinfo' in values and values['supplierinfo'] or product.with_company(buy_rule.company_id)._select_seller(quantity=None) if not buy_rule or not seller: return delay, delay_description buy_rule.ensure_one() supplier_delay = seller[0].delay if supplier_delay and not bypass_delay_description: delay_description.append((_('Vendor Lead Time'), _('+ %d day(s)', supplier_delay))) security_delay = buy_rule.picking_type_id.company_id.po_lead if not bypass_delay_description: delay_description.append((_('Purchase Security Lead Time'), _('+ %d day(s)', security_delay))) days_to_purchase = buy_rule.company_id.days_to_purchase if not bypass_delay_description: delay_description.append((_('Days to Purchase'), _('+ %d day(s)', days_to_purchase))) return delay + supplier_delay + security_delay + days_to_purchase, delay_description @api.model def _get_procurements_to_merge_groupby(self, procurement): # Do not group procument from different orderpoint. 1. _quantity_in_progress # directly depends from the orderpoint_id on the line. 2. The stock move # generated from the order line has the orderpoint's location as # destination location. In case of move_dest_ids those two points are not # necessary anymore since those values are taken from destination moves. return procurement.product_id, procurement.product_uom, procurement.values['propagate_cancel'],\ procurement.values.get('product_description_variants'),\ (procurement.values.get('orderpoint_id') and not procurement.values.get('move_dest_ids')) and procurement.values['orderpoint_id'] @api.model def _get_procurements_to_merge_sorted(self, procurement): return procurement.product_id.id, procurement.product_uom.id, procurement.values['propagate_cancel'],\ procurement.values.get('product_description_variants'),\ (procurement.values.get('orderpoint_id') and not procurement.values.get('move_dest_ids')) and procurement.values['orderpoint_id'] @api.model def _get_procurements_to_merge(self, procurements): """ Get a list of procurements values and create groups of procurements that would use the same purchase order line. params procurements_list list: procurements requests (not ordered nor sorted). return list: procurements requests grouped by their product_id. """ procurements_to_merge = [] for k, procurements in groupby(sorted(procurements, key=self._get_procurements_to_merge_sorted), key=self._get_procurements_to_merge_groupby): procurements_to_merge.append(list(procurements)) return procurements_to_merge @api.model def _merge_procurements(self, procurements_to_merge): """ Merge the quantity for procurements requests that could use the same order line. params similar_procurements list: list of procurements that have been marked as 'alike' from _get_procurements_to_merge method. return a list of procurements values where values of similar_procurements list have been merged. """ merged_procurements = [] for procurements in procurements_to_merge: quantity = 0 move_dest_ids = self.env['stock.move'] orderpoint_id = self.env['stock.warehouse.orderpoint'] for procurement in procurements: if procurement.values.get('move_dest_ids'): move_dest_ids |= procurement.values['move_dest_ids'] if not orderpoint_id and procurement.values.get('orderpoint_id'): orderpoint_id = procurement.values['orderpoint_id'] quantity += procurement.product_qty # The merged procurement can be build from an arbitrary procurement # since they were mark as similar before. Only the quantity and # some keys in values are updated. values = dict(procurement.values) values.update({ 'move_dest_ids': move_dest_ids, 'orderpoint_id': orderpoint_id, }) merged_procurement = self.env['procurement.group'].Procurement( procurement.product_id, quantity, procurement.product_uom, procurement.location_id, procurement.name, procurement.origin, procurement.company_id, values ) merged_procurements.append(merged_procurement) return merged_procurements def _update_purchase_order_line(self, product_id, product_qty, product_uom, company_id, values, line): partner = values['supplier'].name procurement_uom_po_qty = product_uom._compute_quantity(product_qty, product_id.uom_po_id) seller = product_id.with_company(company_id)._select_seller( partner_id=partner, quantity=line.product_qty + procurement_uom_po_qty, date=line.order_id.date_order and line.order_id.date_order.date(), uom_id=product_id.uom_po_id) price_unit = self.env['account.tax']._fix_tax_included_price_company(seller.price, line.product_id.supplier_taxes_id, line.taxes_id, company_id) if seller else 0.0 if price_unit and seller and line.order_id.currency_id and seller.currency_id != line.order_id.currency_id: price_unit = seller.currency_id._convert( price_unit, line.order_id.currency_id, line.order_id.company_id, fields.Date.today()) res = { 'product_qty': line.product_qty + procurement_uom_po_qty, 'price_unit': price_unit, 'move_dest_ids': [(4, x.id) for x in values.get('move_dest_ids', [])] } orderpoint_id = values.get('orderpoint_id') if orderpoint_id: res['orderpoint_id'] = orderpoint_id.id return res def _prepare_purchase_order(self, company_id, origins, values): """ Create a purchase order for procuremets that share the same domain returned by _make_po_get_domain. params values: values of procurements params origins: procuremets origins to write on the PO """ purchase_date = min([fields.Datetime.from_string(value['date_planned']) - relativedelta(days=int(value['supplier'].delay)) for value in values]) # Since the procurements are grouped if they share the same domain for # PO but the PO does not exist. In this case it will create the PO from # the common procurements values. The common values are taken from an # arbitrary procurement. In this case the first. values = values[0] partner = values['supplier'].name fpos = self.env['account.fiscal.position'].with_company(company_id).get_fiscal_position(partner.id) gpo = self.group_propagation_option group = (gpo == 'fixed' and self.group_id.id) or \ (gpo == 'propagate' and values.get('group_id') and values['group_id'].id) or False return { 'partner_id': partner.id, 'user_id': False, 'picking_type_id': self.picking_type_id.id, 'company_id': company_id.id, 'currency_id': partner.with_company(company_id).property_purchase_currency_id.id or company_id.currency_id.id, 'dest_address_id': values.get('partner_id', False), 'origin': ', '.join(origins), 'payment_term_id': partner.with_company(company_id).property_supplier_payment_term_id.id, 'date_order': purchase_date, 'fiscal_position_id': fpos.id, 'group_id': group } def _make_po_get_domain(self, company_id, values, partner): gpo = self.group_propagation_option group = (gpo == 'fixed' and self.group_id) or \ (gpo == 'propagate' and 'group_id' in values and values['group_id']) or False domain = ( ('partner_id', '=', partner.id), ('state', '=', 'draft'), ('picking_type_id', '=', self.picking_type_id.id), ('company_id', '=', company_id.id), ('user_id', '=', False), ) delta_days = self.env['ir.config_parameter'].sudo().get_param('purchase_stock.delta_days_merge') if values.get('orderpoint_id') and delta_days is not False: procurement_date = fields.Date.to_date(values['date_planned']) - relativedelta(days=int(values['supplier'].delay)) delta_days = int(delta_days) domain += ( ('date_order', '<=', datetime.combine(procurement_date + relativedelta(days=delta_days), datetime.max.time())), ('date_order', '>=', datetime.combine(procurement_date - relativedelta(days=delta_days), datetime.min.time())) ) if group: domain += (('group_id', '=', group.id),) return domain def _push_prepare_move_copy_values(self, move_to_copy, new_date): res = super(StockRule, self)._push_prepare_move_copy_values(move_to_copy, new_date) res['purchase_line_id'] = None return res
54.654762
18,364
725
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 ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' module_stock_dropshipping = fields.Boolean("Dropshipping") days_to_purchase = fields.Float( related='company_id.days_to_purchase', readonly=False) is_installed_sale = fields.Boolean(string="Is the Sale Module Installed") def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( is_installed_sale=self.env['ir.module.module'].search([('name', '=', 'sale'), ('state', '=', 'installed')]).id, ) return res
34.52381
725
2,335
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta, datetime, time from collections import defaultdict from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' purchase_line_ids = fields.One2many('purchase.order.line', 'partner_id', string="Purchase Lines") on_time_rate = fields.Float( "On-Time Delivery Rate", compute='_compute_on_time_rate', help="Over the past 12 months; the number of products received on time divided by the number of ordered products.") @api.depends('purchase_line_ids') def _compute_on_time_rate(self): order_lines = self.env['purchase.order.line'].search([ ('partner_id', 'in', self.ids), ('date_order', '>', fields.Date.today() - timedelta(365)), ('qty_received', '!=', 0), ('order_id.state', 'in', ['done', 'purchase']), ('product_id', 'in', self.env['product.product'].sudo()._search([('type', '!=', 'service')])) ]) lines_qty_done = defaultdict(lambda: 0) moves = self.env['stock.move'].search([ ('purchase_line_id', 'in', order_lines.ids), ('state', '=', 'done')]) # Fetch fields from db and put them in cache. order_lines.read(['date_planned', 'partner_id', 'product_uom_qty'], load='') moves.read(['purchase_line_id', 'date'], load='') moves = moves.filtered(lambda m: m.date.date() <= m.purchase_line_id.date_planned.date()) for move, qty_done in zip(moves, moves.mapped('quantity_done')): lines_qty_done[move.purchase_line_id.id] += qty_done partner_dict = {} for line in order_lines: on_time, ordered = partner_dict.get(line.partner_id, (0, 0)) ordered += line.product_uom_qty on_time += lines_qty_done[line.id] partner_dict[line.partner_id] = (on_time, ordered) seen_partner = self.env['res.partner'] for partner, numbers in partner_dict.items(): seen_partner |= partner on_time, ordered = numbers partner.on_time_rate = on_time / ordered * 100 if ordered else -1 # use negative number to indicate no data (self - seen_partner).on_time_rate = -1
48.645833
2,335
3,467
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import re from odoo import api, fields, models from odoo.exceptions import UserError from odoo.osv.expression import expression class PurchaseReport(models.Model): _inherit = "purchase.report" picking_type_id = fields.Many2one('stock.warehouse', 'Warehouse', readonly=True) avg_receipt_delay = fields.Float( 'Average Receipt Delay', digits=(16, 2), readonly=True, store=False, # needs store=False to prevent showing up as a 'measure' option help="Amount of time between expected and effective receipt date. Due to a hack needed to calculate this, \ every record will show the same average value, therefore only use this as an aggregated value with group_operator=avg") effective_date = fields.Datetime(string="Effective Date") def _select(self): return super(PurchaseReport, self)._select() + ", spt.warehouse_id as picking_type_id, po.effective_date as effective_date" def _from(self): return super(PurchaseReport, self)._from() + " left join stock_picking_type spt on (spt.id=po.picking_type_id)" def _group_by(self): return super(PurchaseReport, self)._group_by() + ", spt.warehouse_id, effective_date" @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): """ This is a hack to allow us to correctly calculate the average of PO specific date values since the normal report query result will duplicate PO values across its PO lines during joins and lead to incorrect aggregation values. Only the AVG operator is supported for avg_receipt_delay. """ avg_receipt_delay = next((field for field in fields if re.search(r'\bavg_receipt_delay\b', field)), False) if avg_receipt_delay: fields.remove(avg_receipt_delay) if any(field.split(':')[1].split('(')[0] != 'avg' for field in [avg_receipt_delay] if field): raise UserError("Value: 'avg_receipt_delay' should only be used to show an average. If you are seeing this message then it is being accessed incorrectly.") res = [] if fields: res = super(PurchaseReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) if not res and avg_receipt_delay: res = [{}] if avg_receipt_delay: query = """ SELECT AVG(receipt_delay.po_receipt_delay)::decimal(16,2) AS avg_receipt_delay FROM ( SELECT extract(epoch from age(po.effective_date, po.date_planned))/(24*60*60) AS po_receipt_delay FROM purchase_order po WHERE po.id IN ( SELECT "purchase_report"."order_id" FROM %s WHERE %s) ) AS receipt_delay """ subdomain = domain + [('company_id', '=', self.env.company.id), ('effective_date', '!=', False)] subtables, subwhere, subparams = expression(subdomain, self).query.get_sql() self.env.cr.execute(query % (subtables, subwhere), subparams) res[0].update({ '__count': 1, avg_receipt_delay.split(':')[0]: self.env.cr.fetchall()[0][0], }) return res
49.528571
3,467
594
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class ReportStockRule(models.AbstractModel): _inherit = 'report.stock.report_stock_rule' @api.model def _get_rule_loc(self, rule, product_id): """ We override this method to handle buy rules which do not have a location_src_id. """ res = super(ReportStockRule, self)._get_rule_loc(rule, product_id) if rule.action == 'buy': res['source'] = self.env.ref('stock.stock_location_suppliers') return res
34.941176
594
3,492
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 from odoo.exceptions import UserError from odoo.osv.expression import expression class VendorDelayReport(models.Model): _name = "vendor.delay.report" _description = "Vendor Delay Report" _auto = False partner_id = fields.Many2one('res.partner', 'Vendor', readonly=True) product_id = fields.Many2one('product.product', 'Product', readonly=True) category_id = fields.Many2one('product.category', 'Product Category', readonly=True) date = fields.Datetime('Effective Date', readonly=True) qty_total = fields.Float('Total Quantity', readonly=True) qty_on_time = fields.Float('On-Time Quantity', readonly=True) on_time_rate = fields.Float('On-Time Delivery Rate', readonly=True) def init(self): tools.drop_view_if_exists(self.env.cr, 'vendor_delay_report') self.env.cr.execute(""" CREATE OR replace VIEW vendor_delay_report AS( SELECT m.id AS id, m.date AS date, m.purchase_line_id AS purchase_line_id, m.product_id AS product_id, Min(pc.id) AS category_id, Min(po.partner_id) AS partner_id, Min(m.product_qty) AS qty_total, Sum(CASE WHEN (m.state = 'done' and pol.date_planned::date >= m.date::date) THEN (ml.qty_done / ml_uom.factor * pt_uom.factor) ELSE 0 END) AS qty_on_time FROM stock_move m JOIN purchase_order_line pol ON pol.id = m.purchase_line_id JOIN purchase_order po ON po.id = pol.order_id JOIN product_product p ON p.id = m.product_id JOIN product_template pt ON pt.id = p.product_tmpl_id JOIN uom_uom pt_uom ON pt_uom.id = pt.uom_id JOIN product_category pc ON pc.id = pt.categ_id LEFT JOIN stock_move_line ml ON ml.move_id = m.id LEFT JOIN uom_uom ml_uom ON ml_uom.id = ml.product_uom_id GROUP BY m.id )""") @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): if all('on_time_rate' not in field for field in fields): res = super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) return res for field in fields: if 'on_time_rate' not in field: continue fields.remove(field) agg = field.split(':')[1:] if agg and agg[0] != 'sum': raise NotImplementedError('Aggregate functions other than \':sum\' are not allowed.') qty_total = field.replace('on_time_rate', 'qty_total') if qty_total not in fields: fields.append(qty_total) qty_on_time = field.replace('on_time_rate', 'qty_on_time') if qty_on_time not in fields: fields.append(qty_on_time) break res = super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) for group in res: if group['qty_total'] == 0: on_time_rate = 100 else: on_time_rate = group['qty_on_time'] / group['qty_total'] * 100 group.update({'on_time_rate': on_time_rate}) return res
38.8
3,492
1,711
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ReplenishmentReport(models.AbstractModel): _inherit = 'report.stock.report_product_product_replenishment' def _compute_draft_quantity_count(self, product_template_ids, product_variant_ids, wh_location_ids): res = super()._compute_draft_quantity_count(product_template_ids, product_variant_ids, wh_location_ids) domain = [('state', 'in', ['draft', 'sent', 'to approve'])] domain += self._product_purchase_domain(product_template_ids, product_variant_ids) warehouse_id = self.env.context.get('warehouse', False) if warehouse_id: domain += [('order_id.picking_type_id.warehouse_id', '=', warehouse_id)] po_lines = self.env['purchase.order.line'].search(domain) in_sum = sum(po_lines.mapped('product_uom_qty')) res['draft_purchase_qty'] = in_sum res['draft_purchase_orders'] = po_lines.mapped("order_id").sorted(key=lambda po: po.name) res['draft_purchase_orders_matched'] = self.env.context.get('purchase_line_to_match_id') in po_lines.ids res['qty']['in'] += in_sum return res def _product_purchase_domain(self, product_template_ids, product_variant_ids): if product_variant_ids: return [('product_id', 'in', product_variant_ids)] elif product_template_ids: products = self.env['product.product'].search_read( [('product_tmpl_id', 'in', product_template_ids)], ['id'] ) product_ids = [product['id'] for product in products] return [('product_id', 'in', product_ids)]
51.848485
1,711
1,363
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Peru - Accounting', "version": "2.0", 'summary': "PCGE Simplified", 'category': 'Accounting/Localizations/Account Charts', 'author': 'Vauxoo, Odoo', 'website': 'https://www.odoo.com/documentation/15.0/applications/finance/accounting/fiscal_localizations/localizations/peru.html', 'license': 'LGPL-3', 'depends': [ 'base_vat', 'base_address_extended', 'base_address_city', 'l10n_latam_base', 'l10n_latam_invoice_document', 'account_debit_note', ], 'data': [ 'security/ir.model.access.csv', 'views/account_tax_view.xml', 'data/l10n_pe_chart_data.xml', 'data/account.group.template.csv', 'data/account.account.template.csv', 'data/l10n_pe_chart_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_data.xml', 'data/fiscal_position_data.xml', 'data/l10n_latam_document_type_data.xml', 'data/account_chart_template_data.xml', 'data/res.city.csv', 'data/l10n_pe.res.city.district.csv', 'data/res_country_data.xml', 'data/l10n_latam_identification_type_data.xml', ], 'demo': [ 'demo/demo_company.xml', 'demo/demo_partner.xml', ], }
34.948718
1,363
1,350
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models class AccountChartTemplate(models.Model): _inherit = "account.chart.template" @api.model def _get_demo_data_move(self): cid = self.env.company.id model, data = super()._get_demo_data_move() if self.env.company.account_fiscal_country_id.code == "PE": document_type = self.env.ref('l10n_pe.document_type01') data[f'{cid}_demo_invoice_1']['l10n_latam_document_type_id'] = document_type.id data[f'{cid}_demo_invoice_1']['l10n_latam_document_number'] = 'FFI-000001' data[f'{cid}_demo_invoice_2']['l10n_latam_document_type_id'] = document_type.id data[f'{cid}_demo_invoice_2']['l10n_latam_document_number'] = 'FFI-000002' data[f'{cid}_demo_invoice_3']['l10n_latam_document_type_id'] = document_type.id data[f'{cid}_demo_invoice_3']['l10n_latam_document_number'] = 'FFI-000003' data[f'{cid}_demo_invoice_followup']['l10n_latam_document_type_id'] = document_type.id data[f'{cid}_demo_invoice_followup']['l10n_latam_document_number'] = 'FFI-000004' data[f'{cid}_demo_invoice_5']['l10n_latam_document_number'] = '1' data[f'{cid}_demo_invoice_equipment_purchase']['l10n_latam_document_number'] = 'INV-000089' return model, data
54
1,350
309
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class City(models.Model): _inherit = "res.city" l10n_pe_code = fields.Char('Code', help='This code will help with the ' 'identification of each city in Peru.')
34.333333
309
2,420
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class AccountTax(models.Model): _inherit = "account.tax" l10n_pe_edi_tax_code = fields.Selection([ ('1000', 'IGV - General Sales Tax'), ('1016', 'IVAP - Tax on Sale Paddy Rice'), ('2000', 'ISC - Selective Excise Tax'), ('7152', 'ICBPER - Plastic bag tax'), ('9995', 'EXP - Exportation'), ('9996', 'GRA - Free'), ('9997', 'EXO - Exonerated'), ('9998', 'INA - Unaffected'), ('9999', 'OTROS - Other taxes') ], 'EDI peruvian code') l10n_pe_edi_unece_category = fields.Selection([ ('E', 'Exempt from tax'), ('G', 'Free export item, tax not charged'), ('O', 'Services outside scope of tax'), ('S', 'Standard rate'), ('Z', 'Zero rated goods')], 'EDI UNECE code', help="Follow the UN/ECE 5305 standard from the United Nations Economic Commission for Europe for more " "information http://www.unece.org/trade/untdid/d08a/tred/tred5305.htm" ) class AccountTaxTemplate(models.Model): _inherit = "account.tax.template" l10n_pe_edi_tax_code = fields.Selection([ ('1000', 'IGV - General Sales Tax'), ('1016', 'IVAP - Tax on Sale Paddy Rice'), ('2000', 'ISC - Selective Excise Tax'), ('7152', 'ICBPER - Plastic bag tax'), ('9995', 'EXP - Exportation'), ('9996', 'GRA - Free'), ('9997', 'EXO - Exonerated'), ('9998', 'INA - Unaffected'), ('9999', 'OTROS - Other taxes') ], 'EDI peruvian code') l10n_pe_edi_unece_category = fields.Selection([ ('E', 'Exempt from tax'), ('G', 'Free export item, tax not charged'), ('O', 'Services outside scope of tax'), ('S', 'Standard rate'), ('Z', 'Zero rated goods')], 'EDI UNECE code', help="Follow the UN/ECE 5305 standard from the United Nations Economic Commission for Europe for more " "information http://www.unece.org/trade/untdid/d08a/tred/tred5305.htm" ) def _get_tax_vals(self, company, tax_template_to_tax): val = super()._get_tax_vals(company, tax_template_to_tax) val.update({ 'l10n_pe_edi_tax_code': self.l10n_pe_edi_tax_code, 'l10n_pe_edi_unece_category': self.l10n_pe_edi_unece_category, }) return val
39.032258
2,420
245
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields class L10nLatamIdentificationType(models.Model): _inherit = "l10n_latam.identification.type" l10n_pe_vat_code = fields.Char()
27.222222
245
902
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields from odoo.tools.sql import column_exists, create_column class AccountMoveLine(models.Model): _inherit = "account.move.line" l10n_pe_group_id = fields.Many2one("account.group", related="account_id.group_id", store=True) def _auto_init(self): """ Create column to stop ORM from computing it himself (too slow) """ if not column_exists(self.env.cr, self._table, 'l10n_pe_group_id'): create_column(self.env.cr, self._table, 'l10n_pe_group_id', 'int4') self.env.cr.execute(""" UPDATE account_move_line line SET l10n_pe_group_id = account.group_id FROM account_account account WHERE account.id = line.account_id """) return super()._auto_init()
39.217391
902
453
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class L10nPeResCityDistrict(models.Model): _name = 'l10n_pe.res.city.district' _description = 'District' _order = 'name' name = fields.Char(translate=True) city_id = fields.Many2one('res.city', 'City') code = fields.Char( help='This code will help with the identification of each district ' 'in Peru.')
32.357143
453
375
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResCompany(models.Model): _inherit = 'res.company' def _localization_use_documents(self): # OVERRIDE self.ensure_one() return self.account_fiscal_country_id.code == "PE" or super()._localization_use_documents()
31.25
375
723
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details from odoo import fields, models, api class ResPartner(models.Model): _inherit = 'res.partner' l10n_pe_district = fields.Many2one( 'l10n_pe.res.city.district', string='District', help='Districts are part of a province or city.') @api.onchange('l10n_pe_district') def _onchange_l10n_pe_district(self): if self.l10n_pe_district: self.city_id = self.l10n_pe_district.city_id @api.onchange('city_id') def _onchange_l10n_pe_city_id(self): if self.city_id and self.l10n_pe_district.city_id and self.l10n_pe_district.city_id != self.city_id: self.l10n_pe_district = False
36.15
723
329
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Mrp Repairs', 'version': '1.0', 'category': 'Inventory/Inventory', 'depends': ['repair', 'mrp'], 'installable': True, 'auto_install': True, 'application': False, 'license': 'LGPL-3', }
23.5
329
5,387
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form, tagged from odoo.addons.mrp.tests.common import TestMrpCommon @tagged('post_install', '-at_install') class TestRepairTraceability(TestMrpCommon): def test_tracking_repair_production(self): """ Test that removing a tracked component with a repair does not block the flow of using that component in another bom """ product_to_repair = self.env['product.product'].create({ 'name': 'product first serial to act repair', 'tracking': 'serial', }) ptrepair_lot = self.env['stock.production.lot'].create({ 'name': 'A1', 'product_id': product_to_repair.id, 'company_id': self.env.user.company_id.id }) product_to_remove = self.env['product.product'].create({ 'name': 'other first serial to remove with repair', 'tracking': 'serial', }) ptremove_lot = self.env['stock.production.lot'].create({ 'name': 'B2', 'product_id': product_to_remove.id, 'company_id': self.env.user.company_id.id }) # Create a manufacturing order with product (with SN A1) mo_form = Form(self.env['mrp.production']) mo_form.product_id = product_to_repair with mo_form.move_raw_ids.new() as move: move.product_id = product_to_remove move.product_uom_qty = 1 move.move_line_ids.lot_id = ptremove_lot # Set component serial to B2 mo = mo_form.save() mo.action_confirm() # Set serial to A1 mo.lot_producing_id = ptrepair_lot mo.button_mark_done() with Form(self.env['repair.order']) as ro_form: ro_form.product_id = product_to_repair ro_form.lot_id = ptrepair_lot # Repair product Serial A1 with ro_form.operations.new() as operation: operation.type = 'remove' operation.product_id = product_to_remove operation.lot_id = ptremove_lot # Remove product Serial B2 from the product ro = ro_form.save() ro.action_validate() ro.action_repair_start() ro.action_repair_end() # Create a manufacturing order with product (with SN A2) mo2_form = Form(self.env['mrp.production']) mo2_form.product_id = product_to_repair with mo2_form.move_raw_ids.new() as move: move.product_id = product_to_remove move.product_uom_qty = 1 move.move_line_ids.lot_id = ptremove_lot # Set component serial to B2 again, it is possible mo2 = mo2_form.save() mo2.action_confirm() # Set serial to A2 mo2.lot_producing_id = self.env['stock.production.lot'].create({ 'name': 'A2', 'product_id': product_to_repair.id, 'company_id': self.env.user.company_id.id }) # We are not forbidden to use that serial number, so nothing raised here mo2.button_mark_done() def test_mo_with_used_sn_component(self): """ Suppose a tracked-by-usn component has been used to produce a product. Then, using a repair order, this component is removed from the product and returned as available stock. The user should be able to use the component in a new MO """ def produce_one(product, component): mo_form = Form(self.env['mrp.production']) mo_form.product_id = product with mo_form.move_raw_ids.new() as raw_line: raw_line.product_id = component raw_line.product_uom_qty = 1 mo = mo_form.save() mo.action_confirm() mo.action_assign() action = mo.button_mark_done() wizard = Form(self.env[action['res_model']].with_context(action['context'])).save() wizard.process() return mo stock_location = self.env.ref('stock.stock_location_stock') finished, component = self.env['product.product'].create([{ 'name': 'Finished Product', 'type': 'product', }, { 'name': 'SN Componentt', 'type': 'product', 'tracking': 'serial', }]) sn_lot = self.env['stock.production.lot'].create({ 'product_id': component.id, 'name': 'USN01', 'company_id': self.env.company.id, }) self.env['stock.quant']._update_available_quantity(component, stock_location, 1, lot_id=sn_lot) mo = produce_one(finished, component) self.assertEqual(mo.state, 'done') self.assertEqual(mo.move_raw_ids.lot_ids, sn_lot) ro_form = Form(self.env['repair.order']) ro_form.product_id = finished with ro_form.operations.new() as ro_line: ro_line.type = 'remove' ro_line.product_id = component ro_line.lot_id = sn_lot ro_line.location_dest_id = stock_location ro = ro_form.save() ro.action_validate() ro.action_repair_start() ro.action_repair_end() mo = produce_one(finished, component) self.assertEqual(mo.state, 'done') self.assertEqual(mo.move_raw_ids.lot_ids, sn_lot)
40.810606
5,387
2,583
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class Repair(models.Model): _inherit = 'repair.order' @api.model def create(self, vals): res = super().create(vals) res.action_explode() return res def write(self, vals): res = super().write(vals) self.action_explode() return res def action_explode(self): lines_to_unlink_ids = set() line_vals_list = [] for op in self.operations: bom = self.env['mrp.bom'].sudo()._bom_find(op.product_id, company_id=op.company_id.id, bom_type='phantom')[op.product_id] if not bom: continue factor = op.product_uom._compute_quantity(op.product_uom_qty, bom.product_uom_id) / bom.product_qty _boms, lines = bom.sudo().explode(op.product_id, factor, picking_type=bom.picking_type_id) for bom_line, line_data in lines: if bom_line.product_id.type != 'service': line_vals_list.append(op._prepare_phantom_line_vals(bom_line, line_data['qty'])) lines_to_unlink_ids.add(op.id) self.env['repair.line'].browse(lines_to_unlink_ids).sudo().unlink() if line_vals_list: self.env['repair.line'].create(line_vals_list) class RepairLine(models.Model): _inherit = 'repair.line' def _prepare_phantom_line_vals(self, bom_line, qty): self.ensure_one() product = bom_line.product_id uom = bom_line.product_uom_id partner = self.repair_id.partner_id price = self.repair_id.pricelist_id.get_product_price(product, qty, partner, uom_id=uom.id) tax = self.env['account.tax'] if partner: partner_invoice = self.repair_id.partner_invoice_id or partner fpos = self.env['account.fiscal.position'].get_fiscal_position(partner_invoice.id, delivery_id=self.repair_id.address_id.id) taxes = self.product_id.taxes_id.filtered(lambda x: x.company_id == self.repair_id.company_id) tax = fpos.map_tax(taxes) return { 'name': self.name, 'repair_id': self.repair_id.id, 'type': self.type, 'product_id': product.id, 'price_unit': price, 'tax_id': [(4, t.id) for t in tax], 'product_uom_qty': qty, 'product_uom': uom.id, 'location_id': self.location_id.id, 'location_dest_id': self.location_dest_id.id, 'state': 'draft', }
39.136364
2,583
849
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2019 Bohdan Lisnenko <bohdan.lisnenko@erp.co.ua>, ERP Ukraine { 'name': 'Ukraine - Accounting', 'author': 'ERP Ukraine', 'website': 'https://erp.co.ua', 'version': '1.4', 'description': """ Ukraine - Chart of accounts. ============================ """, 'category': 'Accounting/Localizations/Account Charts', 'depends': ['account'], 'data': [ 'data/account_chart_template.xml', 'data/account.account.template.csv', 'data/account_account_tag_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_template.xml', 'data/account_chart_template_config.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'license': 'LGPL-3', }
30.321429
849
1,193
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Vietnam - Accounting", "version": "2.0.1", "author": "General Solutions", 'website': 'http://gscom.vn', 'category': 'Accounting/Localizations/Account Charts', "description": """ This is the module to manage the accounting chart for Vietnam in Odoo. ========================================================================= This module applies to companies based in Vietnamese Accounting Standard (VAS) with Chart of account under Circular No. 200/2014/TT-BTC **Credits:** - General Solutions. - Trobz """, "depends": [ "account", "base_iban", "l10n_multilang" ], "data": [ 'data/l10n_vn_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_vn_chart_post_data.xml', 'data/account_tax_group_data.xml', 'data/account_tax_report_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml', ], 'demo': [ 'demo/demo_company.xml', ], 'post_init_hook': '_post_init_hook', 'license': 'LGPL-3', }
27.744186
1,193
760
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, SUPERUSER_ID FIXED_ACCOUNTS_MAP = { '5221': '5211', '5222': '5212', '5223': '5213' } def _fix_revenue_deduction_accounts_code(env): vn_template = env.ref('l10n_vn.vn_template') for company in env['res.company'].with_context(active_test=False).search([('chart_template_id', '=', vn_template.id)]): for incorrect_code, correct_code in FIXED_ACCOUNTS_MAP.items(): account = env['account.account'].search([('code', '=', incorrect_code), ('company_id', '=', company.id)]) if account: account.write({'code': correct_code}) def migrate(cr, version): env = api.Environment(cr, SUPERUSER_ID, {}) _fix_revenue_deduction_accounts_code(env)
34.545455
760
507
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'SMS on Events', 'version': '1.0', 'category': 'Marketing/Events', 'description': """Schedule SMS in event management""", 'depends': ['event', 'sms'], 'data': [ 'data/sms_data.xml', 'security/ir.model.access.csv', 'security/sms_security.xml', ], 'demo': [ ], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
25.35
507
4,544
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil.relativedelta import relativedelta from odoo.addons.event.tests.common import TestEventCommon from odoo.addons.phone_validation.tools import phone_validation from odoo.addons.sms.tests.common import SMSCase class TestSMSSchedule(TestEventCommon, SMSCase): @classmethod def setUpClass(cls): super(TestSMSSchedule, cls).setUpClass() cls.sms_template_sub = cls.env['sms.template'].create({ 'name': 'Test subscription', 'model_id': cls.env.ref('event.model_event_registration').id, 'body': '{{ object.event_id.organizer_id.name }} registration confirmation.', 'lang': '{{ object.partner_id.lang }}' }) cls.sms_template_rem = cls.env['sms.template'].create({ 'name': 'Test reminder', 'model_id': cls.env.ref('event.model_event_registration').id, 'body': '{{ object.event_id.organizer_id.name }} reminder', 'lang': '{{ object.partner_id.lang }}' }) cls.event_0.write({ 'event_mail_ids': [ (5, 0), (0, 0, { # right at subscription 'interval_unit': 'now', 'interval_type': 'after_sub', 'notification_type': 'sms', 'template_ref': 'sms.template,%i' % cls.sms_template_sub.id}), (0, 0, { # 3 days before event 'interval_nbr': 3, 'interval_unit': 'days', 'interval_type': 'before_event', 'notification_type': 'sms', 'template_ref': 'sms.template,%i' % cls.sms_template_rem.id}), ] }) def test_sms_schedule(self): with self.mockSMSGateway(): self._create_registrations(self.event_0, 3) # check subscription scheduler sub_scheduler = self.env['event.mail'].search([('event_id', '=', self.event_0.id), ('interval_type', '=', 'after_sub')]) self.assertEqual(len(sub_scheduler), 1) self.assertEqual(sub_scheduler.scheduled_date, self.event_0.create_date, 'event: incorrect scheduled date for checking controller') # verify that subscription scheduler was auto-executed after each registration self.assertEqual(len(sub_scheduler.mail_registration_ids), 3) self.assertTrue(all(m.mail_sent is True for m in sub_scheduler.mail_registration_ids)) self.assertEqual(sub_scheduler.mapped('mail_registration_ids.registration_id'), self.event_0.registration_ids) sanitized_numbers = [] for registration in self.event_0.registration_ids: reg_sanitized_number = phone_validation.phone_format(registration.phone, 'BE', '32', force_format='E164') sanitized_numbers.append(reg_sanitized_number) self.assertSMSOutgoing( self.env['res.partner'], reg_sanitized_number, content='%s registration confirmation.' % self.event_0.organizer_id.name) self.assertTrue(sub_scheduler.mail_done) self.assertEqual(sub_scheduler.mail_count_done, 3) # clear notification queue to avoid conflicts when checking next notifications self.env['mail.notification'].search([('sms_number', 'in', sanitized_numbers)]).unlink() self.env['sms.sms'].search([('number', 'in', sanitized_numbers)]).unlink() # check before event scheduler before_scheduler = self.env['event.mail'].search([('event_id', '=', self.event_0.id), ('interval_type', '=', 'before_event')]) self.assertEqual(len(before_scheduler), 1, 'event: wrong scheduler creation') self.assertEqual(before_scheduler.scheduled_date, self.event_0.date_begin + relativedelta(days=-3)) # execute event reminder scheduler explicitly with self.mockSMSGateway(): before_scheduler.execute() # verify that subscription scheduler was auto-executed after each registration for registration in self.event_0.registration_ids: reg_sanitized_number = phone_validation.phone_format(registration.phone, 'BE', '32', force_format='E164') self.assertSMSOutgoing( self.env['res.partner'], reg_sanitized_number, content='%s reminder' % self.event_0.organizer_id.name) self.assertTrue(before_scheduler.mail_done) self.assertEqual(before_scheduler.mail_count_done, 3)
49.934066
4,544
4,115
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 EventTypeMail(models.Model): _inherit = 'event.type.mail' @api.model def _selection_template_model(self): return super(EventTypeMail, self)._selection_template_model() + [('sms.template', 'SMS')] notification_type = fields.Selection(selection_add=[('sms', 'SMS')], ondelete={'sms': 'set default'}) @api.depends('notification_type') def _compute_template_model_id(self): sms_model = self.env['ir.model']._get('sms.template') sms_mails = self.filtered(lambda mail: mail.notification_type == 'sms') sms_mails.template_model_id = sms_model super(EventTypeMail, self - sms_mails)._compute_template_model_id() class EventMailScheduler(models.Model): _inherit = 'event.mail' @api.model def _selection_template_model(self): return super(EventMailScheduler, self)._selection_template_model() + [('sms.template', 'SMS')] def _selection_template_model_get_mapping(self): return {**super(EventMailScheduler, self)._selection_template_model_get_mapping(), 'sms': 'sms.template'} notification_type = fields.Selection(selection_add=[('sms', 'SMS')], ondelete={'sms': 'set default'}) @api.depends('notification_type') def _compute_template_model_id(self): sms_model = self.env['ir.model']._get('sms.template') sms_mails = self.filtered(lambda mail: mail.notification_type == 'sms') sms_mails.template_model_id = sms_model super(EventMailScheduler, self - sms_mails)._compute_template_model_id() def execute(self): for scheduler in self: now = fields.Datetime.now() if scheduler.interval_type != 'after_sub' and scheduler.notification_type == 'sms': # before or after event -> one shot email if scheduler.mail_done: continue # no template -> ill configured, skip and avoid crash if not scheduler.template_ref: continue # Do not send SMS if the communication was scheduled before the event but the event is over if scheduler.scheduled_date <= now and (scheduler.interval_type != 'before_event' or scheduler.event_id.date_end > now): self.env['event.registration']._message_sms_schedule_mass( template=scheduler.template_ref, active_domain=[('event_id', '=', scheduler.event_id.id), ('state', '!=', 'cancel')], mass_keep_log=True ) scheduler.update({ 'mail_done': True, 'mail_count_done': scheduler.event_id.seats_reserved + scheduler.event_id.seats_used, }) return super(EventMailScheduler, self).execute() @api.onchange('notification_type') def set_template_ref_model(self): super().set_template_ref_model() mail_model = self.env['sms.template'] if self.notification_type == 'sms': record = mail_model.search([('model', '=', 'event.registration')], limit=1) self.template_ref = "{},{}".format('sms.template', record.id) if record else False class EventMailRegistration(models.Model): _inherit = 'event.mail.registration' def execute(self): now = fields.Datetime.now() todo = self.filtered(lambda reg_mail: not reg_mail.mail_sent and \ reg_mail.registration_id.state in ['open', 'done'] and \ (reg_mail.scheduled_date and reg_mail.scheduled_date <= now) and \ reg_mail.scheduler_id.notification_type == 'sms' ) for reg_mail in todo: reg_mail.registration_id._message_sms_schedule_mass( template=reg_mail.scheduler_id.template_ref, mass_keep_log=True ) todo.write({'mail_sent': True}) return super(EventMailRegistration, self).execute()
43.776596
4,115
386
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Registration(models.Model): _inherit = 'event.registration' def _sms_get_number_fields(self): """ This method returns the fields to use to find the number to use to send an SMS on a record. """ return ['mobile', 'phone']
29.692308
386
999
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.osv import expression class SmsTemplate(models.Model): _inherit = 'sms.template' @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): """Context-based hack to filter reference field in a m2o search box to emulate a domain the ORM currently does not support. As we can not specify a domain on a reference field, we added a context key `filter_template_on_event` on the template reference field. If this key is set, we add our domain in the `args` in the `_name_search` method to filtrate the SMS templates. """ if self.env.context.get('filter_template_on_event'): args = expression.AND([[('model', '=', 'event.registration')], args]) return super(SmsTemplate, self)._name_search(name, args, operator, limit, name_get_uid)
45.409091
999
650
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Sparse Fields", 'summary': """Implementation of sparse fields.""", 'description': """ The purpose of this module is to implement "sparse" fields, i.e., fields that are mostly null. This implementation circumvents the PostgreSQL limitation on the number of columns in a table. The values of all sparse fields are stored in a "serialized" field in the form of a JSON mapping. """, 'category': 'Hidden', 'version': '1.0', 'depends': ['base'], 'data': [ 'security/ir.model.access.csv', 'views/views.xml', ], 'license': 'LGPL-3', }
34.210526
650
1,371
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests import common class TestSparseFields(common.TransactionCase): def test_sparse(self): """ test sparse fields. """ record = self.env['sparse_fields.test'].create({}) self.assertFalse(record.data) partner = self.env.ref('base.main_partner') values = [ ('boolean', True), ('integer', 42), ('float', 3.14), ('char', 'John'), ('selection', 'two'), ('partner', partner.id), ] for n, (key, val) in enumerate(values): record.write({key: val}) self.assertEqual(record.data, dict(values[:n+1])) for key, val in values[:-1]: self.assertEqual(record[key], val) self.assertEqual(record.partner, partner) for n, (key, val) in enumerate(values): record.write({key: False}) self.assertEqual(record.data, dict(values[n+1:])) # check reflection of sparse fields in 'ir.model.fields' names = [name for name, _ in values] domain = [('model', '=', 'sparse_fields.test'), ('name', 'in', names)] fields = self.env['ir.model.fields'].search(domain) self.assertEqual(len(fields), len(names)) for field in fields: self.assertEqual(field.serialization_field_id.name, 'data')
34.275
1,371
4,066
py
PYTHON
15.0
# -*- coding: utf-8 -*- from collections import defaultdict from odoo import models, fields, api, _ from odoo.exceptions import UserError class Base(models.AbstractModel): _inherit = 'base' def _valid_field_parameter(self, field, name): return name == 'sparse' or super()._valid_field_parameter(field, name) class IrModelFields(models.Model): _inherit = 'ir.model.fields' ttype = fields.Selection(selection_add=[ ('serialized', 'serialized'), ], ondelete={'serialized': 'cascade'}) serialization_field_id = fields.Many2one('ir.model.fields', string='Serialization Field', ondelete='cascade', domain="[('ttype','=','serialized'), ('model_id', '=', model_id)]", help="If set, this field will be stored in the sparse structure of the " "serialization field, instead of having its own database column. " "This cannot be changed after creation.", ) def write(self, vals): # Limitation: renaming a sparse field or changing the storing system is # currently not allowed if 'serialization_field_id' in vals or 'name' in vals: for field in self: if 'serialization_field_id' in vals and field.serialization_field_id.id != vals['serialization_field_id']: raise UserError(_('Changing the storing system for field "%s" is not allowed.', field.name)) if field.serialization_field_id and (field.name != vals['name']): raise UserError(_('Renaming sparse field "%s" is not allowed', field.name)) return super(IrModelFields, self).write(vals) def _reflect_fields(self, model_names): super()._reflect_fields(model_names) # set 'serialization_field_id' on sparse fields; it is done here to # ensure that the serialized field is reflected already cr = self._cr # retrieve existing values query = """ SELECT model, name, id, serialization_field_id FROM ir_model_fields WHERE model IN %s """ cr.execute(query, [tuple(model_names)]) existing = {row[:2]: row[2:] for row in cr.fetchall()} # determine updates, grouped by value updates = defaultdict(list) for model_name in model_names: for field_name, field in self.env[model_name]._fields.items(): field_id, current_value = existing[(model_name, field_name)] try: value = existing[(model_name, field.sparse)][0] if field.sparse else None except KeyError: msg = _("Serialization field %r not found for sparse field %s!") raise UserError(msg % (field.sparse, field)) if current_value != value: updates[value].append(field_id) if not updates: return # update fields query = "UPDATE ir_model_fields SET serialization_field_id=%s WHERE id IN %s" for value, ids in updates.items(): cr.execute(query, [value, tuple(ids)]) records = self.browse(id_ for ids in updates.values() for id_ in ids) self.pool.post_init(records.modified, ['serialization_field_id']) def _instanciate_attrs(self, field_data): attrs = super(IrModelFields, self)._instanciate_attrs(field_data) if attrs and field_data.get('serialization_field_id'): serialization_record = self.browse(field_data['serialization_field_id']) attrs['sparse'] = serialization_record.name return attrs class TestSparse(models.TransientModel): _name = 'sparse_fields.test' _description = 'Sparse fields Test' data = fields.Serialized() boolean = fields.Boolean(sparse='data') integer = fields.Integer(sparse='data') float = fields.Float(sparse='data') char = fields.Char(sparse='data') selection = fields.Selection([('one', 'One'), ('two', 'Two')], sparse='data') partner = fields.Many2one('res.partner', sparse='data')
41.070707
4,066
2,834
py
PYTHON
15.0
# -*- coding: utf-8 -*- import json from odoo import fields def monkey_patch(cls): """ Return a method decorator to monkey-patch the given class. """ def decorate(func): name = func.__name__ func.super = getattr(cls, name, None) setattr(cls, name, func) return func return decorate # # Implement sparse fields by monkey-patching fields.Field # fields.Field.__doc__ += """ .. _field-sparse: .. rubric:: Sparse fields Sparse fields have a very small probability of being not null. Therefore many such fields can be serialized compactly into a common location, the latter being a so-called "serialized" field. :param sparse: the name of the field where the value of this field must be stored. """ fields.Field.sparse = None @monkey_patch(fields.Field) def _get_attrs(self, model_class, name): attrs = _get_attrs.super(self, model_class, name) if attrs.get('sparse'): # by default, sparse fields are not stored and not copied attrs['store'] = False attrs['copy'] = attrs.get('copy', False) attrs['compute'] = self._compute_sparse if not attrs.get('readonly'): attrs['inverse'] = self._inverse_sparse return attrs @monkey_patch(fields.Field) def _compute_sparse(self, records): for record in records: values = record[self.sparse] record[self.name] = values.get(self.name) if self.relational: for record in records: record[self.name] = record[self.name].exists() @monkey_patch(fields.Field) def _inverse_sparse(self, records): for record in records: values = record[self.sparse] value = self.convert_to_read(record[self.name], record, use_name_get=False) if value: if values.get(self.name) != value: values[self.name] = value record[self.sparse] = values else: if self.name in values: values.pop(self.name) record[self.sparse] = values # # Definition and implementation of serialized fields # class Serialized(fields.Field): """ Serialized fields provide the storage for sparse fields. """ type = 'serialized' column_type = ('text', 'text') prefetch = False # not prefetched by default def convert_to_column(self, value, record, values=None, validate=True): return self.convert_to_cache(value, record, validate=validate) def convert_to_cache(self, value, record, validate=True): # cache format: json.dumps(value) or None return json.dumps(value) if isinstance(value, dict) else (value or None) def convert_to_record(self, value, record): return json.loads(value or "{}") fields.Serialized = Serialized
29.831579
2,834
3,795
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Time Off', 'version': '1.5', 'category': 'Human Resources/Time Off', 'sequence': 85, 'summary': 'Allocate PTOs and follow leaves requests', 'website': 'https://www.odoo.com/app/time-off', 'description': """ Manage time off requests and allocations ===================================== This application controls the time off schedule of your company. It allows employees to request time off. Then, managers can review requests for time off and approve or reject them. This way you can control the overall time off planning for the company or department. You can configure several kinds of time off (sickness, paid days, ...) and allocate time off to an employee or department quickly using time off allocation. An employee can also make a request for more days off by making a new time off allocation. It will increase the total of available days for that time off type (if the request is accepted). You can keep track of time off in different ways by following reports: * Time Off Summary * Time Off by Department * Time Off Analysis A synchronization with an internal agenda (Meetings of the CRM module) is also possible in order to automatically create a meeting when a time off request is accepted by setting up a type of meeting in time off Type. """, 'depends': ['hr', 'calendar', 'resource'], 'data': [ 'data/report_paperformat.xml', 'data/mail_data.xml', 'data/hr_holidays_data.xml', 'data/ir_cron_data.xml', 'security/hr_holidays_security.xml', 'security/ir.model.access.csv', 'views/resource_views.xml', 'views/hr_leave_views.xml', 'views/hr_leave_type_views.xml', 'views/hr_leave_allocation_views.xml', 'views/hr_leave_accrual_views.xml', 'views/mail_activity_views.xml', 'wizard/hr_holidays_summary_employees_views.xml', 'wizard/hr_departure_wizard_views.xml', 'report/hr_holidays_templates.xml', 'report/hr_holidays_reports.xml', 'report/hr_leave_reports.xml', 'report/hr_leave_report_calendar.xml', 'report/hr_leave_employee_type_report.xml', 'views/hr_views.xml', 'views/hr_holidays_views.xml', ], 'demo': [ 'data/hr_holidays_demo.xml', ], 'installable': True, 'application': True, 'auto_install': False, 'assets': { 'mail.assets_discuss_public': [ 'hr_holidays/static/src/components/*/*', 'hr_holidays/static/src/models/*/*.js', ], 'web.assets_backend': [ 'hr_holidays/static/src/js/time_off_calendar.js', 'hr_holidays/static/src/js/float_without_trailing_zeros.js', 'hr_holidays/static/src/js/time_off_calendar_employee.js', 'hr_holidays/static/src/js/radio_image.js', 'hr_holidays/static/src/js/leave_stats_widget.js', 'hr_holidays/static/src/models/*/*.js', 'hr_holidays/static/src/scss/time_off.scss', 'hr_holidays/static/src/components/*/*.scss', 'hr_holidays/static/src/scss/accrual_plan_level.scss', ], 'web.tests_assets': [ 'hr_holidays/static/tests/helpers/**/*', ], 'web.qunit_suite_tests': [ 'hr_holidays/static/src/components/*/tests/*.js', 'hr_holidays/static/tests/test_leave_stats_widget.js', ], 'web.assets_qweb': [ 'hr_holidays/static/src/components/*/*.xml', 'hr_holidays/static/src/xml/*.xml', ], 'web.assets_tests': [ '/hr_holidays/static/tests/tours/**/**.js' ], }, 'license': 'LGPL-3', }
40.37234
3,795
45,682
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date, timedelta import time from dateutil.relativedelta import relativedelta from freezegun import freeze_time from pytz import timezone, UTC from odoo import fields from odoo.exceptions import ValidationError from odoo.tools import mute_logger from odoo.tests.common import Form from odoo.tests import tagged from odoo.exceptions import UserError from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon @tagged('leave_requests') class TestLeaveRequests(TestHrHolidaysCommon): def _check_holidays_status(self, holiday_status, ml, lt, rl, vrl): self.assertEqual(holiday_status.max_leaves, ml, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.leaves_taken, lt, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.remaining_leaves, rl, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.virtual_remaining_leaves, vrl, 'hr_holidays: wrong type days computation') def _check_holidays_count(self, holidays_count_result, ml, lt, rl, vrl, vlt): self.assertEqual( holidays_count_result, { 'max_leaves': ml, 'leaves_taken': lt, 'remaining_leaves': rl, 'virtual_remaining_leaves': vrl, 'virtual_leaves_taken': vlt, } ) def setUp(self): super(TestLeaveRequests, self).setUp() # Make sure we have the rights to create, validate and delete the leaves, leave types and allocations LeaveType = self.env['hr.leave.type'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True) self.holidays_type_1 = LeaveType.create({ 'name': 'NotLimitedHR', 'requires_allocation': 'no', 'leave_validation_type': 'hr', }) self.holidays_type_2 = LeaveType.create({ 'name': 'Limited', 'requires_allocation': 'yes', 'employee_requests': 'yes', 'leave_validation_type': 'hr', }) self.holidays_type_3 = LeaveType.create({ 'name': 'TimeNotLimited', 'requires_allocation': 'no', 'leave_validation_type': 'manager', }) self.holidays_type_4 = LeaveType.create({ 'name': 'Limited with 2 approvals', 'requires_allocation': 'yes', 'employee_requests': 'yes', 'leave_validation_type': 'both', }) self.holidays_support_document = LeaveType.create({ 'name': 'Time off with support document', 'support_document': True, 'requires_allocation': 'no', 'leave_validation_type': 'no_validation', }) def set_employee_create_date(self, id, newdate): """ This method is a hack in order to be able to define/redefine the create_date of the employees. This is done in SQL because ORM does not allow to write onto the create_date field. """ self.env.cr.execute(""" UPDATE hr_employee SET create_date = '%s' WHERE id = %s """ % (newdate, id)) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_overlapping_requests(self): """ Employee cannot create a new leave request at the same time, avoid interlapping """ self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Hol11', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_1.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': datetime.today(), 'number_of_days': 1, }) with self.assertRaises(ValidationError): self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Hol21', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_1.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': datetime.today(), 'number_of_days': 1, }) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_limited_type_no_days(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master return @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_limited_type_days_left(self): """ Employee creates a leave request in a limited category and has enough days left """ with freeze_time('2022-01-05'): aloc1_user_group = self.env['hr.leave.allocation'].with_user(self.user_hruser_id).create({ 'name': 'Days for limited category', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 2, 'state': 'confirm', 'date_from': time.strftime('%Y-1-1'), 'date_to': time.strftime('%Y-12-31'), }) aloc1_user_group.action_validate() holiday_status = self.holidays_type_2.with_user(self.user_employee_id) self._check_holidays_status(holiday_status, 2.0, 0.0, 2.0, 2.0) hol = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Hol11', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': (datetime.today() - relativedelta(days=2)), 'date_to': datetime.today(), 'number_of_days': 2, }) holiday_status.invalidate_cache() self._check_holidays_status(holiday_status, 2.0, 0.0, 2.0, 0.0) hol.with_user(self.user_hrmanager_id).action_approve() holiday_status.invalidate_cache(['max_leaves']) self._check_holidays_status(holiday_status, 2.0, 2.0, 0.0, 0.0) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_accrual_validity_time_valid(self): """ Employee ask leave during a valid validity time """ self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).create({ 'name': 'Sick Time Off', 'holiday_status_id': self.holidays_type_2.id, 'employee_id': self.employee_emp.id, 'date_from': fields.Datetime.from_string('2017-01-01 00:00:00'), 'date_to': fields.Datetime.from_string('2017-06-01 00:00:00'), 'number_of_days': 10, 'state': 'validate', }) self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Valid time period', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': fields.Datetime.from_string('2017-03-03 06:00:00'), 'date_to': fields.Datetime.from_string('2017-03-11 19:00:00'), 'number_of_days': 1, }) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_accrual_validity_time_not_valid(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master return @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_department_leave(self): """ Create a department leave """ self.employee_hrmanager.write({'department_id': self.hr_dept.id}) self.assertFalse(self.env['hr.leave'].search([('employee_id', 'in', self.hr_dept.member_ids.ids)])) leave_form = Form(self.env['hr.leave'].with_user(self.user_hrmanager), view='hr_holidays.hr_leave_view_form_manager') leave_form.holiday_type = 'department' leave_form.department_id = self.hr_dept leave_form.holiday_status_id = self.holidays_type_1 leave_form.request_date_from = date(2019, 5, 6) leave_form.request_date_to = date(2019, 5, 6) leave = leave_form.save() leave.action_approve() member_ids = self.hr_dept.member_ids.ids self.assertEqual(self.env['hr.leave'].search_count([('employee_id', 'in', member_ids)]), len(member_ids), "Leave should be created for members of department") @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_allocation_request(self): """ Create an allocation request """ # employee should be set to current user allocation_form = Form(self.env['hr.leave.allocation'].with_user(self.user_employee)) allocation_form.name = 'New Allocation Request' allocation_form.holiday_status_id = self.holidays_type_2 allocation_form.date_from = date(2019, 5, 6) allocation_form.date_to = date(2019, 5, 6) allocation = allocation_form.save() @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_employee_is_absent(self): """ Only the concerned employee should be considered absent """ user_employee_leave = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Hol11', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_1.id, 'date_from': (fields.Datetime.now() - relativedelta(days=1)), 'date_to': fields.Datetime.now() + relativedelta(days=1), 'number_of_days': 2, }) (self.employee_emp | self.employee_hrmanager).mapped('is_absent') # compute in batch self.assertFalse(self.employee_emp.is_absent, "He should not be considered absent") self.assertFalse(self.employee_hrmanager.is_absent, "He should not be considered absent") user_employee_leave.sudo().write({ 'state': 'validate', }) (self.employee_emp | self.employee_hrmanager)._compute_leave_status() self.assertTrue(self.employee_emp.is_absent, "He should be considered absent") self.assertFalse(self.employee_hrmanager.is_absent, "He should not be considered absent") @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_timezone_employee_leave_request(self): """ Create a leave request for an employee in another timezone """ self.employee_emp.tz = 'NZ' # GMT+12 leave = self.env['hr.leave'].new({ 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_1.id, 'request_unit_hours': True, 'request_date_from': date(2019, 5, 6), 'request_date_to': date(2019, 5, 6), 'request_hour_from': '8', # 8:00 AM in the employee's timezone 'request_hour_to': '17', # 5:00 PM in the employee's timezone }) self.assertEqual(leave.date_from, datetime(2019, 5, 5, 20, 0, 0), "It should have been localized before saving in UTC") self.assertEqual(leave.date_to, datetime(2019, 5, 6, 5, 0, 0), "It should have been localized before saving in UTC") @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_timezone_company_leave_request(self): """ Create a leave request for a company in another timezone """ company = self.env['res.company'].create({'name': "Hergé"}) company.resource_calendar_id.tz = 'NZ' # GMT+12 leave = self.env['hr.leave'].new({ 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_1.id, 'request_unit_hours': True, 'holiday_type': 'company', 'mode_company_id': company.id, 'request_date_from': date(2019, 5, 6), 'request_date_to': date(2019, 5, 6), 'request_hour_from': '8', # 8:00 AM in the company's timezone 'request_hour_to': '17', # 5:00 PM in the company's timezone }) self.assertEqual(leave.date_from, datetime(2019, 5, 5, 20, 0, 0), "It should have been localized before saving in UTC") self.assertEqual(leave.date_to, datetime(2019, 5, 6, 5, 0, 0), "It should have been localized before saving in UTC") @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_timezone_company_validated(self): """ Create a leave request for a company in another timezone and validate it """ self.env.user.tz = 'NZ' # GMT+12 company = self.env['res.company'].create({'name': "Hergé"}) employee = self.env['hr.employee'].create({'name': "Remi", 'company_id': company.id}) leave_form = Form(self.env['hr.leave'], view='hr_holidays.hr_leave_view_form_manager') leave_form.holiday_type = 'company' leave_form.mode_company_id = company leave_form.holiday_status_id = self.holidays_type_1 leave_form.request_date_from = date(2019, 5, 6) leave_form.request_date_to = date(2019, 5, 6) leave = leave_form.save() leave.state = 'confirm' leave.action_validate() employee_leave = self.env['hr.leave'].search([('employee_id', '=', employee.id)]) self.assertEqual( employee_leave.request_date_from, date(2019, 5, 6), "Timezone should be kept between company and employee leave" ) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_timezone_department_leave_request(self): """ Create a leave request for a department in another timezone """ company = self.env['res.company'].create({'name': "Hergé"}) company.resource_calendar_id.tz = 'NZ' # GMT+12 department = self.env['hr.department'].create({'name': "Museum", 'company_id': company.id}) leave = self.env['hr.leave'].new({ 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_1.id, 'request_unit_hours': True, 'holiday_type': 'department', 'department_id': department.id, 'request_date_from': date(2019, 5, 6), 'request_date_to': date(2019, 5, 6), 'request_hour_from': '8', # 8:00 AM in the department's timezone 'request_hour_to': '17', # 5:00 PM in the department's timezone }) self.assertEqual(leave.date_from, datetime(2019, 5, 5, 20, 0, 0), "It should have been localized before saving in UTC") self.assertEqual(leave.date_to, datetime(2019, 5, 6, 5, 0, 0), "It should have been localized before saving in UTC") def test_number_of_hours_display(self): # Test that the field number_of_hours_dispay doesn't change # after time off validation, as it takes the attendances # minus the resource leaves to compute that field. calendar = self.env['resource.calendar'].create({ 'name': 'Monday Morning Else Full Time 38h/week', 'hours_per_day': 7.6, 'attendance_ids': [ (0, 0, {'name': 'Monday Morning', 'dayofweek': '0', 'hour_from': 8.5, 'hour_to': 12.5, 'day_period': 'morning'}), (0, 0, {'name': 'Tuesday Morning', 'dayofweek': '1', 'hour_from': 8.5, 'hour_to': 12.5, 'day_period': 'morning'}), (0, 0, {'name': 'Tuesday Afternoon', 'dayofweek': '1', 'hour_from': 13, 'hour_to': 17.5, 'day_period': 'afternoon'}), (0, 0, {'name': 'Wednesday Morning', 'dayofweek': '2', 'hour_from': 8.5, 'hour_to': 12.5, 'day_period': 'morning'}), (0, 0, {'name': 'Wednesday Afternoon', 'dayofweek': '2', 'hour_from': 13, 'hour_to': 17.5, 'day_period': 'afternoon'}), (0, 0, {'name': 'Thursday Morning', 'dayofweek': '3', 'hour_from': 8.5, 'hour_to': 12.5, 'day_period': 'morning'}), (0, 0, {'name': 'Thursday Afternoon', 'dayofweek': '3', 'hour_from': 13, 'hour_to': 17.5, 'day_period': 'afternoon'}), (0, 0, {'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 8.5, 'hour_to': 12.5, 'day_period': 'morning'}), (0, 0, {'name': 'Friday Afternoon', 'dayofweek': '4', 'hour_from': 13, 'hour_to': 17.5, 'day_period': 'afternoon'}) ], }) employee = self.employee_emp employee.resource_calendar_id = calendar self.env.user.company_id.resource_calendar_id = calendar leave_type = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'request_unit': 'hour', 'leave_validation_type': 'both', }) allocation = self.env['hr.leave.allocation'].create({ 'name': '20 days allocation', 'holiday_status_id': leave_type.id, 'number_of_days': 20, 'employee_id': employee.id, 'state': 'confirm', 'date_from': time.strftime('2018-1-1'), 'date_to': time.strftime('%Y-1-1'), }) allocation.action_validate() leave1 = self.env['hr.leave'].create({ 'name': 'Holiday 1 week', 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'date_from': fields.Datetime.from_string('2019-12-23 06:00:00'), 'date_to': fields.Datetime.from_string('2019-12-27 20:00:00'), 'number_of_days': 5, }) self.assertEqual(leave1.number_of_hours_display, 38) leave1.action_approve() self.assertEqual(leave1.number_of_hours_display, 38) leave1.action_validate() self.assertEqual(leave1.number_of_hours_display, 38) leave2 = self.env['hr.leave'].create({ 'name': 'Holiday 1 Day', 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'date_from': fields.Datetime.from_string('2019-12-30 06:00:00'), 'date_to': fields.Datetime.from_string('2019-12-30 13:00:00'), 'number_of_days': 1, }) self.assertEqual(leave2.number_of_hours_display, 4) leave2.action_approve() self.assertEqual(leave2.number_of_hours_display, 4) leave2.action_validate() self.assertEqual(leave2.number_of_hours_display, 4) def test_number_of_hours_display_global_leave(self): # Check that the field number_of_hours_display # takes the global leaves into account, even # after validation calendar = self.env['resource.calendar'].create({ 'name': 'Classic 40h/week', 'hours_per_day': 8.0, 'attendance_ids': [ (0, 0, {'name': 'Monday Morning', 'dayofweek': '0', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Monday Afternoon', 'dayofweek': '0', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Tuesday Morning', 'dayofweek': '1', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Tuesday Afternoon', 'dayofweek': '1', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Wednesday Morning', 'dayofweek': '2', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Wednesday Afternoon', 'dayofweek': '2', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Thursday Morning', 'dayofweek': '3', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Thursday Afternoon', 'dayofweek': '3', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Friday Afternoon', 'dayofweek': '4', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}) ], 'global_leave_ids': [(0, 0, { 'name': 'Christmas Leave', 'date_from': fields.Datetime.from_string('2019-12-25 00:00:00'), 'date_to': fields.Datetime.from_string('2019-12-26 23:59:59'), 'resource_id': False, 'time_type': 'leave', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar self.env.user.company_id.resource_calendar_id = calendar leave_type = self.env['hr.leave.type'].create({ 'name': 'Sick', 'request_unit': 'hour', 'leave_validation_type': 'both', 'requires_allocation': 'no', }) leave1 = self.env['hr.leave'].create({ 'name': 'Sick 1 week during christmas snif', 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'date_from': fields.Datetime.from_string('2019-12-23 06:00:00'), 'date_to': fields.Datetime.from_string('2019-12-27 20:00:00'), 'number_of_days': 5, }) self.assertEqual(leave1.number_of_hours_display, 24) leave1.action_approve() self.assertEqual(leave1.number_of_hours_display, 24) leave1.action_validate() self.assertEqual(leave1.number_of_hours_display, 24) def _test_leave_with_tz(self, tz, local_date_from, local_date_to, number_of_days): self.user_employee.tz = tz tz = timezone(tz) # Mimic what is done by the calendar widget when clicking on a day. It # will take the local datetime from 7:00 to 19:00 and then convert it # to UTC before sending it. Values here are for PST (UTC -8) and # represent a leave on 2019/1/1 from 7:00 to 19:00 local time. values = { 'date_from': tz.localize(local_date_from).astimezone(UTC).replace(tzinfo=None), 'date_to': tz.localize(local_date_to).astimezone(UTC).replace(tzinfo=None), # note that this can be the next day in UTC } values.update(self.env['hr.leave'].with_user(self.user_employee_id)._default_get_request_parameters(values)) # Dates should be local to the user self.assertEqual(values['request_date_from'], local_date_from.date()) self.assertEqual(values['request_date_to'], local_date_to.date()) values.update({ 'name': 'Test', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_1.id, }) leave = self.env['hr.leave'].with_user(self.user_employee_id).new(values) self.assertEqual(leave.number_of_days, number_of_days) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_defaults_with_timezones(self): """ Make sure that leaves start with correct defaults for non-UTC timezones """ timezones_to_test = ('UTC', 'Pacific/Midway', 'US/Pacific', 'Asia/Taipei', 'Pacific/Kiritimati') # UTC, UTC -11, UTC -8, UTC +8, UTC +14 # January 2020 # Su Mo Tu We Th Fr Sa # 1 2 3 4 # 5 6 7 8 9 10 11 # 12 13 14 15 16 17 18 # 19 20 21 22 23 24 25 # 26 27 28 29 30 31 local_date_from = datetime(2020, 1, 1, 7, 0, 0) local_date_to = datetime(2020, 1, 1, 19, 0, 0) for tz in timezones_to_test: self._test_leave_with_tz(tz, local_date_from, local_date_to, 1) # We, Th, Fr, Mo, Tu, We => 6 days local_date_from = datetime(2020, 1, 1, 7, 0, 0) local_date_to = datetime(2020, 1, 8, 19, 0, 0) for tz in timezones_to_test: self._test_leave_with_tz(tz, local_date_from, local_date_to, 6)#TODO JUD check why this fails def test_expired_allocation(self): allocation = self.env['hr.leave.allocation'].create({ 'name': 'Expired Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 20, 'state': 'confirm', 'date_from': '2020-01-01', 'date_to': '2020-12-31', }) allocation.action_validate() with self.assertRaises(ValidationError): self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2021-09-01', 'date_to': '2021-09-02', 'number_of_days': 1, }) self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2020-09-01', 'date_to': '2020-09-02', 'number_of_days': 1, }) def test_no_days_expired(self): # First expired allocation allocation1 = self.env['hr.leave.allocation'].create({ 'name': 'Expired Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 20, 'state': 'confirm', 'date_from': '2020-01-01', 'date_to': '2020-12-31', }) allocation2 = self.env['hr.leave.allocation'].create({ 'name': 'Expired Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 3, 'state': 'confirm', 'date_from': '2021-01-01', 'date_to': '2021-12-31', }) allocation1.action_validate() allocation2.action_validate() # Try creating a request that could be validated if allocation1 was still valid with self.assertRaises(ValidationError): self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2021-09-06', 'date_to': '2021-09-10', 'number_of_days': 5, }) # This time we have enough days self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2021-09-06', 'date_to': '2021-09-08', 'number_of_days': 3, }) def test_company_leaves(self): # First expired allocation allocation = self.env['hr.leave.allocation'].create({ 'name': 'Allocation', 'holiday_type': 'company', 'mode_company_id': self.env.company.id, 'holiday_status_id': self.holidays_type_1.id, 'number_of_days': 20, 'state': 'confirm', 'date_from': '2021-01-01', }) allocation.action_validate() req1_form = Form(self.env['hr.leave'].sudo()) req1_form.employee_ids.add(self.employee_emp) req1_form.employee_ids.add(self.employee_hrmanager) req1_form.holiday_status_id = self.holidays_type_1 req1_form.request_date_from = fields.Date.to_date('2021-12-06') req1_form.request_date_to = fields.Date.to_date('2021-12-08') self.assertEqual(req1_form.number_of_days, 3) req1_form.save().action_approve() req2_form = Form(self.env['hr.leave'].sudo()) req2_form.employee_ids.add(self.employee_hruser) req2_form.holiday_status_id = self.holidays_type_1 req2_form.request_date_from = fields.Date.to_date('2021-12-06') req2_form.request_date_to = fields.Date.to_date('2021-12-08') self.assertEqual(req2_form.number_of_days, 3) def test_leave_with_public_holiday_other_company(self): other_company = self.env['res.company'].create({ 'name': 'Test Company', }) # Create a public holiday for the second company p_leave = self.env['resource.calendar.leaves'].create({ 'date_from': datetime(2022, 3, 11), 'date_to': datetime(2022, 3, 11, 23, 59, 59), }) p_leave.company_id = other_company leave = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'holiday_type': 'employee', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_1.id, 'date_from': datetime(2022, 3, 11), 'date_to': datetime(2022, 3, 11, 23, 59, 59), }) self.assertEqual(leave.number_of_days, 1) def test_several_allocations(self): allocation_vals = { 'name': 'Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 5, 'state': 'confirm', 'date_from': '2022-01-01', 'date_to': '2022-12-31', } allocation1 = self.env['hr.leave.allocation'].create(allocation_vals) allocation2 = self.env['hr.leave.allocation'].create(allocation_vals) allocation1.action_validate() allocation2.action_validate() # Able to create a leave of 10 days with two allocations of 5 days self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2022-01-01', 'date_to': '2022-01-15', 'number_of_days': 10, }) def test_several_allocations_split(self): Allocation = self.env['hr.leave.allocation'] allocation_vals = { 'name': 'Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'state': 'confirm', 'date_from': '2022-01-01', 'date_to': '2022-12-31', } Leave = self.env['hr.leave'].with_user(self.user_employee_id).sudo() leave_vals = { 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, } for unit in ['hour', 'day']: self.holidays_type_2.request_unit = unit allocation_vals.update({'number_of_days': 4}) allocation_4days = Allocation.create(allocation_vals) allocation_vals.update({'number_of_days': 1}) allocation_1day = Allocation.create(allocation_vals) allocations = (allocation_4days + allocation_1day) allocations.action_validate() leave_vals.update({ 'date_from': '2022-01-03 00:00:00', 'date_to': '2022-01-06 23:59:59', 'number_of_days': 4, }) leave_draft = Leave.create(leave_vals) leave_draft.action_refuse() leave_vals.update({ 'date_from': '2022-01-03 00:00:00', 'date_to': '2022-01-06 23:59:59', 'number_of_days': 4, }) leave_4days = Leave.create(leave_vals) leave_vals.update({ 'date_from': '2022-01-07 00:00:00', 'date_to': '2022-01-07 23:59:59', 'number_of_days': 1, }) leave_1day = Leave.create(leave_vals) leaves = (leave_4days + leave_1day) leaves.action_approve() allocation_days = self.holidays_type_2._get_employees_days_per_allocation([self.employee_emp_id]) self.assertEqual(allocation_days[self.employee_emp_id][self.holidays_type_2][allocation_4days]['leaves_taken'], leave_4days['number_of_%ss_display' % unit], 'As 4 days were available in this allocation, they should have been taken') self.assertEqual(allocation_days[self.employee_emp_id][self.holidays_type_2][allocation_1day]['leaves_taken'], leave_1day['number_of_%ss_display' % unit], 'As no days were available in previous allocation, they should have been taken in this one') leaves.action_refuse() allocations.action_refuse() def test_holiday_type_requires_no_allocation(self): # holiday_type_2 initially requires an allocation # Once an allocation is granted and a leave is taken, # the holiday type is changed to no longer require an allocation. # Leaves taken and available days should be correctly computed. with freeze_time('2020-09-15'): allocation = self.env['hr.leave.allocation'].create({ 'name': 'Expired Allocation', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 5, 'state': 'confirm', 'date_from': '2020-01-01', 'date_to': '2020-12-31', }) allocation.action_validate() leave1 = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2020-09-06', 'date_to': '2020-09-08', 'number_of_days': 3, }) self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=5, lt=0, rl=5, vrl=2, vlt=3, ) self.holidays_type_2.requires_allocation = 'no' leave2 = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': '2020-07-06', 'date_to': '2020-07-08', 'number_of_days': 3, }) # The 5 allocation days are not consumed anymore # virtual_remaining_leaves reflect the total number of leave days taken self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=5, lt=0, rl=5, vrl=5, vlt=6, ) leave1.with_user(self.user_hrmanager_id).action_approve() leave2.with_user(self.user_hrmanager_id).action_approve() # leaves_taken and virtual_leaves_taken reflect the total number of leave days taken self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=5, lt=6, rl=5, vrl=5, vlt=6, ) def test_archived_allocation(self): with freeze_time('2022-09-15'): allocation_2021 = self.env['hr.leave.allocation'].create({ 'name': 'Annual Time Off 2021', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 10, 'state': 'confirm', 'date_from': '2021-06-01', 'date_to': '2021-12-31', }) allocation_2022 = self.env['hr.leave.allocation'].create({ 'name': 'Annual Time Off 2022', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_type_2.id, 'number_of_days': 20, 'state': 'confirm', 'date_from': '2022-01-01', 'date_to': '2022-12-31', }) allocation_2021.action_validate() allocation_2022.action_validate() # Leave taken in 2021 leave_2021 = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'holiday_type': 'employee', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': datetime(2021, 8, 9, 0, 0, 0), 'date_to': datetime(2021, 8, 13, 23, 59, 59), }) leave_2021.with_user(self.user_hrmanager_id).action_approve() # The holidays count only takes into account the valid allocations at that date self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id], date=date(2021, 12, 1))[self.employee_emp_id][self.holidays_type_2.id], ml=10, lt=5, rl=5, vrl=5, vlt=5, ) # Virtual remaining leave is equal to 1 because there is only one day remaining in the allocation based on its validity self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id], date=date(2021, 12, 31))[self.employee_emp_id][self.holidays_type_2.id], ml=10, lt=5, rl=5, vrl=1, vlt=5, ) leave_2022 = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'holiday_type': 'employee', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.holidays_type_2.id, 'date_from': datetime(2022, 8, 9, 0, 0, 0), 'date_to': datetime(2022, 8, 13, 23, 59, 59), }) leave_2022.with_user(self.user_hrmanager_id).action_approve() # The holidays count in 2022 is not affected by the first leave taken in 2021 self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=20, lt=4, rl=16, vrl=16, vlt=4, ) # The holidays count in 2021 is not affected by the leave taken in 2022 self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id], date=date(2021, 12, 1))[self.employee_emp_id][self.holidays_type_2.id], ml=10, lt=5, rl=5, vrl=5, vlt=5, ) with self.assertRaisesRegex(UserError, r'You cannot archive an allocation which is in confirm or validate state.'): # The logic of the test is relevant, so we do not remove it. # However, the behaviour will change. # Indeed, a confirmed or validated allocation cannot be archived allocation_2021.active = False # If the allocation is archived, the leaves taken are still counted on this allocation # but the max leaves and remaining leaves are not counted anymore self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id], date=date(2021, 12, 1))[self.employee_emp_id][self.holidays_type_2.id], ml=0, lt=5, rl=0, vrl=0, vlt=5, ) # The holidays count in 2022 is not affected by the archived allocation in 2021 self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=20, lt=4, rl=16, vrl=16, vlt=4, ) allocation_2021.active = True # The holidays count in 2021 is back to what it was when the allocation was active self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id], date=date(2021, 12, 1))[self.employee_emp_id][self.holidays_type_2.id], ml=10, lt=5, rl=5, vrl=5, vlt=5, ) # The holidays count in 2022 is still not affected by the allocation in 2021 self._check_holidays_count( self.holidays_type_2.get_employees_days([self.employee_emp_id])[self.employee_emp_id][self.holidays_type_2.id], ml=20, lt=4, rl=16, vrl=16, vlt=4, ) def test_create_support_document_in_the_past(self): with freeze_time('2022-10-19'): self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_support_document.id, 'date_from': '2022-10-17', 'date_to': '2022-10-17', 'number_of_days': 1, 'supported_attachment_ids': [(6, 0, [])], # Sent by webclient }) def test_prevent_misplacement_of_allocations_without_end_date(self): """ The objective is to check that it is not possible to place leaves for which the interval does not correspond to the interval of allocations. """ holiday_type_A = self.env['hr.leave.type'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Type A', 'requires_allocation': 'yes', 'employee_requests': 'yes', 'leave_validation_type': 'hr', }) # Create allocations with no end date allocations = self.env['hr.leave.allocation'].create([ { 'name': 'Type A march 1 day without date to', 'employee_id': self.employee_emp_id, 'holiday_status_id': holiday_type_A.id, 'number_of_days': 1, 'state': 'confirm', 'date_from': '2023-01-03', }, { 'name': 'Type A april 5 day without date to', 'employee_id': self.employee_emp_id, 'holiday_status_id': holiday_type_A.id, 'number_of_days': 5, 'state': 'confirm', 'date_from': '2023-04-01', }, ]) allocations.action_validate() trigger_error_leave = { 'name': 'Holiday Request', 'employee_id': self.employee_emp_id, 'holiday_status_id': holiday_type_A.id, 'date_from': '2023-03-14', 'date_to': '2023-03-16', 'number_of_days': 3, } with self.assertRaises(ValidationError): self.env['hr.leave'].with_user(self.user_employee_id).create(trigger_error_leave) def test_current_leave_status(self): types = ('no_validation', 'manager', 'hr', 'both') employee = self.employee_emp def run_validation_flow(leave_validation_type): LeaveType = self.env['hr.leave.type'].with_user(self.user_hrmanager_id) leave_type = LeaveType.with_context(tracking_disable=True).create({ 'name': leave_validation_type.capitalize(), 'leave_validation_type': leave_validation_type, 'requires_allocation': 'no', }) current_leave = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Holiday Request', 'holiday_type': 'employee', 'employee_id': employee.id, 'holiday_status_id': leave_type.id, 'date_from': fields.Date.today(), 'date_to': fields.Date.today() + timedelta(days=2), 'number_of_days': 2, }) if leave_validation_type in ('manager', 'both'): self.assertFalse(employee.is_absent) self.assertFalse(employee.current_leave_id) self.assertEqual(employee.filtered_domain([('is_absent', '=', False)]), employee) self.assertFalse(employee.filtered_domain([('is_absent', '=', True)])) current_leave.with_user(self.user_hruser_id).action_approve() if leave_validation_type in ('hr', 'both'): self.assertFalse(employee.is_absent) self.assertFalse(employee.current_leave_id) self.assertEqual(employee.filtered_domain([('is_absent', '=', False)]), employee) self.assertFalse(employee.filtered_domain([('is_absent', '=', True)])) current_leave.with_user(self.user_hrmanager_id).action_validate() self.assertTrue(employee.is_absent) self.assertEqual(employee.current_leave_id, current_leave.holiday_status_id) self.assertFalse(employee.filtered_domain([('is_absent', '=', False)])) self.assertEqual(employee.filtered_domain([('is_absent', '=', True)]), employee) raise RuntimeError() for leave_validation_type in types: with self.assertRaises(RuntimeError), self.env.cr.savepoint(): run_validation_flow(leave_validation_type)
48.388771
45,679
1,133
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG from odoo.tests import tagged, TransactionCase @tagged('-at_install', 'post_install') class TestHrLeaveUninstall(TransactionCase): def test_unlink_model(self): model = self.env['ir.model'].search([('model', '=', 'hr.leave')]) activity_type = self.env['mail.activity'].search([ ('res_model', '=', 'hr.leave') ]).activity_type_id self.assertTrue(activity_type) self.assertIn('hr.leave', activity_type.mapped('res_model')) model.sudo().with_context(**{MODULE_UNINSTALL_FLAG: True}).unlink() self.assertFalse(model.exists()) domain = [('res_model', '=', 'hr.leave')] self.assertFalse(self.env['mail.activity'].search(domain)) self.assertFalse(self.env['mail.activity.type'].search(domain)) self.assertFalse(self.env['mail.followers'].search(domain)) self.assertFalse(self.env['mail.message'].search([ ('model', '=', 'hr.leave'), ]))
40.464286
1,133
36,145
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import tests from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon from odoo.exceptions import AccessError, UserError, ValidationError from odoo.tools import mute_logger @tests.tagged('access_rights', 'post_install', '-at_install') class TestHrHolidaysAccessRightsCommon(TestHrHolidaysCommon): def setUp(self): super(TestHrHolidaysAccessRightsCommon, self).setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Unlimited', 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.rd_dept.manager_id = False self.hr_dept.manager_id = False self.employee_emp.parent_id = False self.employee_leave = self.env['hr.leave'].with_user(self.user_employee_id).create({ 'name': 'Test', 'holiday_status_id': self.leave_type.id, 'department_id': self.employee_emp.department_id.id, 'employee_id': self.employee_emp.id, 'date_from': datetime.now(), 'date_to': datetime.now() + relativedelta(days=1), 'number_of_days': 1, }) self.lt_no_validation = self.env['hr.leave.type'].create({ 'name': 'Validation = no_validation', 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.lt_validation_hr = self.env['hr.leave.type'].create({ 'name': 'Validation = HR', 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.lt_validation_manager = self.env['hr.leave.type'].create({ 'name': 'Validation = manager', 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.lt_validation_both = self.env['hr.leave.type'].create({ 'name': 'Validation = both', 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.draft_status = [ self.lt_validation_hr, self.lt_validation_manager, self.lt_validation_both ] self.confirm_status = [ self.lt_no_validation, self.lt_validation_hr, self.lt_validation_manager, self.lt_validation_both ] def request_leave(self, user_id, date_from, number_of_days, values=None): values = dict(values or {}, **{ 'date_from': date_from, 'request_date_from': date_from, 'date_to': date_from + relativedelta(days=number_of_days), 'request_date_to': date_from + relativedelta(days=number_of_days), 'number_of_days': number_of_days, }) return self.env['hr.leave'].with_user(user_id).create(values) @tests.tagged('access_rights', 'access_rights_states') class TestAcessRightsStates(TestHrHolidaysAccessRightsCommon): # ****************************************************** # Action draft # ****************************************************** def test_draft_status(self): """ We should only be able to draft a leave that is in confirm or refuse state """ for i, status in enumerate(self.draft_status): values = { 'name': 'Ranoi', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.action_draft() values = { 'name': 'Ranoi', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=20 + i), 1, values) # the state has to be set to draft in a write because it is initialized to confirm if it has validation leave.write({'state': 'draft'}) with self.assertRaises(UserError): leave.action_draft() def test_base_user_draft_his_leave(self): """ Should be able to draft his own leave whatever the holiday_status_id """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_employee.id).action_draft() def test_base_user_draft_other_employee_leave(self): """ Should not be able to draft the leave of someone else whatever the holiday_status_id """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_employee.id).action_draft() def test_base_user_draft_other_employee_leave_and_is_leave_manager_id(self): """ Should not be able to draft the leave of someone else even when being the leave manager id for this person whatever the holiday_status_id """ self.employee_hruser.write({'leave_manager_id': self.user_employee.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_employee.id).action_draft() def test_base_user_draft_self_and_is_leave_manager_id(self): """ Should be able to draft his own leave even when being leave manager id whatever the holiday_status_id """ self.employee_emp.write({'leave_manager_id': self.user_employee.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_employee.id).action_draft() def test_base_user_draft_refused_leave(self): """ Should not be able to draft a refused leave """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.action_refuse() with self.assertRaises(UserError): leave.with_user(self.user_employee.id).action_draft() def test_base_user_draft_current_leave(self): """ Should not be able to draft a passed leave """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=-20 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_employee.id).action_draft() def test_holiday_user_draft_his_leave(self): """ Should be able to draft his own leave whatever the holiday_status_id """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hruser.id).action_draft() def test_holiday_user_draft_other_employee_leave(self): """ Should not be able to draft other employee leave whatever the holiday_status_id """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_hruser.id).action_draft() def test_holiday_user_draft_other_employee_leave_and_is_leave_manager_id(self): """ Should not be able to draft other employee leave even if he is the leave manager id whatever the holiday_status_id """ self.employee_emp.write({'leave_manager_id': self.user_hruser.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_hruser.id).action_draft() def test_holiday_user_draft_self_and_is_manager_id(self): """ Should be able to draft his own leave even if he is leave manager id whatever the holiday_status_id """ self.employee_hruser.write({'leave_manager_id': self.user_hruser.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hruser.id).action_draft() def test_holiday_user_draft_refused_leave(self): """ Should not be able to draft a refused leave """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.action_refuse() with self.assertRaises(UserError): leave.with_user(self.user_hruser.id).action_draft() def test_holiday_user_draft_current_leave(self): """ Should not be able to draft a passed leave """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=-20 + i), 1, values) with self.assertRaises(UserError): leave.with_user(self.user_hruser.id).action_draft() def test_holiday_manager_draft_his_leave(self): """ The holiday manager should be able to do everything """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hrmanager.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hrmanager.id).action_draft() def test_holiday_manager_draft_other_employee_leave(self): """ The holiday manager should be able to do everything """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hrmanager.id).action_draft() def test_holiday_manager_draft_other_employee_leave_and_is_leave_manager_id(self): """ The holiday manager should be able to do everything """ self.employee_hruser.write({'leave_manager_id': self.user_hrmanager.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hrmanager.id).action_draft() def test_holiday_manager_draft_self_and_is_manager_id(self): """ The holiday manager should be able to do everything """ self.employee_hrmanager.write({'leave_manager_id': self.user_hrmanager.id}) for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hrmanager.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.with_user(self.user_hrmanager.id).action_draft() def test_holiday_manager_draft_refused_leave(self): """ The holiday manager should be able to do everything """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=5 + i), 1, values) leave.action_refuse() leave.with_user(self.user_hrmanager.id).action_draft() def test_holiday_manager_draft_current_leave(self): """ The holiday manager should be able to do everything """ for i, status in enumerate(self.draft_status): values = { 'name': 'Random Leave', 'employee_id': self.employee_hruser.id, 'holiday_status_id': status.id, } leave = self.request_leave(1, datetime.today() + relativedelta(days=-20 + i), 1, values) leave.with_user(self.user_hrmanager.id).action_draft() @tests.tagged('access_rights', 'access_rights_create') class TestAccessRightsCreate(TestHrHolidaysAccessRightsCommon): @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_base_user_create_self(self): """ A simple user can create a leave for himself """ values = { 'name': 'Hol10', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.leave_type.id, } self.request_leave(self.user_employee_id, datetime.today() + relativedelta(days=5), 1, values) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_base_user_create_other(self): """ A simple user cannot create a leave for someone else """ values = { 'name': 'Hol10', 'employee_id': self.employee_hruser_id, 'holiday_status_id': self.leave_type.id, } with self.assertRaises(AccessError): self.request_leave(self.user_employee_id, datetime.today() + relativedelta(days=5), 1, values) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_base_user_create_batch(self): """ A simple user cannot create a leave in bacth mode (by company, by department, by tag)""" values = { 'name': 'Hol10', 'holiday_status_id': self.leave_type.id, 'holiday_type': 'company', 'mode_company_id': 1, } with self.assertRaises(AccessError): self.request_leave(self.user_employee_id, datetime.today() + relativedelta(days=5), 1, values) # hr_holidays.group_hr_holidays_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_holidays_user_create_self(self): """ A holidays user can create a leave for himself """ values = { 'name': 'Hol10', 'employee_id': self.employee_hruser_id, 'holiday_status_id': self.leave_type.id, } self.request_leave(self.user_hruser_id, datetime.today() + relativedelta(days=5), 1, values) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_holidays_user_create_other(self): """ A holidays user can create a leave for someone else """ values = { 'name': 'Hol10', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.leave_type.id, } self.request_leave(self.user_hruser_id, datetime.today() + relativedelta(days=5), 1, values) # hr_holidays.group_hr_holidays_manager @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_holidays_manager_create_self(self): """ A holidays manager can create a leave for himself """ values = { 'name': 'Hol10', 'employee_id': self.employee_hrmanager_id, 'holiday_status_id': self.leave_type.id, } self.request_leave(self.user_hrmanager_id, datetime.today() + relativedelta(days=5), 1, values) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_holidays_manager_create_other(self): """ A holidays manager can create a leave for someone else """ values = { 'name': 'Hol10', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.leave_type.id, } self.request_leave(self.user_hrmanager_id, datetime.today() + relativedelta(days=5), 1, values) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_holidays_manager_create_batch(self): """ A holidays manager can create a leave in bacth mode (by company, by department, by tag)""" values = { 'name': 'Hol10', 'holiday_status_id': self.leave_type.id, 'holiday_type': 'company', 'mode_company_id': 1, } self.request_leave(self.user_hrmanager_id, datetime.today() + relativedelta(days=5), 1, values) @tests.tagged('access_rights', 'access_rights_read') class TestAccessRightsRead(TestHrHolidaysAccessRightsCommon): # base.group_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_read_by_user_other(self): """ Users should not be able to read other people requests """ other_leave = self.env['hr.leave'].with_user(self.user_hruser).create({ 'name': 'Test', 'holiday_status_id': self.leave_type.id, 'department_id': self.employee_hruser.department_id.id, 'employee_id': self.employee_hruser.id, 'date_from': datetime.now(), 'date_to': datetime.now() + relativedelta(days=1), 'number_of_days': 1, }) with self.assertRaises(AccessError), self.cr.savepoint(): res = other_leave.with_user(self.user_employee_id).read(['number_of_days', 'state', 'name']) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_read_by_user_other_browse(self): """ Users should not be able to browse other people requests """ other_leave = self.env['hr.leave'].with_user(self.user_hruser).create({ 'name': 'Test', 'holiday_status_id': self.leave_type.id, 'department_id': self.employee_hruser.department_id.id, 'employee_id': self.employee_hruser.id, 'date_from': datetime.now(), 'date_to': datetime.now() + relativedelta(days=1), 'number_of_days': 1, }) with self.assertRaises(AccessError), self.cr.savepoint(): other_leave.invalidate_cache(['name']) name = other_leave.with_user(self.user_employee_id).name @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_read_by_user_own(self): """ Users should be able to read name field of own requests """ res = self.employee_leave.read(['name', 'number_of_days', 'state']) self.assertEqual(res[0]['name'], 'Test') @tests.tagged('access_rights', 'access_rights_write') class TestAccessRightsWrite(TestHrHolidaysAccessRightsCommon): # base.group_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_update_by_user(self): """ User may update its leave """ self.employee_leave.with_user(self.user_employee_id).write({'name': 'Crocodile Dundee is my man'}) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_update_by_user_other(self): """ User cannot update other people leaves """ other_leave = self.env['hr.leave'].with_user(self.user_hruser).create({ 'name': 'Test', 'holiday_status_id': self.leave_type.id, 'department_id': self.employee_hruser.department_id.id, 'employee_id': self.employee_hruser.id, 'date_from': datetime.now(), 'date_to': datetime.now() + relativedelta(days=1), 'number_of_days': 1, }) with self.assertRaises(AccessError): other_leave.with_user(self.user_employee_id).write({'name': 'Crocodile Dundee is my man'}) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_creation_for_other_user(self): """ Employee cannot creates a leave request for another employee """ HolidaysEmployeeGroup = self.env['hr.leave'].with_user(self.user_employee_id) with self.assertRaises(AccessError): HolidaysEmployeeGroup.create({ 'name': 'Hol10', 'employee_id': self.employee_hruser_id, 'holiday_status_id': self.leave_type.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': datetime.today(), 'number_of_days': 1, }) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_messaging_by_user(self): """ User may communicate on its own leaves, even if validated """ self.employee_leave.with_user(self.user_employee_id).message_post( body='I haz messaging', subtype_xmlid='mail.mt_comment', message_type='comment' ) self.employee_leave.with_user(self.user_hrmanager_id).action_approve() self.employee_leave.with_user(self.user_employee_id).message_post( body='I still haz messaging', subtype_xmlid='mail.mt_comment', message_type='comment' ) # ---------------------------------------- # Validation: one validation, HR # ---------------------------------------- # base.group_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_hr_to_validate_by_user(self): """ User may not validate any leaves in HR mode """ with self.assertRaises(UserError): self.employee_leave.with_user(self.user_employee_id).action_approve() with self.assertRaises(UserError): self.employee_leave.with_user(self.user_employee_id).write({'state': 'validate'}) # hr_holidays.group_hr_holidays_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_hr_to_validate_by_holiday_user(self): """ Manager can validate leaves in HR mode """ self.assertEqual(self.employee_leave.state, 'confirm') self.employee_leave.with_user(self.user_hrmanager_id).action_approve() self.assertEqual(self.employee_leave.state, 'validate') # hr_holidays.group_hr_holidays_manager @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_hr_to_validate_by_manager(self): """ Manager validate its own leaves """ manager_leave = self.env['hr.leave'].with_user(self.user_hrmanager_id).create({ 'name': 'Hol manager', 'holiday_status_id': self.leave_type.id, 'employee_id': self.employee_hrmanager_id, 'date_from': (datetime.today() + relativedelta(days=15)), 'date_to': (datetime.today() + relativedelta(days=16)), 'number_of_days': 1, }) self.assertEqual(manager_leave.state, 'confirm') manager_leave.action_approve() self.assertEqual(manager_leave.state, 'validate') # ---------------------------------------- # Validation: one validation, manager # ---------------------------------------- # base.group_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_manager_to_validate_by_user(self): """ A simple user can validate in manager mode if he is leave_manager_id """ self.leave_type.write({'leave_validation_type': 'manager'}) values = { 'name': 'Hol HrUser', 'employee_id': self.employee_hruser_id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } hr_leave = self.request_leave(self.user_hruser_id, datetime.now() + relativedelta(days=2), 1, values) with self.assertRaises(AccessError): hr_leave.with_user(self.user_employee_id).action_approve() self.employee_hruser.write({'leave_manager_id': self.user_employee_id}) hr_leave.with_user(self.user_employee_id).action_approve() # hr_holidays.group_hr_holidays_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_manager_to_validate_by_holiday_user(self): """ A holiday user can validate in manager mode """ self.leave_type.write({'leave_validation_type': 'manager'}) values = { 'name': 'Hol HrUser', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } hr_leave = self.request_leave(self.user_hruser_id, datetime.now() + relativedelta(days=2), 1, values) hr_leave.with_user(self.user_hruser_id).action_approve() # ---------------------------------------- # Validation: double # ---------------------------------------- @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_double_validate(self): self.leave_type.write({'leave_validation_type': 'both'}) values = { 'name': 'double HrManager', 'employee_id': self.employee_hrmanager_id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } self.employee_hrmanager.leave_manager_id = self.env['res.users'].browse(1) hr_leave = self.request_leave(self.user_hruser_id, datetime.now() + relativedelta(days=6), 1, values) with self.assertRaises(AccessError): hr_leave.with_user(self.user_employee_id).action_approve() self.employee_hrmanager.leave_manager_id = self.user_hruser hr_leave.with_user(self.user_hruser_id).action_approve() with self.assertRaises(AccessError): hr_leave.with_user(self.user_employee_id).action_validate() hr_leave.with_user(self.user_hruser_id).action_validate() # hr_holidays.group_hr_holidays_manager @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_double_validate_holiday_manager(self): self.leave_type.write({'leave_validation_type': 'both'}) values = { 'name': 'double HrManager', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } hr_leave = self.request_leave(self.user_hrmanager_id, datetime.now() + relativedelta(days=4), 1, values).with_user(self.user_hrmanager_id) hr_leave.action_approve() hr_leave.action_validate() # ---------------------------------------- # State = Refuse # ---------------------------------------- # base.group_user # hr_holidays.group_hr_holidays_user # TODO Can refuse # hr_holidays.group_hr_holidays_manager # TODO Can refuse # ---------------------------------------- # State = Cancel # ---------------------------------------- # base.group_user # TODO Can Cancel if start_date in the future # hr_holidays.group_hr_holidays_user # TODO Can Cancel if not in validate # hr_holidays.group_hr_holidays_manager # TODO Can always cancel with great powers comes great responbilities class TestAccessRightsUnlink(TestHrHolidaysAccessRightsCommon): # base.group_user @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_unlink_draft_by_user(self): """ A simple user may delete its leave in draft state in the future""" values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'state': 'draft', } leave = self.request_leave(self.user_employee_id, datetime.now() + relativedelta(days=6), 1, values) leave.with_user(self.user_employee.id).unlink() def test_leave_unlink_confirm_by_user(self): """ A simple user may delete its leave in confirm state in the future""" values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } leave = self.request_leave(self.user_employee_id, datetime.now() + relativedelta(days=6), 1, values) leave.with_user(self.user_employee.id).unlink() def test_leave_unlink_confirm_in_past_by_user(self): """ A simple user cannot delete its leave in the past""" values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'state': 'confirm', } leave = self.request_leave(self.user_employee_id, datetime.now() + relativedelta(days=-4), 1, values) with self.assertRaises(UserError), self.cr.savepoint(): leave.with_user(self.user_employee.id).unlink() def test_leave_unlink_validate_by_user(self): """ A simple user cannot delete its leave in validate state""" values = { 'name': 'Random Leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, } leave = self.request_leave(self.user_employee_id, datetime.now() + relativedelta(days=6), 1, values) leave.with_user(self.user_hrmanager_id).write({'state': 'validate'}) with self.assertRaises(UserError), self.cr.savepoint(): leave.with_user(self.user_employee.id).unlink() class TestMultiCompany(TestHrHolidaysCommon): def setUp(self): super(TestMultiCompany, self).setUp() self.new_company = self.env['res.company'].create({ 'name': 'Crocodile Dundee Company', }) self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Unlimited - Company New', 'company_id': self.new_company.id, 'leave_validation_type': 'hr', 'requires_allocation': 'no', }) self.rd_dept.manager_id = False self.hr_dept.manager_id = False self.employee_leave = self.env['hr.leave'].create({ 'name': 'Test', 'holiday_status_id': self.leave_type.id, 'department_id': self.employee_emp.department_id.id, 'employee_id': self.employee_emp.id, 'date_from': datetime.now(), 'date_to': datetime.now() + relativedelta(days=1), 'number_of_days': 1, }) @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_user(self): employee_leave = self.employee_leave.with_user(self.user_employee) employee_leave.invalidate_cache(['name']) with self.assertRaises(AccessError): employee_leave.name with self.assertRaises(AccessError): employee_leave.action_approve() @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_officer(self): employee_leave_hruser = self.employee_leave.with_user(self.user_hruser) employee_leave_hruser.invalidate_cache(['name']) with self.assertRaises(AccessError): employee_leave_hruser.name with self.assertRaises(AccessError): employee_leave_hruser.action_approve() @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_other_company_manager(self): employee_leave_hrmanager = self.employee_leave.with_user(self.user_hrmanager) employee_leave_hrmanager.invalidate_cache(['name']) with self.assertRaises(AccessError): employee_leave_hrmanager.name with self.assertRaises(AccessError): employee_leave_hrmanager.action_approve() @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_no_company_user(self): self.leave_type.write({'company_id': False}) employee_leave = self.employee_leave.with_user(self.user_employee) employee_leave.name with self.assertRaises(UserError): employee_leave.action_approve() self.assertEqual(employee_leave.state, 'confirm') @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_no_company_officer(self): self.leave_type.write({'company_id': False}) employee_leave_hruser = self.employee_leave.with_user(self.user_hruser) employee_leave_hruser.name employee_leave_hruser.action_approve() self.assertEqual(employee_leave_hruser.state, 'validate') @mute_logger('odoo.models.unlink', 'odoo.addons.mail.models.mail_mail') def test_leave_access_no_company_manager(self): self.leave_type.write({'company_id': False}) employee_leave_hrmanager = self.employee_leave.with_user(self.user_hrmanager) employee_leave_hrmanager.name employee_leave_hrmanager.action_approve() self.assertEqual(employee_leave_hrmanager.state, 'validate')
42.623821
36,145
3,750
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon class TestChangeDepartment(TestHrHolidaysCommon): def test_employee_change_department_request_change_department(self): self.HolidaysEmployeeGroup = self.env['hr.leave'].with_user(self.user_employee_id) HolidayStatusManagerGroup = self.env['hr.leave.type'].with_user(self.user_hrmanager_id) self.holidays_status_1 = HolidayStatusManagerGroup.create({ 'name': 'NotLimitedHR', 'requires_allocation': 'no', }) def create_holiday(name, start, end): return self.HolidaysEmployeeGroup.create({ 'name': name, 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_status_1.id, 'date_from': (datetime.today() + relativedelta(days=start)).strftime('%Y-%m-%d %H:%M'), 'date_to': datetime.today() + relativedelta(days=end), 'number_of_days': end-start, }) # Non approved leave request change department self.employee_emp.department_id = self.rd_dept hol1_employee_group = create_holiday("hol1", 1, 2) self.employee_emp.department_id = self.hr_dept self.assertEqual(hol1_employee_group.department_id, self.hr_dept, 'hr_holidays: non approved leave request should change department if employee change department') # Approved passed leave request change department self.employee_emp.department_id = self.hr_dept hol2_employee_group = create_holiday("hol2", -4, -3) hol2_user_group = hol2_employee_group.with_user(self.user_hruser_id) hol2_user_group.action_approve() self.employee_emp.department_id = self.rd_dept self.assertEqual(hol2_employee_group.department_id, self.hr_dept, 'hr_holidays: approved passed leave request should stay in previous department if employee change department') # Approved futur leave request change department self.employee_emp.department_id = self.hr_dept hol22_employee_group = create_holiday("hol22", 3, 4) hol22_user_group = hol22_employee_group.with_user(self.user_hruser_id) hol22_user_group.action_approve() self.employee_emp.department_id = self.rd_dept self.assertEqual(hol22_employee_group.department_id, self.rd_dept, 'hr_holidays: approved futur leave request should change department if employee change department') # Refused passed leave request change department self.employee_emp.department_id = self.rd_dept hol3_employee_group = create_holiday("hol3", -6, -5) hol3_user_group = hol3_employee_group.with_user(self.user_hruser_id) hol3_user_group.action_refuse() self.employee_emp.department_id = self.hr_dept # Change department self.assertEqual(hol3_employee_group.department_id, self.rd_dept, 'hr_holidays: refused passed leave request should stay in previous department if employee change department') # Refused futur leave request change department self.employee_emp.department_id = self.rd_dept hol32_employee_group = create_holiday("hol32", 5, 6) hol32_user_group = hol32_employee_group.with_user(self.user_hruser_id) hol32_user_group.action_refuse() self.employee_emp.department_id = self.hr_dept # Change department self.assertEqual(hol32_employee_group.department_id, self.hr_dept, 'hr_holidays: refused futur leave request should change department if employee change department')
56.818182
3,750
44,929
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from freezegun import freeze_time from dateutil.relativedelta import relativedelta from odoo.tests import tagged from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon @tagged('post_install', '-at_install') class TestAccrualAllocations(TestHrHolidaysCommon): def setUp(self): super(TestAccrualAllocations, self).setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'time_type': 'leave', 'requires_allocation': 'yes', }) def setAllocationCreateDate(self, allocation_id, date): """ This method is a hack in order to be able to define/redefine the create_date of the allocations. This is done in SQL because ORM does not allow to write onto the create_date field. """ self.env.cr.execute(""" UPDATE hr_leave_allocation SET create_date = '%s' WHERE id = %s """ % (date, allocation_id)) def test_frequency_daily(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 10000 })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() tomorrow = datetime.date.today() + relativedelta(days=2) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(tomorrow): allocation._update_accrual() nextcall = datetime.date.today() + relativedelta(days=1) self.assertEqual(allocation.number_of_days, 1, 'There should be 1 day allocated.') self.assertEqual(allocation.nextcall, nextcall, 'The next call date of the cron should be in 2 days.') allocation._update_accrual() self.assertEqual(allocation.number_of_days, 1, 'There should be only 1 day allocated.') def test_frequency_weekly(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 10000 })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2021-09-03', }) with freeze_time(datetime.date(2021, 9, 5)): allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() nextWeek = allocation.date_from + relativedelta(days=1, weekday=0) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(nextWeek): allocation._update_accrual() nextWeek = datetime.date.today() + relativedelta(days=1, weekday=0) #Prorated self.assertAlmostEqual(allocation.number_of_days, 0.2857, 4, 'There should be 0.2857 day allocated.') self.assertEqual(allocation.nextcall, nextWeek, 'The next call date of the cron should be in 2 weeks') with freeze_time(nextWeek): allocation._update_accrual() nextWeek = datetime.date.today() + relativedelta(days=1, weekday=0) self.assertAlmostEqual(allocation.number_of_days, 1.2857, 4, 'There should be 1.2857 day allocated.') self.assertEqual(allocation.nextcall, nextWeek, 'The next call date of the cron should be in 2 weeks') def test_frequency_bimonthly(self): with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'bimonthly', 'first_day': 1, 'second_day': 15, 'maximum_leave': 10000, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2021-09-03', }) self.setAllocationCreateDate(allocation.id, '2021-09-01 00:00:00') allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() next_date = datetime.date(2021, 9, 15) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(next_date): next_date = datetime.date(2021, 10, 1) allocation._update_accrual() #Prorated self.assertAlmostEqual(allocation.number_of_days, 0.7857, 4, 'There should be 0.7857 day allocated.') self.assertEqual(allocation.nextcall, next_date, 'The next call date of the cron should be October 1st') with freeze_time(next_date): allocation._update_accrual() #Not Prorated self.assertAlmostEqual(allocation.number_of_days, 1.7857, 4, 'There should be 1.7857 day allocated.') def test_frequency_monthly(self): with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 10000 })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2021-08-31', }) self.setAllocationCreateDate(allocation.id, '2021-09-01 00:00:00') allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() next_date = datetime.date(2021, 10, 1) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(next_date): next_date = datetime.date(2021, 11, 1) allocation._update_accrual() # Prorata = 1 since a whole month passed self.assertEqual(allocation.number_of_days, 1, 'There should be 1 day allocated.') self.assertEqual(allocation.nextcall, next_date, 'The next call date of the cron should be November 1st') def test_frequency_biyearly(self): with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'biyearly', 'maximum_leave': 10000, })], }) #this sets up an accrual on the 1st of January and the 1st of July allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) self.setAllocationCreateDate(allocation.id, '2021-09-01 00:00:00') allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() next_date = datetime.date(2022, 1, 1) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(next_date): next_date = datetime.date(2022, 7, 1) allocation._update_accrual() # Prorated self.assertAlmostEqual(allocation.number_of_days, 0.6576, 4, 'There should be 0.6576 day allocated.') self.assertEqual(allocation.nextcall, next_date, 'The next call date of the cron should be July 1st') with freeze_time(next_date): allocation._update_accrual() # Not Prorated self.assertAlmostEqual(allocation.number_of_days, 1.6576, 4, 'There should be 1.6576 day allocated.') def test_frequency_yearly(self): with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'yearly', 'maximum_leave': 10000, })], }) #this sets up an accrual on the 1st of January allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) self.setAllocationCreateDate(allocation.id, '2021-09-01 00:00:00') allocation.action_confirm() allocation.action_validate() self.assertFalse(allocation.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet.') allocation._update_accrual() next_date = datetime.date(2022, 1, 1) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(next_date): next_date = datetime.date(2023, 1, 1) allocation._update_accrual() self.assertAlmostEqual(allocation.number_of_days, 0.3315, 4, 'There should be 0.3315 day allocated.') self.assertEqual(allocation.nextcall, next_date, 'The next call date of the cron should be January 1st 2023') with freeze_time(next_date): allocation._update_accrual() self.assertAlmostEqual(allocation.number_of_days, 1.3315, 4, 'There should be 1.3315 day allocated.') def test_check_gain(self): # 2 accruals, one based on worked time, one not # check gain with freeze_time('2021-08-30'): attendances = [] for index in range(5): attendances.append((0, 0, { 'name': '%s_%d' % ('40 Hours', index), 'hour_from': 8, 'hour_to': 12, 'dayofweek': str(index), 'day_period': 'morning' })) attendances.append((0, 0, { 'name': '%s_%d' % ('40 Hours', index), 'hour_from': 13, 'hour_to': 17, 'dayofweek': str(index), 'day_period': 'afternoon' })) calendar_emp = self.env['resource.calendar'].create({ 'name': '40 Hours', 'tz': self.employee_emp.tz, 'attendance_ids': attendances, }) self.employee_emp.resource_calendar_id = calendar_emp.id accrual_plan_not_based_on_worked_time = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 5, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 10000, })], }) accrual_plan_based_on_worked_time = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 5, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 10000, 'is_based_on_worked_time': True, })], }) allocation_not_worked_time = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan_not_based_on_worked_time.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'state': 'validate', }) allocation_worked_time = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan_based_on_worked_time.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'state': 'validate', }) self.setAllocationCreateDate(allocation_not_worked_time.id, '2021-08-01 00:00:00') self.setAllocationCreateDate(allocation_worked_time.id, '2021-08-01 00:00:00') holiday_type = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'requires_allocation': 'no', 'responsible_id': self.user_hrmanager_id, }) leave = self.env['hr.leave'].create({ 'name': 'leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': holiday_type.id, 'date_from': '2021-09-02 00:00:00', 'date_to': '2021-09-02 23:59:59', }) leave.action_validate() self.assertFalse(allocation_not_worked_time.nextcall, 'There should be no nextcall set on the allocation.') self.assertFalse(allocation_worked_time.nextcall, 'There should be no nextcall set on the allocation.') self.assertEqual(allocation_not_worked_time.number_of_days, 0, 'There should be no days allocated yet.') self.assertEqual(allocation_worked_time.number_of_days, 0, 'There should be no days allocated yet.') next_date = datetime.date(2021, 9, 6) with freeze_time(next_date): # next_date = datetime.date(2021, 9, 13) self.env['hr.leave.allocation']._update_accrual() # Prorated self.assertAlmostEqual(allocation_not_worked_time.number_of_days, 4.2857, 4, 'There should be 4.2857 days allocated.') # 3.75 -> starts 1 day after allocation date -> 31/08-3/09 => 4 days - 1 days time off => (3 / 4) * 5 days # ^ result without prorata # Prorated self.assertAlmostEqual(allocation_worked_time.number_of_days, 3, 4, 'There should be 3 days allocated.') self.assertEqual(allocation_not_worked_time.nextcall, datetime.date(2021, 9, 13), 'The next call date of the cron should be the September 13th') self.assertEqual(allocation_worked_time.nextcall, datetime.date(2021, 9, 13), 'The next call date of the cron should be the September 13th') with freeze_time(next_date + relativedelta(days=7)): next_date = datetime.date(2021, 9, 20) self.env['hr.leave.allocation']._update_accrual() self.assertAlmostEqual(allocation_not_worked_time.number_of_days, 9.2857, 4, 'There should be 9.2857 days allocated.') self.assertEqual(allocation_not_worked_time.nextcall, next_date, 'The next call date of the cron should be September 20th') self.assertAlmostEqual(allocation_worked_time.number_of_days, 8, 4, 'There should be 8 days allocated.') self.assertEqual(allocation_worked_time.nextcall, next_date, 'The next call date of the cron should be September 20th') def test_check_max_value(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 1, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() allocation._update_accrual() tomorrow = datetime.date.today() + relativedelta(days=2) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(tomorrow): allocation._update_accrual() nextcall = datetime.date.today() + relativedelta(days=1) allocation._update_accrual() self.assertEqual(allocation.number_of_days, 1, 'There should be only 1 day allocated.') with freeze_time(nextcall): allocation._update_accrual() nextcall = datetime.date.today() + relativedelta(days=1) #The maximum value is 1 so this shouldn't change anything allocation._update_accrual() self.assertEqual(allocation.number_of_days, 1, 'There should be only 1 day allocated.') def test_check_max_value_hours(self): with freeze_time(datetime.date(2017, 12, 5)): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'hours', 'frequency': 'daily', 'maximum_leave': 4, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() allocation._update_accrual() tomorrow = datetime.date.today() + relativedelta(days=2) self.assertEqual(allocation.number_of_days, 0, 'There should be no days allocated yet. The accrual starts tomorrow.') with freeze_time(tomorrow): allocation._update_accrual() nextcall = datetime.date.today() + relativedelta(days=10) allocation._update_accrual() self.assertEqual(allocation.number_of_days, 0.125, 'There should be only 0.125 days allocated.') with freeze_time(nextcall): allocation._update_accrual() nextcall = datetime.date.today() + relativedelta(days=1) #The maximum value is 1 so this shouldn't change anything allocation._update_accrual() self.assertEqual(allocation.number_of_days, 0.5, 'There should be only 0.5 days allocated.') def test_accrual_transition_immediately(self): #1 accrual with 2 levels and level transition immediately accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'transition_mode': 'immediately', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 1, }), (0, 0, { 'start_count': 10, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 1, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() next_date = datetime.date.today() + relativedelta(days=11) second_level = self.env['hr.leave.accrual.level'].search([('accrual_plan_id', '=', accrual_plan.id), ('start_count', '=', 10)]) self.assertEqual(allocation._get_current_accrual_plan_level_id(next_date)[0], second_level, 'The second level should be selected') def test_accrual_transition_after_period(self): # 1 accrual with 2 levels and level transition after accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'transition_mode': 'end_of_accrual', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 1, }), (0, 0, { 'start_count': 10, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'maximum_leave': 1, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() next_date = datetime.date.today() + relativedelta(days=11) second_level = self.env['hr.leave.accrual.level'].search([('accrual_plan_id', '=', accrual_plan.id), ('start_count', '=', 10)]) self.assertEqual(allocation._get_current_accrual_plan_level_id(next_date)[0], second_level, 'The second level should be selected') def test_unused_accrual_lost(self): #1 accrual with 2 levels and level transition immediately with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 1, 'action_with_unused_accruals': 'lost', })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 10, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-01-01'): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 1, 'The number of days should be reset') def test_unused_accrual_postponed(self): # 1 accrual with 2 levels and level transition after # This also tests retroactivity with freeze_time('2021-09-01'): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 25, 'action_with_unused_accruals': 'postponed', })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 10, 'allocation_type': 'accrual', }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-01-01'): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 25, 'The maximum number of days should be reached and kept.') def test_accrual_skipped_period(self): # Test that when an allocation is made in the past and the second level is technically reached # that the first level is not skipped completely. accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 15, 'added_value_type': 'days', 'frequency': 'biyearly', 'maximum_leave': 100, 'action_with_unused_accruals': 'postponed', }), (0, 0, { 'start_count': 4, 'start_type': 'month', 'added_value': 10, 'added_value_type': 'days', 'frequency': 'biyearly', 'maximum_leave': 500, 'action_with_unused_accruals': 'postponed', })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual Allocation - Test', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': datetime.date(2020, 8, 16), }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-1-10'): allocation._update_accrual() self.assertAlmostEqual(allocation.number_of_days, 30.82, 2, "Invalid number of days") def test_three_levels_accrual(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 2, 'start_type': 'month', 'added_value': 3, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 3, 'action_with_unused_accruals': 'postponed', 'first_day': 31, }), (0, 0, { 'start_count': 3, 'start_type': 'month', 'added_value': 6, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 6, 'action_with_unused_accruals': 'postponed', 'first_day': 31, }), (0, 0, { 'start_count': 4, 'start_type': 'month', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 100, 'action_with_unused_accruals': 'postponed', 'first_day': 31, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual Allocation - Test', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': datetime.date(2022, 1, 31), }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-7-20'): allocation._update_accrual() # The first level gives 3 days # The second level could give 6 days but since the first level was already giving # 3 days, the second level gives 3 days to reach the second level's limit. # The third level gives 1 day since it only counts for one iteration. self.assertEqual(allocation.number_of_days, 7) def test_accrual_lost(self): # Test that when an allocation is made in the past and the second level is technically reached # that the first level is not skipped completely. accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [ (0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 100, 'action_with_unused_accruals': 'lost', }), ], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual Allocation - Test', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': datetime.date(2022, 1, 1), }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-4-4'): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 3, "Invalid number of days") def test_accrual_lost_previous_days(self): # Test that when an allocation with two levels is made and that the first level has it's action # with unused accruals set as lost that the days are effectively lost accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [ (0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 12, 'action_with_unused_accruals': 'lost', }), (0, 0, { 'start_count': 1, 'start_type': 'year', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'monthly', 'maximum_leave': 12, 'action_with_unused_accruals': 'lost', }), ], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual Allocation - Test', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': datetime.date(2021, 1, 1), }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-4-4'): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 4, "Invalid number of days") def test_accrual_lost_first_january(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [ (0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 3, 'added_value_type': 'days', 'frequency': 'yearly', 'maximum_leave': 12, 'action_with_unused_accruals': 'lost', }) ], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual Allocation - Test', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': datetime.date(2019, 1, 1), }) allocation.action_confirm() allocation.action_validate() with freeze_time('2022-4-1'): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 3, "Invalid number of days") def test_accrual_maximum_leaves(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 5, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2021-09-03', }) with freeze_time(datetime.date(2021, 10, 3)): allocation.action_confirm() allocation.action_validate() allocation._update_accrual() self.assertEqual(allocation.number_of_days, 5, "Should accrue maximum 5 days") def test_accrual_maximum_leaves_no_limit(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 1, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'daily', 'maximum_leave': 0, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2021-09-03', }) with freeze_time(datetime.date(2021, 10, 3)): allocation.action_confirm() allocation.action_validate() allocation._update_accrual() self.assertEqual(allocation.number_of_days, 29, "No limits for accrued days") def test_accrual_leaves_taken_maximum(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'days', 'frequency': 'weekly', 'week_day': 'mon', 'maximum_leave': 5, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2022-01-01', }) allocation.action_confirm() allocation.action_validate() with freeze_time(datetime.date(2022, 3, 2)): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 5, "Maximum of 5 days accrued") leave = self.env['hr.leave'].create({ 'name': 'leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': '2022-03-07 00:00:00', 'date_to': '2022-03-11 23:59:59', }) leave.action_validate() with freeze_time(datetime.date(2022, 6, 1)): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 10, "Should accrue 5 additional days") def test_accrual_leaves_taken_maximum_hours(self): accrual_plan = self.env['hr.leave.accrual.plan'].with_context(tracking_disable=True).create({ 'name': 'Accrual Plan For Test', 'level_ids': [(0, 0, { 'start_count': 0, 'start_type': 'day', 'added_value': 1, 'added_value_type': 'hours', 'frequency': 'weekly', 'week_day': 'mon', 'maximum_leave': 10, })], }) allocation = self.env['hr.leave.allocation'].with_user(self.user_hrmanager_id).with_context(tracking_disable=True).create({ 'name': 'Accrual allocation for employee', 'accrual_plan_id': accrual_plan.id, 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'number_of_days': 0, 'allocation_type': 'accrual', 'date_from': '2022-01-01', }) allocation.action_confirm() allocation.action_validate() with freeze_time(datetime.date(2022, 4, 1)): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 10 / self.hours_per_day, "Maximum of 10 hours accrued") leave = self.env['hr.leave'].create({ 'name': 'leave', 'employee_id': self.employee_emp.id, 'holiday_status_id': self.leave_type.id, 'date_from': '2022-03-07 00:00:00', 'date_to': '2022-03-07 23:59:59' }) leave.action_validate() with freeze_time(datetime.date(2022, 6, 1)): allocation._update_accrual() self.assertEqual(allocation.number_of_days, 18 / self.hours_per_day, "Should accrue 8 additional hours")
48.103854
44,929
10,157
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tests from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon from odoo.exceptions import AccessError, UserError import time @tests.tagged('access_rights', 'post_install', '-at_install') class TestAllocationRights(TestHrHolidaysCommon): def setUp(self): super().setUp() self.rd_dept.manager_id = False self.hr_dept.manager_id = False self.employee_emp.parent_id = False self.employee_emp.leave_manager_id = False self.lt_no_allocation = self.env['hr.leave.type'].create({ 'name': 'Validation = HR', 'allocation_validation_type': 'officer', 'requires_allocation': 'no', 'employee_requests': 'yes', }) self.lt_validation_manager = self.env['hr.leave.type'].create({ 'name': 'Validation = manager', 'allocation_validation_type': 'officer', 'requires_allocation': 'yes', 'employee_requests': 'yes', }) self.lt_allocation_manager = self.env['hr.leave.type'].create({ 'name': 'Validation = manager', 'allocation_validation_type': 'set', 'requires_allocation': 'yes', 'employee_requests': 'no', }) self.lt_allocation_no_validation = self.env['hr.leave.type'].create({ 'name': 'Validation = user', 'allocation_validation_type': 'no', 'requires_allocation': 'yes', 'employee_requests': 'yes', }) def request_allocation(self, user, values={}): values = dict(values, **{ 'name': 'Allocation', 'number_of_days': 1, 'date_from': time.strftime('%Y-01-01'), 'date_to': time.strftime('%Y-12-31'), }) return self.env['hr.leave.allocation'].with_user(user).create(values) class TestAccessRightsSimpleUser(TestAllocationRights): def test_simple_user_request_allocation(self): """ A simple user can request an allocation but not approve it """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_employee.id, values) with self.assertRaises(UserError): allocation.action_validate() def test_simple_user_request_fixed_allocation(self): """ A simple user cannot request an allocation if employee requests is not enabled """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_allocation_manager.id, } with self.assertRaises(AccessError): self.request_allocation(self.user_employee.id, values) def test_simple_user_request_allocation_no_validation(self): """ A simple user can request and automatically validate an allocation with no validation """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_allocation_no_validation.id, } allocation = self.request_allocation(self.user_employee.id, values) self.assertEqual(allocation.state, 'validate', "It should be validated") def test_simple_user_request_allocation_no_validation_other(self): """ A simple user cannot request an other user's allocation with no validation """ values = { 'employee_id': self.employee_hruser.id, 'holiday_status_id': self.lt_allocation_no_validation.id, } with self.assertRaises(AccessError): self.request_allocation(self.user_employee.id, values) def test_simple_user_reset_to_draft(self): """ A simple user can reset to draft only his own allocation """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_employee.id, values) self.assertEqual(allocation.state, 'draft') allocation.action_confirm() self.assertEqual(allocation.state, 'confirm', "It should be confirmed") allocation.action_draft() self.assertEqual(allocation.state, 'draft', "It should have been reset to draft") class TestAccessRightsEmployeeManager(TestAllocationRights): def setUp(self): super().setUp() self.managed_employee = self.env['hr.employee'].create({ 'name': 'Jolly Jumper', 'leave_manager_id': self.user_employee.id, }) def test_manager_request_allocation_other(self): """ A manager cannot request and approve an allocation for employees he doesn't manage """ values = { 'employee_id': self.employee_hruser.id, 'holiday_status_id': self.lt_validation_manager.id, } with self.assertRaises(AccessError): self.request_allocation(self.user_employee.id, values) # user is not the employee's manager def test_manager_approve_request_allocation(self): """ A manager can request and approve an allocation for managed employees """ values = { 'employee_id': self.managed_employee.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_employee.id, values) allocation.action_confirm() allocation.action_validate() self.assertEqual(allocation.state, 'validate', "The allocation should be validated") def test_manager_refuse_request_allocation(self): """ A manager can request and refuse an allocation for managed employees """ values = { 'employee_id': self.managed_employee.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_employee.id, values) allocation.action_confirm() allocation.action_refuse() self.assertEqual(allocation.state, 'refuse', "The allocation should be validated") def test_manager_batch_allocation(self): """ A manager cannot create batch allocation """ values = { 'holiday_status_id': self.lt_validation_manager.id, 'holiday_type': 'company', 'mode_company_id': self.user_employee.company_id.id, } with self.assertRaises(AccessError): self.request_allocation(self.user_employee.id, values) def test_manager_approve_own(self): """ A manager cannot approve his own allocation """ values = { 'employee_id': self.user_employee.employee_id.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_employee.id, values) with self.assertRaises(UserError): allocation.action_validate() class TestAccessRightsHolidayUser(TestAllocationRights): def test_holiday_user_request_allocation(self): """ A holiday user can request and approve an allocation for any employee """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_hruser.id, values) allocation.action_confirm() allocation.action_validate() self.assertEqual(allocation.state, 'validate', "It should have been validated") def test_holiday_user_request_fixed_allocation(self): """ A holiday user can request and approve an allocation if set by HR """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_allocation_manager.id, } allocation = self.request_allocation(self.user_hruser.id, values) allocation.action_confirm() allocation.action_validate() self.assertEqual(allocation.state, 'validate', "It should have been validated") def test_holiday_user_batch_allocation(self): """ A holiday user cannot create a batch allocation """ values = { 'holiday_status_id': self.lt_validation_manager.id, 'holiday_type': 'company', 'mode_company_id': self.user_employee.company_id.id, } with self.assertRaises(AccessError): self.request_allocation(self.user_hruser.id, values) def test_holiday_user_cannot_approve_own(self): """ A holiday user cannot approve his own allocation """ values = { 'employee_id': self.employee_hruser.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_hruser.id, values) allocation.action_confirm() with self.assertRaises(UserError): allocation.action_validate() class TestAccessRightsHolidayManager(TestAllocationRights): def test_holiday_manager_can_approve_own(self): """ A holiday manager can approve his own allocation """ values = { 'employee_id': self.employee_hrmanager.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_hrmanager.id, values) allocation.action_confirm() allocation.action_validate() self.assertEqual(allocation.state, 'validate', "It should have been validated") def test_holiday_manager_refuse_validated(self): """ A holiday manager can refuse a validated allocation """ values = { 'employee_id': self.employee_emp.id, 'holiday_status_id': self.lt_validation_manager.id, } allocation = self.request_allocation(self.user_hrmanager.id, values) allocation.action_confirm() allocation.action_validate() self.assertEqual(allocation.state, 'validate', "It should have been validated") allocation.action_refuse() self.assertEqual(allocation.state, 'refuse', "It should have been refused")
42.145228
10,157
13,840
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, datetime from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged('company_leave') class TestCompanyLeave(TransactionCase): """ Test leaves for a whole company, conflict resolutions """ @classmethod def setUpClass(cls): super(TestCompanyLeave, cls).setUpClass() cls.company = cls.env['res.company'].create({'name': 'A company'}) cls.bank_holiday = cls.env['hr.leave.type'].create({ 'name': 'Bank Holiday', 'responsible_id': cls.env.user.id, 'company_id': cls.company.id, 'requires_allocation': 'no', }) cls.paid_time_off = cls.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'request_unit': 'day', 'leave_validation_type': 'both', 'company_id': cls.company.id, 'requires_allocation': 'no', }) cls.employee = cls.env['hr.employee'].create({ 'name': 'My Employee', 'company_id': cls.company.id, }) def test_leave_whole_company_01(self): # TEST CASE 1: Leaves taken in days. Take a 3 days leave # Add a company leave on the second day. # Check that leave is split into 2. leave = self.env['hr.leave'].create({ 'name': 'Hol11', 'employee_id': self.employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 1, 7), 'date_from': date(2020, 1, 7), 'request_date_to': date(2020, 1, 9), 'date_to': date(2020, 1, 9), 'number_of_days': 3, }) leave._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 1, 8), 'request_date_from': date(2020, 1, 8), 'date_to': date(2020, 1, 8), 'request_date_to': date(2020, 1, 8), 'number_of_days': 1, }) company_leave._compute_date_from_to() company_leave.action_validate() all_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee.id)], order='id') self.assertEqual(len(all_leaves), 4) # Original Leave self.assertEqual(leave.state, 'refuse') # before leave self.assertEqual(all_leaves[1].date_from, datetime(2020, 1, 7, 7, 0)) self.assertEqual(all_leaves[1].date_to, datetime(2020, 1, 7, 16, 0)) self.assertEqual(all_leaves[1].number_of_days, 1) self.assertEqual(all_leaves[1].state, 'confirm') # After leave self.assertEqual(all_leaves[2].date_from, datetime(2020, 1, 9, 7, 0)) self.assertEqual(all_leaves[2].date_to, datetime(2020, 1, 9, 16, 0)) self.assertEqual(all_leaves[2].number_of_days, 1) self.assertEqual(all_leaves[2].state, 'confirm') # Company Leave self.assertEqual(all_leaves[3].date_from, datetime(2020, 1, 8, 7, 0)) self.assertEqual(all_leaves[3].date_to, datetime(2020, 1, 8, 16, 0)) self.assertEqual(all_leaves[3].number_of_days, 1) self.assertEqual(all_leaves[3].state, 'validate') def test_leave_whole_company_02(self): # TEST CASE 2: Leaves taken in half-days. Take a 3 days leave # Add a company leave on the second day # Check that leave is split into 2 self.paid_time_off.request_unit = 'half_day' leave = self.env['hr.leave'].create({ 'name': 'Hol11', 'employee_id': self.employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 1, 7), 'date_from': date(2020, 1, 7), 'request_date_to': date(2020, 1, 9), 'date_to': date(2020, 1, 9), 'number_of_days': 3, }) leave._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 1, 8), 'request_date_from': date(2020, 1, 8), 'date_to': date(2020, 1, 8), 'request_date_to': date(2020, 1, 8), 'number_of_days': 1, }) company_leave._compute_date_from_to() company_leave.action_validate() all_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee.id)], order='id') self.assertEqual(len(all_leaves), 4) # Original Leave self.assertEqual(leave.state, 'refuse') # before leave self.assertEqual(all_leaves[1].date_from, datetime(2020, 1, 7, 7, 0)) self.assertEqual(all_leaves[1].date_to, datetime(2020, 1, 7, 16, 0)) self.assertEqual(all_leaves[1].number_of_days, 1) self.assertEqual(all_leaves[1].state, 'confirm') # After leave self.assertEqual(all_leaves[2].date_from, datetime(2020, 1, 9, 7, 0)) self.assertEqual(all_leaves[2].date_to, datetime(2020, 1, 9, 16, 0)) self.assertEqual(all_leaves[2].number_of_days, 1) self.assertEqual(all_leaves[2].state, 'confirm') # Company Leave self.assertEqual(all_leaves[3].date_from, datetime(2020, 1, 8, 7, 0)) self.assertEqual(all_leaves[3].date_to, datetime(2020, 1, 8, 16, 0)) self.assertEqual(all_leaves[3].number_of_days, 1) self.assertEqual(all_leaves[3].state, 'validate') def test_leave_whole_company_03(self): # TEST CASE 3: Leaves taken in half-days. Take a 0.5 days leave # Add a company leave on the same day # Check that leave refused self.paid_time_off.request_unit = 'half_day' leave = self.env['hr.leave'].create({ 'name': 'Hol11', 'employee_id': self.employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 1, 7), 'request_date_to': date(2020, 1, 7), 'number_of_days': 0.5, 'request_unit_half': True, 'request_date_from_period': 'am', }) leave._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 1, 7), 'request_date_from': date(2020, 1, 7), 'date_to': date(2020, 1, 7), 'request_date_to': date(2020, 1, 7), 'number_of_days': 1, }) company_leave._compute_date_from_to() company_leave.action_validate() all_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee.id)], order='id') self.assertEqual(len(all_leaves), 2) # Original Leave self.assertEqual(leave.state, 'refuse') # Company Leave self.assertEqual(all_leaves[1].date_from, datetime(2020, 1, 7, 7, 0)) self.assertEqual(all_leaves[1].date_to, datetime(2020, 1, 7, 16, 0)) self.assertEqual(all_leaves[1].number_of_days, 1) self.assertEqual(all_leaves[1].state, 'validate') def test_leave_whole_company_04(self): # TEST CASE 4: Leaves taken in days. Take a 1 days leave # Add a company leave on the same day # Check that leave is refused self.paid_time_off.request_unit = 'day' leave = self.env['hr.leave'].create({ 'name': 'Hol11', 'employee_id': self.employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 1, 9), 'request_date_to': date(2020, 1, 9), 'number_of_days': 1, }) leave._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 1, 9), 'request_date_from': date(2020, 1, 9), 'date_to': date(2020, 1, 9), 'request_date_to': date(2020, 1, 9), 'number_of_days': 1, }) company_leave._compute_date_from_to() company_leave.action_validate() all_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee.id)], order='id') self.assertEqual(len(all_leaves), 2) # Original Leave self.assertEqual(leave.state, 'refuse') # Company Leave self.assertEqual(all_leaves[1].date_from, datetime(2020, 1, 9, 7, 0)) self.assertEqual(all_leaves[1].date_to, datetime(2020, 1, 9, 16, 0)) self.assertEqual(all_leaves[1].number_of_days, 1) self.assertEqual(all_leaves[1].state, 'validate') def test_leave_whole_company_06(self): # Test case 6: Leaves taken in days. But the employee # only works on Monday, Wednesday and Friday # Takes a time off for all the week (3 days), should be split self.employee.resource_calendar_id.write({'attendance_ids': [ (5, 0, 0), (0, 0, {'name': 'Monday Morning', 'dayofweek': '0', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Monday Afternoon', 'dayofweek': '0', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Wednesday Morning', 'dayofweek': '2', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Wednesday Afternoon', 'dayofweek': '2', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}), (0, 0, {'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}), (0, 0, {'name': 'Friday Afternoon', 'dayofweek': '4', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}) ]}) leave = self.env['hr.leave'].create({ 'name': 'Hol11', 'employee_id': self.employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 1, 6), 'request_date_to': date(2020, 1, 10), 'number_of_days': 3, }) leave._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 1, 10), 'request_date_from': date(2020, 1, 10), 'date_to': date(2020, 1, 10), 'request_date_to': date(2020, 1, 10), 'number_of_days': 1, }) company_leave._compute_date_from_to() company_leave.action_validate() all_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee.id)], order='id') self.assertEqual(len(all_leaves), 3) # Original Leave self.assertEqual(leave.state, 'refuse') # before leave self.assertEqual(all_leaves[1].date_from, datetime(2020, 1, 6, 7, 0)) self.assertEqual(all_leaves[1].date_to, datetime(2020, 1, 9, 16, 0)) self.assertEqual(all_leaves[1].number_of_days, 2) self.assertEqual(all_leaves[1].state, 'confirm') # Company Leave self.assertEqual(all_leaves[2].date_from, datetime(2020, 1, 10, 7, 0)) self.assertEqual(all_leaves[2].date_to, datetime(2020, 1, 10, 16, 0)) self.assertEqual(all_leaves[2].number_of_days, 1) self.assertEqual(all_leaves[2].state, 'validate') def test_leave_whole_company_07(self): # Test Case 7: Try to create a bank holidays for a lot of # employees, and check the performances # 100 employees - 15 already on holidays that day employees = self.env['hr.employee'].create([{ 'name': 'Employee %s' % i, 'company_id': self.company.id } for i in range(100)]) leaves = self.env['hr.leave'].create([{ 'name': 'Holiday - %s' % employee.name, 'employee_id': employee.id, 'holiday_status_id': self.paid_time_off.id, 'request_date_from': date(2020, 3, 29), 'date_from': datetime(2020, 3, 29, 7, 0, 0), 'request_date_to': date(2020, 4, 1), 'date_to': datetime(2020, 4, 1, 19, 0, 0), 'number_of_days': 3, } for employee in employees[0:15]]) leaves._compute_date_from_to() company_leave = self.env['hr.leave'].create({ 'name': 'Bank Holiday', 'holiday_type': 'company', 'mode_company_id': self.company.id, 'holiday_status_id': self.bank_holiday.id, 'date_from': date(2020, 4, 1), 'request_date_from': date(2020, 4, 1), 'date_to': date(2020, 4, 1), 'request_date_to': date(2020, 4, 1), 'number_of_days': 1, }) company_leave._compute_date_from_to() with self.assertQueryCount(__system__=774, admin=867): # 770 community # Original query count: 1987 # Without tracking/activity context keys: 5154 company_leave.action_validate() leaves = self.env['hr.leave'].search([('holiday_status_id', '=', self.bank_holiday.id)]) self.assertEqual(len(leaves), 102)
42.453988
13,840
2,252
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 TestHrHolidaysCommon(common.TransactionCase): def setUp(self): super(TestHrHolidaysCommon, self).setUp() self.env.user.tz = 'Europe/Brussels' # Test users to use through the various tests self.user_hruser = mail_new_test_user(self.env, login='armande', groups='base.group_user,hr_holidays.group_hr_holidays_user') self.user_hruser_id = self.user_hruser.id self.user_hrmanager = mail_new_test_user(self.env, login='bastien', groups='base.group_user,hr_holidays.group_hr_holidays_manager') self.user_hrmanager_id = self.user_hrmanager.id self.user_employee = mail_new_test_user(self.env, login='david', groups='base.group_user') self.user_employee_id = self.user_employee.id # Hr Data Department = self.env['hr.department'].with_context(tracking_disable=True) self.hr_dept = Department.create({ 'name': 'Human Resources', }) self.rd_dept = Department.create({ 'name': 'Research and devlopment', }) self.employee_emp = self.env['hr.employee'].create({ 'name': 'David Employee', 'user_id': self.user_employee_id, 'department_id': self.rd_dept.id, }) self.employee_emp_id = self.employee_emp.id self.employee_hruser = self.env['hr.employee'].create({ 'name': 'Armande HrUser', 'user_id': self.user_hruser_id, 'department_id': self.rd_dept.id, }) self.employee_hruser_id = self.employee_hruser.id self.employee_hrmanager = self.env['hr.employee'].create({ 'name': 'Bastien HrManager', 'user_id': self.user_hrmanager_id, 'department_id': self.hr_dept.id, 'parent_id': self.employee_hruser_id, }) self.employee_hrmanager_id = self.employee_hrmanager.id self.rd_dept.write({'manager_id': self.employee_hruser_id}) self.hours_per_day = self.employee_emp.resource_id.calendar_id.hours_per_day or 8
39.508772
2,252
14,151
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from datetime import datetime from dateutil.relativedelta import relativedelta from freezegun import freeze_time from psycopg2 import IntegrityError from odoo import fields from odoo.exceptions import AccessError, ValidationError, UserError from odoo.tools import mute_logger, test_reports from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon class TestHolidaysFlow(TestHrHolidaysCommon): @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_00_leave_request_flow_unlimited(self): """ Testing leave request flow: unlimited type of leave request """ Requests = self.env['hr.leave'] HolidaysStatus = self.env['hr.leave.type'] # HrManager creates some holiday statuses HolidayStatusManagerGroup = HolidaysStatus.with_user(self.user_hrmanager_id) HolidayStatusManagerGroup.create({ 'name': 'WithMeetingType', 'requires_allocation': 'no', }) self.holidays_status_hr = HolidayStatusManagerGroup.create({ 'name': 'NotLimitedHR', 'requires_allocation': 'no', 'leave_validation_type': 'hr', }) self.holidays_status_manager = HolidayStatusManagerGroup.create({ 'name': 'NotLimitedManager', 'requires_allocation': 'no', 'leave_validation_type': 'manager', }) HolidaysEmployeeGroup = Requests.with_user(self.user_employee_id) # Employee creates a leave request in a no-limit category hr manager only hol1_employee_group = HolidaysEmployeeGroup.create({ 'name': 'Hol11', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_status_hr.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': datetime.today(), 'number_of_days': 1, }) hol1_user_group = hol1_employee_group.with_user(self.user_hruser_id) hol1_manager_group = hol1_employee_group.with_user(self.user_hrmanager_id) self.assertEqual(hol1_user_group.state, 'confirm', 'hr_holidays: newly created leave request should be in confirm state') # HrUser validates the employee leave request -> should work hol1_user_group.action_approve() self.assertEqual(hol1_manager_group.state, 'validate', 'hr_holidays: validated leave request should be in validate state') # Employee creates a leave request in a no-limit category department manager only hol12_employee_group = HolidaysEmployeeGroup.create({ 'name': 'Hol12', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_status_manager.id, 'date_from': (datetime.today() + relativedelta(days=12)), 'date_to': (datetime.today() + relativedelta(days=13)), 'number_of_days': 1, }) hol12_user_group = hol12_employee_group.with_user(self.user_hruser_id) hol12_manager_group = hol12_employee_group.with_user(self.user_hrmanager_id) self.assertEqual(hol12_user_group.state, 'confirm', 'hr_holidays: newly created leave request should be in confirm state') # HrManager validate the employee leave request hol12_manager_group.action_approve() self.assertEqual(hol1_user_group.state, 'validate', 'hr_holidays: validates leave request should be in validate state') @mute_logger('odoo.addons.base.models.ir_model', 'odoo.models') def test_01_leave_request_flow_limited(self): """ Testing leave request flow: limited type of leave request """ with freeze_time('2022-01-15'): Requests = self.env['hr.leave'] Allocations = self.env['hr.leave.allocation'] HolidaysStatus = self.env['hr.leave.type'] holiday_status_paid_time_off = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'requires_allocation': 'yes', 'employee_requests': 'no', 'allocation_validation_type': 'set', 'leave_validation_type': 'both', 'responsible_id': self.env.ref('base.user_admin').id, }) self.env['hr.leave.allocation'].create([ { 'name': 'Paid Time off for David', 'holiday_status_id': holiday_status_paid_time_off.id, 'number_of_days': 20, 'employee_id': self.employee_emp_id, 'state': 'validate', 'date_from': time.strftime('%Y-%m-01'), }, { 'name': 'Paid Time off for David', 'holiday_status_id': holiday_status_paid_time_off.id, 'number_of_days': 20, 'employee_id': self.ref('hr.employee_admin'), 'state': 'validate', 'date_from': time.strftime('%Y-%m-01'), } ]) def _check_holidays_status(holiday_status, ml, lt, rl, vrl): self.assertEqual(holiday_status.max_leaves, ml, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.leaves_taken, lt, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.remaining_leaves, rl, 'hr_holidays: wrong type days computation') self.assertEqual(holiday_status.virtual_remaining_leaves, vrl, 'hr_holidays: wrong type days computation') # HrManager creates some holiday statuses HolidayStatusManagerGroup = HolidaysStatus.with_user(self.user_hrmanager_id) HolidayStatusManagerGroup.create({ 'name': 'WithMeetingType', 'requires_allocation': 'no', }) self.holidays_status_limited = HolidayStatusManagerGroup.create({ 'name': 'Limited', 'requires_allocation': 'yes', 'employee_requests': 'no', 'allocation_validation_type': 'set', 'leave_validation_type': 'both', }) HolidaysEmployeeGroup = Requests.with_user(self.user_employee_id) # HrUser allocates some leaves to the employee aloc1_user_group = Allocations.with_user(self.user_hruser_id).create({ 'name': 'Days for limited category', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_status_limited.id, 'number_of_days': 2, 'state': 'confirm', 'date_from': time.strftime('%Y-%m-01'), }) # HrUser validates the first step # HrManager validates the second step aloc1_user_group.with_user(self.user_hrmanager_id).action_validate() # Checks Employee has effectively some days left hol_status_2_employee_group = self.holidays_status_limited.with_user(self.user_employee_id) _check_holidays_status(hol_status_2_employee_group, 2.0, 0.0, 2.0, 2.0) # Employee creates a leave request in the limited category, now that he has some days left hol2 = HolidaysEmployeeGroup.create({ 'name': 'Hol22', 'employee_id': self.employee_emp_id, 'holiday_status_id': self.holidays_status_limited.id, 'date_from': (datetime.today() + relativedelta(days=2)).strftime('%Y-%m-%d %H:%M'), 'date_to': (datetime.today() + relativedelta(days=3)), 'number_of_days': 1, }) hol2_user_group = hol2.with_user(self.user_hruser_id) # Check left days: - 1 virtual remaining day hol_status_2_employee_group.invalidate_cache() _check_holidays_status(hol_status_2_employee_group, 2.0, 0.0, 2.0, 1.0) # HrManager validates the second step hol2_user_group.with_user(self.user_hrmanager_id).action_validate() self.assertEqual(hol2.state, 'validate', 'hr_holidays: second validation should lead to validate state') # Check left days: - 1 day taken _check_holidays_status(hol_status_2_employee_group, 2.0, 1.0, 1.0, 1.0) # HrManager finds an error: he refuses the leave request hol2.with_user(self.user_hrmanager_id).action_refuse() self.assertEqual(hol2.state, 'refuse', 'hr_holidays: refuse should lead to refuse state') # Check left days: 2 days left again hol_status_2_employee_group.invalidate_cache(['max_leaves']) _check_holidays_status(hol_status_2_employee_group, 2.0, 0.0, 2.0, 2.0) self.assertEqual(hol2.state, 'refuse', 'hr_holidays: hr_user should not be able to reset a refused leave request') # HrManager resets the request hol2_manager_group = hol2.with_user(self.user_hrmanager_id) hol2_manager_group.action_draft() self.assertEqual(hol2.state, 'draft', 'hr_holidays: resetting should lead to draft state') employee_id = self.ref('hr.employee_admin') # cl can be of maximum 20 days for employee_admin hol3_status = holiday_status_paid_time_off.with_context(employee_id=employee_id) # I assign the dates in the holiday request for 1 day hol3 = Requests.create({ 'name': 'Sick Time Off', 'holiday_status_id': hol3_status.id, 'date_from': datetime.today().strftime('%Y-%m-10 10:00:00'), 'date_to': datetime.today().strftime('%Y-%m-11 19:00:00'), 'employee_id': employee_id, 'number_of_days': 1, }) # I find a small mistake on my leave request to I click on "Refuse" button to correct a mistake. hol3.action_refuse() self.assertEqual(hol3.state, 'refuse', 'hr_holidays: refuse should lead to refuse state') # I again set to draft and then confirm. hol3.action_draft() self.assertEqual(hol3.state, 'draft', 'hr_holidays: resetting should lead to draft state') hol3.action_confirm() self.assertEqual(hol3.state, 'confirm', 'hr_holidays: confirming should lead to confirm state') # I validate the holiday request by clicking on "To Approve" button. hol3.action_validate() self.assertEqual(hol3.state, 'validate', 'hr_holidays: validation should lead to validate state') # Check left days for casual leave: 19 days left _check_holidays_status(hol3_status, 20.0, 1.0, 19.0, 19.0) def test_10_leave_summary_reports(self): # Print the HR Holidays(Summary Employee) Report through the wizard ctx = { 'model': 'hr.employee', 'active_ids': [self.ref('hr.employee_admin')] } data_dict = { 'date_from': datetime.today().strftime('%Y-%m-01'), 'emp': [(6, 0, [self.ref('hr.employee_admin')])], 'holiday_type': 'Approved' } self.env.company.external_report_layout_id = self.env.ref('web.external_layout_standard').id test_reports.try_report_action(self.env.cr, self.env.uid, 'action_hr_holidays_summary_employee', wiz_data=data_dict, context=ctx, our_module='hr_holidays') def test_sql_constraint_dates(self): # The goal is mainly to verify that a human friendly # error message is triggered if the date_from is after # date_to. Coming from a bug due to the new ORM 13.0 holiday_status_paid_time_off = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'requires_allocation': 'yes', 'employee_requests': 'no', 'allocation_validation_type': 'set', 'leave_validation_type': 'both', 'responsible_id': self.env.ref('base.user_admin').id, }) self.env['hr.leave.allocation'].create({ 'name': 'Paid Time off for David', 'holiday_status_id': holiday_status_paid_time_off.id, 'number_of_days': 20, 'employee_id': self.ref('hr.employee_admin'), 'state': 'validate', 'date_from': time.strftime('%Y-%m-01'), 'date_to': time.strftime('%Y-12-31'), }) leave_vals = { 'name': 'Sick Time Off', 'holiday_status_id': holiday_status_paid_time_off.id, 'date_from': datetime.today().strftime('%Y-%m-11 19:00:00'), 'date_to': datetime.today().strftime('%Y-%m-10 10:00:00'), 'employee_id': self.ref('hr.employee_admin'), 'number_of_days': 1, } with mute_logger('odoo.sql_db'): with self.assertRaises(IntegrityError): with self.cr.savepoint(): self.env['hr.leave'].create(leave_vals) leave_vals = { 'name': 'Sick Time Off', 'holiday_status_id': holiday_status_paid_time_off.id, 'date_from': datetime.today().strftime('%Y-%m-10 10:00:00'), 'date_to': datetime.today().strftime('%Y-%m-11 19:00:00'), 'employee_id': self.ref('hr.employee_admin'), 'number_of_days': 1, } leave = self.env['hr.leave'].create(leave_vals) with mute_logger('odoo.sql_db'): with self.assertRaises(IntegrityError): # No ValidationError with self.cr.savepoint(): leave.write({ 'date_from': datetime.today().strftime('%Y-%m-11 19:00:00'), 'date_to': datetime.today().strftime('%Y-%m-10 10:00:00'), })
49.135417
14,151
2,623
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date from dateutil.relativedelta import relativedelta from odoo import Command from odoo.tests.common import tagged, TransactionCase from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT @tagged('post_install', '-at_install') class TestPartner(TransactionCase): def setUp(self): super().setUp() # use a single value for today throughout the tests to avoid weird scenarios around midnight self.today = date.today() baseUser = self.env['res.users'].create({ 'email': 'e.e@example.com', 'groups_id': [Command.link(self.env.ref('base.group_user').id)], 'login': 'emp', 'name': 'Ernest Employee', 'notification_type': 'inbox', 'signature': '--\nErnest', }) self.partner = baseUser.partner_id self.users = baseUser + self.env['res.users'].create({ 'name': 'test1', 'login': 'test1', 'email': 'test1@example.com', 'partner_id': self.partner.id, }) self.employees = self.env['hr.employee'].create([{ 'user_id': user.id, } for user in self.users]) self.leave_type = self.env['hr.leave.type'].create({ 'leave_validation_type': 'no_validation', 'requires_allocation': 'no', 'name': 'Legal Leaves', 'time_type': 'leave', }) def test_res_partner_mail_partner_format(self): self.assertEqual( self.partner.mail_partner_format()[self.partner]['out_of_office_date_end'], False, 'Partner is not considered out of office if one of their users is not on holiday', ) self.env['hr.leave'].create([{ 'date_from': self.today + relativedelta(days=-2), 'date_to': self.today + relativedelta(days=2), 'employee_id': self.employees[0].id, 'holiday_status_id': self.leave_type.id, }, { 'date_from': self.today + relativedelta(days=-2), 'date_to': self.today + relativedelta(days=3), 'employee_id': self.employees[1].id, 'holiday_status_id': self.leave_type.id, }]) self.assertEqual( self.partner.mail_partner_format()[self.partner]['out_of_office_date_end'], (self.today + relativedelta(days=2)).strftime(DEFAULT_SERVER_DATE_FORMAT), 'Return date is the first return date of all users associated with a partner', )
39.149254
2,623
4,607
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.addons.base.tests.common import TransactionCaseWithUserDemo from odoo.tests.common import tagged, users, warmup from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon @tagged('out_of_office') class TestOutOfOffice(TestHrHolidaysCommon): def setUp(self): super().setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Legal Leaves', 'time_type': 'leave', 'requires_allocation': 'no', }) def test_leave_ooo(self): self.assertNotEqual(self.employee_hruser.user_id.im_status, 'leave_offline', 'user should not be on leave') self.assertNotEqual(self.employee_hruser.user_id.partner_id.im_status, 'leave_offline', 'user should not be on leave') leave_date_end = (datetime.today() + relativedelta(days=3)) leave = self.env['hr.leave'].create({ 'name': 'Christmas', 'employee_id': self.employee_hruser.id, 'holiday_status_id': self.leave_type.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': leave_date_end, 'number_of_days': 4, }) leave.action_approve() self.assertEqual(self.employee_hruser.user_id.im_status, 'leave_offline', 'user should be out (leave_offline)') self.assertEqual(self.employee_hruser.user_id.partner_id.im_status, 'leave_offline', 'user should be out (leave_offline)') partner = self.employee_hruser.user_id.partner_id partner2 = self.user_employee.partner_id channel = self.env['mail.channel'].with_user(self.user_employee).with_context({ 'mail_create_nolog': True, 'mail_create_nosubscribe': True, }).create({ 'channel_partner_ids': [(4, partner.id), (4, partner2.id)], 'public': 'private', 'channel_type': 'chat', 'name': 'test' }) channel_info = channel.channel_info()[0] self.assertEqual(len(channel_info['members']), 2, "Channel info should get info for the 2 members") partner_info = next(c for c in channel_info['members'] if c['email'] == partner.email) partner2_info = next(c for c in channel_info['members'] if c['email'] == partner2.email) self.assertFalse(partner2_info['out_of_office_date_end'], "current user should not be out of office") self.assertEqual(partner_info['out_of_office_date_end'], leave_date_end.strftime(DEFAULT_SERVER_DATE_FORMAT), "correspondent should be out of office") @tagged('out_of_office') class TestOutOfOfficePerformance(TestHrHolidaysCommon, TransactionCaseWithUserDemo): def setUp(self): super(TestOutOfOfficePerformance, self).setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Legal Leaves', 'time_type': 'leave', 'requires_allocation': 'no', }) self.leave_date_end = (datetime.today() + relativedelta(days=3)) self.leave = self.env['hr.leave'].create({ 'name': 'Christmas', 'employee_id': self.employee_hruser_id, 'holiday_status_id': self.leave_type.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': (datetime.today() + relativedelta(days=3)), 'number_of_days': 4, }) self.hr_user = self.employee_hruser.user_id self.hr_partner = self.employee_hruser.user_id.partner_id self.employer_partner = self.user_employee.partner_id @users('__system__', 'demo') @warmup def test_leave_im_status_performance_partner_offline(self): with self.assertQueryCount(__system__=2, demo=2): self.assertEqual(self.employer_partner.im_status, 'offline') @users('__system__', 'demo') @warmup def test_leave_im_status_performance_user_leave_offline(self): self.leave.write({'state': 'validate'}) with self.assertQueryCount(__system__=2, demo=2): self.assertEqual(self.hr_user.im_status, 'leave_offline') @users('__system__', 'demo') @warmup def test_leave_im_status_performance_partner_leave_offline(self): self.leave.write({'state': 'validate'}) with self.assertQueryCount(__system__=2, demo=2): self.assertEqual(self.hr_partner.im_status, 'leave_offline')
45.166667
4,607
1,375
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.base.tests.common import HttpCase from odoo.tests.common import tagged from odoo.tests.common import users from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon @tagged('post_install', '-at_install') class TestHolidaysCalendar(HttpCase, TestHrHolidaysCommon): @users('admin') def test_hours_time_off_request_calendar_view(self): """ Testing the flow of clicking on a day, save the leave request directly and verify that the start/end time are correctly set """ self.env.user.tz = 'UTC' calendar = self.env.user.employee_id.resource_calendar_id.attendance_ids expected_start_thursday = calendar[6].hour_from expected_end_thursday = calendar[7].hour_to self.start_tour('/', 'time_off_request_calendar_view', login='admin') last_leave = self.env['hr.leave'].search([('employee_id.id', '=', self.env.user.employee_id.id)]).sorted(lambda leave: leave.create_date)[-1] self.assertEqual(last_leave.date_from.weekday(), 3, "It should be Thursday") self.assertEqual(last_leave.date_from.hour, expected_start_thursday, "Wrong start of the day") self.assertEqual(last_leave.date_to.hour, expected_end_thursday, "Wrong end of the day")
45.833333
1,375
1,442
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime from dateutil.relativedelta import relativedelta from odoo.exceptions import AccessError from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon class TestHrLeaveType(TestHrHolidaysCommon): def test_time_type(self): leave_type = self.env['hr.leave.type'].create({ 'name': 'Paid Time Off', 'time_type': 'leave', 'requires_allocation': 'no', }) leave_1 = self.env['hr.leave'].create({ 'name': 'Doctor Appointment', 'employee_id': self.employee_hruser_id, 'holiday_status_id': leave_type.id, 'date_from': (datetime.today() - relativedelta(days=1)), 'date_to': datetime.today(), 'number_of_days': 1, }) leave_1.action_approve() self.assertEqual( self.env['resource.calendar.leaves'].search([('holiday_id', '=', leave_1.id)]).time_type, 'leave' ) def test_type_creation_right(self): # HrUser creates some holiday statuses -> crash because only HrManagers should do this with self.assertRaises(AccessError): self.env['hr.leave.type'].with_user(self.user_hruser_id).create({ 'name': 'UserCheats', 'requires_allocation': 'no', })
34.333333
1,442
13,482
py
PYTHON
15.0
# -*- coding: utf-8 -*- from datetime import date, datetime from odoo.tests.common import Form from odoo.addons.hr_holidays.tests.common import TestHrHolidaysCommon from odoo.exceptions import ValidationError class TestAutomaticLeaveDates(TestHrHolidaysCommon): def setUp(self): super(TestAutomaticLeaveDates, self).setUp() self.leave_type = self.env['hr.leave.type'].create({ 'name': 'Automatic Test', 'time_type': 'leave', 'requires_allocation': 'no', }) def test_no_attendances(self): calendar = self.env['resource.calendar'].create({ 'name': 'No Attendances', 'attendance_ids': [(5, 0, 0)], }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0) self.assertEqual(leave_form.number_of_hours_text, '0 Hours') def test_single_attendance_on_morning_and_afternoon(self): calendar = self.env['resource.calendar'].create({ 'name': 'simple morning + afternoon', 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'monday morning', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '0', }), (0, 0, { 'name': 'monday afternoon', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon', 'dayofweek': '0', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, .5) self.assertEqual(leave_form.number_of_hours_text, '4 Hours') leave_form.request_date_from_period = 'pm' self.assertEqual(leave_form.number_of_days_display, .5) self.assertEqual(leave_form.number_of_hours_text, '4 Hours') def test_multiple_attendance_on_morning(self): calendar = self.env['resource.calendar'].create({ 'name': 'multi morning', 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'monday morning 1', 'hour_from': 8, 'hour_to': 10, 'day_period': 'morning', 'dayofweek': '0', }), (0, 0, { 'name': 'monday morning 2', 'hour_from': 10.25, 'hour_to': 12.25, 'day_period': 'morning', 'dayofweek': '0', }), (0, 0, { 'name': 'monday afternoon', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon', 'dayofweek': '0', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, .5) self.assertEqual(leave_form.number_of_hours_text, '4 Hours') leave_form.request_date_from_period = 'pm' self.assertEqual(leave_form.number_of_days_display, .5) self.assertEqual(leave_form.number_of_hours_text, '4 Hours') def test_attendance_on_morning(self): calendar = self.env['resource.calendar'].create({ 'name': 'Morning only', 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'Monday All day', 'hour_from': 8, 'hour_to': 16, 'day_period': 'morning', 'dayofweek': '0', })], }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True # Ask for morning leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0.5) self.assertEqual(leave_form.number_of_hours_text, '8 Hours') # Ask for afternoon leave_form.request_date_from_period = 'pm' self.assertEqual(leave_form.number_of_days_display, 0.5) self.assertEqual(leave_form.number_of_hours_text, '8 Hours') def test_attendance_next_day(self): self.env.user.tz = 'Europe/Brussels' calendar = self.env['resource.calendar'].create({ 'name': 'auto next day', 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'tuesday morning', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '1', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type # does not work on mondays leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0) self.assertEqual(leave_form.number_of_hours_text, '0 Hours') self.assertEqual(leave_form.date_from, datetime(2019, 9, 2, 6, 0, 0)) self.assertEqual(leave_form.date_to, datetime(2019, 9, 2, 10, 0, 0)) def test_attendance_previous_day(self): self.env.user.tz = 'Europe/Brussels' calendar = self.env['resource.calendar'].create({ 'name': 'auto next day', 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'monday morning', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '0', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type # does not work on tuesdays leave_form.request_date_from = date(2019, 9, 3) leave_form.request_date_to = date(2019, 9, 3) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0) self.assertEqual(leave_form.number_of_hours_text, '0 Hours') self.assertEqual(leave_form.date_from, datetime(2019, 9, 3, 6, 0, 0)) self.assertEqual(leave_form.date_to, datetime(2019, 9, 3, 10, 0, 0)) def test_2weeks_calendar(self): self.env.user.tz = 'Europe/Brussels' calendar = self.env['resource.calendar'].create({ 'name': 'auto next day', 'two_weeks_calendar': True, 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'monday morning odd week', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '0', 'week_type': '0', }), (0, 0, { 'name': 'monday morning even week', 'hour_from': 10, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '0', 'week_type': '1', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type # even week, works 2 hours leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0.5) self.assertEqual(leave_form.number_of_hours_text, '2 Hours') self.assertEqual(leave_form.date_from, datetime(2019, 9, 2, 8, 0, 0)) self.assertEqual(leave_form.date_to, datetime(2019, 9, 2, 10, 0, 0)) with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type # odd week, works 4 hours leave_form.request_date_from = date(2019, 9, 9) leave_form.request_date_to = date(2019, 9, 9) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0.5) self.assertEqual(leave_form.number_of_hours_text, '4 Hours') self.assertEqual(leave_form.date_from, datetime(2019, 9, 9, 6, 0, 0)) self.assertEqual(leave_form.date_to, datetime(2019, 9, 9, 10, 0, 0)) def test_2weeks_calendar_next_week(self): self.env.user.tz = 'Europe/Brussels' calendar = self.env['resource.calendar'].create({ 'name': 'auto next day', 'two_weeks_calendar': True, 'attendance_ids': [(5, 0, 0), (0, 0, { 'name': 'monday morning odd week', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning', 'dayofweek': '0', 'week_type': '0', })] }) employee = self.employee_emp employee.resource_calendar_id = calendar with Form(self.env['hr.leave'].with_context(default_employee_id=employee.id)) as leave_form: leave_form.holiday_status_id = self.leave_type # even week, does not work leave_form.request_date_from = date(2019, 9, 2) leave_form.request_date_to = date(2019, 9, 2) leave_form.request_unit_half = True leave_form.request_date_from_period = 'am' self.assertEqual(leave_form.number_of_days_display, 0) self.assertEqual(leave_form.number_of_hours_text, '0 Hours') self.assertEqual(leave_form.date_from, datetime(2019, 9, 2, 6, 0, 0)) self.assertEqual(leave_form.date_to, datetime(2019, 9, 2, 10, 0, 0))
46.171233
13,482
1,221
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 api, fields, models class HrDepartureWizard(models.TransientModel): _inherit = 'hr.departure.wizard' cancel_leaves = fields.Boolean("Cancel Future Leaves", default=True, help="Cancel all time off after this date.") archive_allocation = fields.Boolean("Archive Employee Allocations", default=True, help="Remove employee from existing accrual plans.") def action_register_departure(self): super(HrDepartureWizard, self).action_register_departure() if self.cancel_leaves: future_leaves = self.env['hr.leave'].search([('employee_id', '=', self.employee_id.id), ('date_to', '>', self.departure_date), ('state', '!=', 'refuse')]) future_leaves.write({'state': 'refuse'}) if self.archive_allocation: employee_allocations = self.env['hr.leave.allocation'].search([('employee_id', '=', self.employee_id.id)]) employee_allocations.action_archive()
45.222222
1,221
1,177
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo import api, fields, models class HolidaysSummaryEmployee(models.TransientModel): _name = 'hr.holidays.summary.employee' _description = 'HR Time Off Summary Report By Employee' date_from = fields.Date(string='From', required=True, default=lambda *a: time.strftime('%Y-%m-01')) emp = fields.Many2many('hr.employee', 'summary_emp_rel', 'sum_id', 'emp_id', string='Employee(s)') holiday_type = fields.Selection([ ('Approved', 'Approved'), ('Confirmed', 'Confirmed'), ('both', 'Both Approved and Confirmed') ], string='Select Time Off Type', required=True, default='Approved') def print_report(self): self.ensure_one() [data] = self.read() data['emp'] = self.env.context.get('active_ids', []) employees = self.env['hr.employee'].browse(data['emp']) datas = { 'ids': [], 'model': 'hr.employee', 'form': data } return self.env.ref('hr_holidays.action_report_holidayssummary').report_action(employees, data=datas)
37.967742
1,177
80,552
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com) import logging import pytz from collections import namedtuple, defaultdict from datetime import datetime, timedelta, time from pytz import timezone, UTC from odoo import api, fields, models, tools from odoo.addons.base.models.res_partner import _tz_get from odoo.addons.resource.models.resource import float_to_time, HOURS_PER_DAY from odoo.exceptions import AccessError, UserError, ValidationError from odoo.tools import float_compare, format_date from odoo.tools.float_utils import float_round from odoo.tools.translate import _ from odoo.osv import expression _logger = logging.getLogger(__name__) # Used to agglomerate the attendances in order to find the hour_from and hour_to # See _compute_date_from_to DummyAttendance = namedtuple('DummyAttendance', 'hour_from, hour_to, dayofweek, day_period, week_type') class HolidaysRequest(models.Model): """ Leave Requests Access specifications - a regular employee / user - can see all leaves; - cannot see name field of leaves belonging to other user as it may contain private information that we don't want to share to other people than HR people; - can modify only its own not validated leaves (except writing on state to bypass approval); - can discuss on its leave requests; - can reset only its own leaves; - cannot validate any leaves; - an Officer - can see all leaves; - can validate "HR" single validation leaves from people if - he is the employee manager; - he is the department manager; - he is member of the same department; - target employee has no manager and no department manager; - can validate "Manager" single validation leaves from people if - he is the employee manager; - he is the department manager; - target employee has no manager and no department manager; - can first validate "Both" double validation leaves from people like "HR" single validation, moving the leaves to validate1 state; - cannot validate its own leaves; - can reset only its own leaves; - can refuse all leaves; - a Manager - can do everything he wants On top of that multicompany rules apply based on company defined on the leave request leave type. """ _name = "hr.leave" _description = "Time Off" _order = "date_from desc" _inherit = ['mail.thread', 'mail.activity.mixin'] _mail_post_access = 'read' @api.model def default_get(self, fields_list): defaults = super(HolidaysRequest, self).default_get(fields_list) defaults = self._default_get_request_parameters(defaults) employee = self.env['hr.employee'].browse(defaults['employee_id']) if defaults.get('employee_id') else self.env.user.employee_id # In some cases, the context does not contain the employee's working time for the day requested if defaults.get('request_date_from') and defaults.get('request_date_to'): default_attendance_from, default_attendance_to = self._get_attendances(employee, defaults['request_date_from'], defaults['request_date_to']) defaults['date_from'] = self._get_start_or_end_from_attendance(default_attendance_from.hour_from, defaults['request_date_from'], employee) defaults['date_to'] = self._get_start_or_end_from_attendance(default_attendance_to.hour_to, defaults['request_date_to'], employee) if 'holiday_status_id' in fields_list and not defaults.get('holiday_status_id'): lt = self.env['hr.leave.type'].search(['|', ('requires_allocation', '=', 'no'), ('has_valid_allocation', '=', True)], limit=1) if lt: defaults['holiday_status_id'] = lt.id defaults['request_unit_custom'] = False if 'state' in fields_list and not defaults.get('state'): lt = self.env['hr.leave.type'].browse(defaults.get('holiday_status_id')) defaults['state'] = 'confirm' now = fields.Datetime.now() if 'date_from' not in defaults: defaults.update({'date_from': now}) if 'date_to' not in defaults: defaults.update({'date_to': now}) default_start_time = self._get_start_or_end_from_attendance(7, datetime.now().date(), employee).time() default_end_time = self._get_start_or_end_from_attendance(19, datetime.now().date(), employee).time() if defaults['date_from'].time() == default_start_time and defaults['date_to'].time() == default_end_time: date_from = defaults['date_from'].date() date_to = defaults['date_to'].date() attendance_from, attendance_to = self._get_attendances(employee, date_from, date_to) defaults['date_from'] = self._get_start_or_end_from_attendance(attendance_from.hour_from, date_from, employee) defaults['date_to'] = self._get_start_or_end_from_attendance(attendance_to.hour_to, date_to, employee) return defaults def _get_start_or_end_from_attendance(self, hour, date, employee): hour = float_to_time(float(hour)) holiday_tz = timezone(employee.tz or self.env.user.tz) return holiday_tz.localize(datetime.combine(date, hour)).astimezone(UTC).replace(tzinfo=None) def _get_attendances(self, employee, request_date_from, request_date_to): resource_calendar_id = employee.resource_calendar_id or self.env.company.resource_calendar_id domain = [('calendar_id', '=', resource_calendar_id.id), ('display_type', '=', False)] attendances = self.env['resource.calendar.attendance'].read_group(domain, ['ids:array_agg(id)', 'hour_from:min(hour_from)', 'hour_to:max(hour_to)', 'week_type', 'dayofweek', 'day_period'], ['week_type', 'dayofweek', 'day_period'], lazy=False) # Must be sorted by dayofweek ASC and day_period DESC attendances = sorted([DummyAttendance(group['hour_from'], group['hour_to'], group['dayofweek'], group['day_period'], group['week_type']) for group in attendances], key=lambda att: (att.dayofweek, att.day_period != 'morning')) default_value = DummyAttendance(0, 0, 0, 'morning', False) if resource_calendar_id.two_weeks_calendar: # find week type of start_date start_week_type = self.env['resource.calendar.attendance'].get_week_type(request_date_from) attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == start_week_type] attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != start_week_type] # First, add days of actual week coming after date_from attendance_filtred = [att for att in attendance_actual_week if int(att.dayofweek) >= request_date_from.weekday()] # Second, add days of the other type of week attendance_filtred += list(attendance_actual_next_week) # Third, add days of actual week (to consider days that we have remove first because they coming before date_from) attendance_filtred += list(attendance_actual_week) end_week_type = self.env['resource.calendar.attendance'].get_week_type(request_date_to) attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == end_week_type] attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != end_week_type] attendance_filtred_reversed = list(reversed([att for att in attendance_actual_week if int(att.dayofweek) <= request_date_to.weekday()])) attendance_filtred_reversed += list(reversed(attendance_actual_next_week)) attendance_filtred_reversed += list(reversed(attendance_actual_week)) # find first attendance coming after first_day attendance_from = attendance_filtred[0] # find last attendance coming before last_day attendance_to = attendance_filtred_reversed[0] else: # find first attendance coming after first_day attendance_from = next((att for att in attendances if int(att.dayofweek) >= request_date_from.weekday()), attendances[0] if attendances else default_value) # find last attendance coming before last_day attendance_to = next((att for att in reversed(attendances) if int(att.dayofweek) <= request_date_to.weekday()), attendances[-1] if attendances else default_value) return attendance_from, attendance_to def _default_get_request_parameters(self, values): new_values = dict(values) global_from, global_to = False, False # TDE FIXME: consider a mapping on several days that is not the standard # calendar widget 7-19 in user's TZ is some custom input if values.get('date_from'): user_tz = self.env.user.tz or 'UTC' localized_dt = timezone('UTC').localize(values['date_from']).astimezone(timezone(user_tz)) global_from = localized_dt.time().hour == 7 and localized_dt.time().minute == 0 new_values['request_date_from'] = localized_dt.date() if values.get('date_to'): user_tz = self.env.user.tz or 'UTC' localized_dt = timezone('UTC').localize(values['date_to']).astimezone(timezone(user_tz)) global_to = localized_dt.time().hour == 19 and localized_dt.time().minute == 0 new_values['request_date_to'] = localized_dt.date() if global_from and global_to: new_values['request_unit_custom'] = True return new_values # description name = fields.Char('Description', compute='_compute_description', inverse='_inverse_description', search='_search_description', compute_sudo=False) private_name = fields.Char('Time Off Description', groups='hr_holidays.group_hr_holidays_user') state = fields.Selection([ ('draft', 'To Submit'), ('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved') ], string='Status', compute='_compute_state', store=True, tracking=True, copy=False, readonly=False, help="The status is set to 'To Submit', when a time off request is created." + "\nThe status is 'To Approve', when time off request is confirmed by user." + "\nThe status is 'Refused', when time off request is refused by manager." + "\nThe status is 'Approved', when time off request is approved by manager.") report_note = fields.Text('HR Comments', copy=False, groups="hr_holidays.group_hr_holidays_manager") user_id = fields.Many2one('res.users', string='User', related='employee_id.user_id', related_sudo=True, compute_sudo=True, store=True, readonly=True) manager_id = fields.Many2one('hr.employee', compute='_compute_from_employee_id', store=True, readonly=False) # leave type configuration holiday_status_id = fields.Many2one( "hr.leave.type", compute='_compute_from_employee_id', store=True, string="Time Off Type", required=True, readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}, domain=['|', ('requires_allocation', '=', 'no'), ('has_valid_allocation', '=', True)]) holiday_allocation_id = fields.Many2one( 'hr.leave.allocation', compute='_compute_from_holiday_status_id', string="Allocation", store=True, readonly=False) color = fields.Integer("Color", related='holiday_status_id.color') validation_type = fields.Selection(string='Validation Type', related='holiday_status_id.leave_validation_type', readonly=False) # HR data employee_id = fields.Many2one( 'hr.employee', compute='_compute_from_employee_ids', store=True, string='Employee', index=True, readonly=False, ondelete="restrict", states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}, tracking=True, compute_sudo=False) employee_company_id = fields.Many2one(related='employee_id.company_id', readonly=True, store=True) active_employee = fields.Boolean(related='employee_id.active', readonly=True) tz_mismatch = fields.Boolean(compute='_compute_tz_mismatch') tz = fields.Selection(_tz_get, compute='_compute_tz') department_id = fields.Many2one( 'hr.department', compute='_compute_department_id', store=True, string='Department', readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}) notes = fields.Text('Reasons', readonly=True, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}) # duration date_from = fields.Datetime( 'Start Date', compute='_compute_date_from_to', store=True, readonly=False, index=True, copy=False, required=True, tracking=True, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}) date_to = fields.Datetime( 'End Date', compute='_compute_date_from_to', store=True, readonly=False, copy=False, required=True, tracking=True, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}) number_of_days = fields.Float( 'Duration (Days)', compute='_compute_number_of_days', store=True, readonly=False, copy=False, tracking=True, help='Number of days of the time off request. Used in the calculation. To manually correct the duration, use this field.') number_of_days_display = fields.Float( 'Duration in days', compute='_compute_number_of_days_display', readonly=True, help='Number of days of the time off request according to your working schedule. Used for interface.') number_of_hours_display = fields.Float( 'Duration in hours', compute='_compute_number_of_hours_display', readonly=True, help='Number of hours of the time off request according to your working schedule. Used for interface.') number_of_hours_text = fields.Char(compute='_compute_number_of_hours_text') duration_display = fields.Char('Requested (Days/Hours)', compute='_compute_duration_display', store=True, help="Field allowing to see the leave request duration in days or hours depending on the leave_type_request_unit") # details # details meeting_id = fields.Many2one('calendar.event', string='Meeting', copy=False) parent_id = fields.Many2one('hr.leave', string='Parent', copy=False) linked_request_ids = fields.One2many('hr.leave', 'parent_id', string='Linked Requests') holiday_type = fields.Selection([ ('employee', 'By Employee'), ('company', 'By Company'), ('department', 'By Department'), ('category', 'By Employee Tag')], string='Allocation Mode', readonly=True, required=True, default='employee', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category') employee_ids = fields.Many2many( 'hr.employee', compute='_compute_from_holiday_type', store=True, string='Employees', readonly=False, groups="hr_holidays.group_hr_holidays_user", states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}) multi_employee = fields.Boolean( compute='_compute_from_employee_ids', store=True, compute_sudo=False, help='Holds whether this allocation concerns more than 1 employee') category_id = fields.Many2one( 'hr.employee.category', compute='_compute_from_holiday_type', store=True, string='Employee Tag', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help='Category of Employee') mode_company_id = fields.Many2one( 'res.company', compute='_compute_from_holiday_type', store=True, string='Company Mode', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}) first_approver_id = fields.Many2one( 'hr.employee', string='First Approval', readonly=True, copy=False, help='This area is automatically filled by the user who validate the time off') second_approver_id = fields.Many2one( 'hr.employee', string='Second Approval', readonly=True, copy=False, help='This area is automatically filled by the user who validate the time off with second level (If time off type need second validation)') can_reset = fields.Boolean('Can reset', compute='_compute_can_reset') can_approve = fields.Boolean('Can Approve', compute='_compute_can_approve') attachment_ids = fields.One2many('ir.attachment', 'res_id', string="Attachments") # To display in form view supported_attachment_ids = fields.Many2many( 'ir.attachment', string="Attach File", compute='_compute_supported_attachment_ids', inverse='_inverse_supported_attachment_ids') supported_attachment_ids_count = fields.Integer(compute='_compute_supported_attachment_ids') # UX fields leave_type_request_unit = fields.Selection(related='holiday_status_id.request_unit', readonly=True) leave_type_support_document = fields.Boolean(related="holiday_status_id.support_document") # Interface fields used when not using hour-based computation request_date_from = fields.Date('Request Start Date') request_date_to = fields.Date('Request End Date') # Interface fields used when using hour-based computation request_hour_from = fields.Selection([ ('0', '12:00 AM'), ('0.5', '12:30 AM'), ('1', '1:00 AM'), ('1.5', '1:30 AM'), ('2', '2:00 AM'), ('2.5', '2:30 AM'), ('3', '3:00 AM'), ('3.5', '3:30 AM'), ('4', '4:00 AM'), ('4.5', '4:30 AM'), ('5', '5:00 AM'), ('5.5', '5:30 AM'), ('6', '6:00 AM'), ('6.5', '6:30 AM'), ('7', '7:00 AM'), ('7.5', '7:30 AM'), ('8', '8:00 AM'), ('8.5', '8:30 AM'), ('9', '9:00 AM'), ('9.5', '9:30 AM'), ('10', '10:00 AM'), ('10.5', '10:30 AM'), ('11', '11:00 AM'), ('11.5', '11:30 AM'), ('12', '12:00 PM'), ('12.5', '12:30 PM'), ('13', '1:00 PM'), ('13.5', '1:30 PM'), ('14', '2:00 PM'), ('14.5', '2:30 PM'), ('15', '3:00 PM'), ('15.5', '3:30 PM'), ('16', '4:00 PM'), ('16.5', '4:30 PM'), ('17', '5:00 PM'), ('17.5', '5:30 PM'), ('18', '6:00 PM'), ('18.5', '6:30 PM'), ('19', '7:00 PM'), ('19.5', '7:30 PM'), ('20', '8:00 PM'), ('20.5', '8:30 PM'), ('21', '9:00 PM'), ('21.5', '9:30 PM'), ('22', '10:00 PM'), ('22.5', '10:30 PM'), ('23', '11:00 PM'), ('23.5', '11:30 PM')], string='Hour from') request_hour_to = fields.Selection([ ('0', '12:00 AM'), ('0.5', '12:30 AM'), ('1', '1:00 AM'), ('1.5', '1:30 AM'), ('2', '2:00 AM'), ('2.5', '2:30 AM'), ('3', '3:00 AM'), ('3.5', '3:30 AM'), ('4', '4:00 AM'), ('4.5', '4:30 AM'), ('5', '5:00 AM'), ('5.5', '5:30 AM'), ('6', '6:00 AM'), ('6.5', '6:30 AM'), ('7', '7:00 AM'), ('7.5', '7:30 AM'), ('8', '8:00 AM'), ('8.5', '8:30 AM'), ('9', '9:00 AM'), ('9.5', '9:30 AM'), ('10', '10:00 AM'), ('10.5', '10:30 AM'), ('11', '11:00 AM'), ('11.5', '11:30 AM'), ('12', '12:00 PM'), ('12.5', '12:30 PM'), ('13', '1:00 PM'), ('13.5', '1:30 PM'), ('14', '2:00 PM'), ('14.5', '2:30 PM'), ('15', '3:00 PM'), ('15.5', '3:30 PM'), ('16', '4:00 PM'), ('16.5', '4:30 PM'), ('17', '5:00 PM'), ('17.5', '5:30 PM'), ('18', '6:00 PM'), ('18.5', '6:30 PM'), ('19', '7:00 PM'), ('19.5', '7:30 PM'), ('20', '8:00 PM'), ('20.5', '8:30 PM'), ('21', '9:00 PM'), ('21.5', '9:30 PM'), ('22', '10:00 PM'), ('22.5', '10:30 PM'), ('23', '11:00 PM'), ('23.5', '11:30 PM')], string='Hour to') # used only when the leave is taken in half days request_date_from_period = fields.Selection([ ('am', 'Morning'), ('pm', 'Afternoon')], string="Date Period Start", default='am') # request type request_unit_half = fields.Boolean('Half Day', compute='_compute_request_unit_half', store=True, readonly=False) request_unit_hours = fields.Boolean('Custom Hours', compute='_compute_request_unit_hours', store=True, readonly=False) request_unit_custom = fields.Boolean('Days-long custom hours', compute='_compute_request_unit_custom', store=True, readonly=False) # view is_hatched = fields.Boolean('Hatched', compute='_compute_is_hatched') is_striked = fields.Boolean('Striked', compute='_compute_is_hatched') _sql_constraints = [ ('type_value', "CHECK((holiday_type='employee' AND (employee_id IS NOT NULL OR multi_employee IS TRUE)) or " "(holiday_type='company' AND mode_company_id IS NOT NULL) or " "(holiday_type='category' AND category_id IS NOT NULL) or " "(holiday_type='department' AND department_id IS NOT NULL) )", "The employee, department, company or employee category of this request is missing. Please make sure that your user login is linked to an employee."), ('date_check2', "CHECK ((date_from <= date_to))", "The start date must be anterior to the end date."), ('duration_check', "CHECK ( number_of_days >= 0 )", "If you want to change the number of days you should use the 'period' mode"), ] def _auto_init(self): res = super(HolidaysRequest, self)._auto_init() tools.create_index(self._cr, 'hr_leave_date_to_date_from_index', self._table, ['date_to', 'date_from']) return res @api.constrains('holiday_status_id', 'number_of_days') def _check_allocation_duration(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master return @api.depends_context('uid') def _compute_description(self): self.check_access_rights('read') self.check_access_rule('read') is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user') for leave in self: if is_officer or leave.user_id == self.env.user or leave.employee_id.leave_manager_id == self.env.user: leave.name = leave.sudo().private_name else: leave.name = '*****' def _inverse_description(self): is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user') for leave in self: if is_officer or leave.user_id == self.env.user or leave.employee_id.leave_manager_id == self.env.user: leave.sudo().private_name = leave.name def _search_description(self, operator, value): is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user') domain = [('private_name', operator, value)] if not is_officer: domain = expression.AND([domain, [('user_id', '=', self.env.user.id)]]) leaves = self.search(domain) return [('id', 'in', leaves.ids)] @api.depends('holiday_status_id') def _compute_state(self): for leave in self: leave.state = 'confirm' if leave.validation_type != 'no_validation' else 'draft' @api.depends('holiday_status_id.requires_allocation', 'validation_type', 'employee_id', 'date_from', 'date_to') def _compute_from_holiday_status_id(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master self.holiday_allocation_id = False @api.depends('request_date_from_period', 'request_hour_from', 'request_hour_to', 'request_date_from', 'request_date_to', 'request_unit_half', 'request_unit_hours', 'request_unit_custom', 'employee_id') def _compute_date_from_to(self): for holiday in self: if holiday.request_date_from and holiday.request_date_to and holiday.request_date_from > holiday.request_date_to: holiday.request_date_to = holiday.request_date_from if not holiday.request_date_from: holiday.date_from = False elif not holiday.request_unit_half and not holiday.request_unit_hours and not holiday.request_date_to: holiday.date_to = False else: if holiday.request_unit_half or holiday.request_unit_hours: holiday.request_date_to = holiday.request_date_from resource_calendar_id = holiday.employee_id.resource_calendar_id or self.env.company.resource_calendar_id domain = [('calendar_id', '=', resource_calendar_id.id), ('display_type', '=', False)] attendances = self.env['resource.calendar.attendance'].read_group(domain, ['ids:array_agg(id)', 'hour_from:min(hour_from)', 'hour_to:max(hour_to)', 'week_type', 'dayofweek', 'day_period'], ['week_type', 'dayofweek', 'day_period'], lazy=False) # Must be sorted by dayofweek ASC and day_period DESC attendances = sorted([DummyAttendance(group['hour_from'], group['hour_to'], group['dayofweek'], group['day_period'], group['week_type']) for group in attendances], key=lambda att: (att.dayofweek, att.day_period != 'morning')) default_value = DummyAttendance(0, 0, 0, 'morning', False) if resource_calendar_id.two_weeks_calendar: # find week type of start_date start_week_type = self.env['resource.calendar.attendance'].get_week_type(holiday.request_date_from) attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == start_week_type] attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != start_week_type] # First, add days of actual week coming after date_from attendance_filtred = [att for att in attendance_actual_week if int(att.dayofweek) >= holiday.request_date_from.weekday()] # Second, add days of the other type of week attendance_filtred += list(attendance_actual_next_week) # Third, add days of actual week (to consider days that we have remove first because they coming before date_from) attendance_filtred += list(attendance_actual_week) end_week_type = self.env['resource.calendar.attendance'].get_week_type(holiday.request_date_to) attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == end_week_type] attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != end_week_type] attendance_filtred_reversed = list(reversed([att for att in attendance_actual_week if int(att.dayofweek) <= holiday.request_date_to.weekday()])) attendance_filtred_reversed += list(reversed(attendance_actual_next_week)) attendance_filtred_reversed += list(reversed(attendance_actual_week)) # find first attendance coming after first_day attendance_from = attendance_filtred[0] # find last attendance coming before last_day attendance_to = attendance_filtred_reversed[0] else: # find first attendance coming after first_day attendance_from = next((att for att in attendances if int(att.dayofweek) >= holiday.request_date_from.weekday()), attendances[0] if attendances else default_value) # find last attendance coming before last_day attendance_to = next((att for att in reversed(attendances) if int(att.dayofweek) <= holiday.request_date_to.weekday()), attendances[-1] if attendances else default_value) compensated_request_date_from = holiday.request_date_from compensated_request_date_to = holiday.request_date_to if holiday.request_unit_half: if holiday.request_date_from_period == 'am': hour_from = float_to_time(attendance_from.hour_from) hour_to = float_to_time(attendance_from.hour_to) else: hour_from = float_to_time(attendance_to.hour_from) hour_to = float_to_time(attendance_to.hour_to) elif holiday.request_unit_hours: hour_from = float_to_time(float(holiday.request_hour_from)) hour_to = float_to_time(float(holiday.request_hour_to)) elif holiday.request_unit_custom: hour_from = holiday.date_from.time() hour_to = holiday.date_to.time() compensated_request_date_from = holiday._adjust_date_based_on_tz(holiday.request_date_from, hour_from) compensated_request_date_to = holiday._adjust_date_based_on_tz(holiday.request_date_to, hour_to) else: hour_from = float_to_time(attendance_from.hour_from) hour_to = float_to_time(attendance_to.hour_to) holiday.date_from = timezone(holiday.tz).localize(datetime.combine(compensated_request_date_from, hour_from)).astimezone(UTC).replace(tzinfo=None) holiday.date_to = timezone(holiday.tz).localize(datetime.combine(compensated_request_date_to, hour_to)).astimezone(UTC).replace(tzinfo=None) @api.depends('holiday_status_id', 'request_unit_hours', 'request_unit_custom') def _compute_request_unit_half(self): for holiday in self: if holiday.holiday_status_id or holiday.request_unit_hours or holiday.request_unit_custom: holiday.request_unit_half = False @api.depends('holiday_status_id', 'request_unit_half', 'request_unit_custom') def _compute_request_unit_hours(self): for holiday in self: if holiday.holiday_status_id or holiday.request_unit_half or holiday.request_unit_custom: holiday.request_unit_hours = False @api.depends('holiday_status_id', 'request_unit_half', 'request_unit_hours') def _compute_request_unit_custom(self): for holiday in self: if holiday.holiday_status_id or holiday.request_unit_half or holiday.request_unit_hours: holiday.request_unit_custom = False @api.depends('employee_ids') def _compute_from_employee_ids(self): for holiday in self: if len(holiday.employee_ids) == 1: holiday.employee_id = holiday.employee_ids[0]._origin else: holiday.employee_id = False holiday.multi_employee = (len(holiday.employee_ids) > 1) @api.depends('holiday_type') def _compute_from_holiday_type(self): for holiday in self: if holiday.holiday_type == 'employee': if not holiday.employee_ids: # This handles the case where a request is made with only the employee_id # but does not need to be recomputed on employee_id changes holiday.employee_ids = holiday.employee_id or self.env.user.employee_id holiday.mode_company_id = False holiday.category_id = False elif holiday.holiday_type == 'company': holiday.employee_ids = False if not holiday.mode_company_id: holiday.mode_company_id = self.env.company.id holiday.category_id = False elif holiday.holiday_type == 'department': holiday.employee_ids = False holiday.mode_company_id = False holiday.category_id = False elif holiday.holiday_type == 'category': holiday.employee_ids = False holiday.mode_company_id = False else: holiday.employee_ids = self.env.context.get('default_employee_id') or holiday.employee_id or self.env.user.employee_id @api.depends('employee_id') def _compute_from_employee_id(self): for holiday in self: holiday.manager_id = holiday.employee_id.parent_id.id if holiday.employee_id.user_id != self.env.user and self._origin.employee_id != holiday.employee_id: holiday.holiday_status_id = False @api.depends('employee_id', 'holiday_type') def _compute_department_id(self): for holiday in self: if holiday.employee_id: holiday.department_id = holiday.employee_id.department_id elif holiday.holiday_type == 'department': if not holiday.department_id: holiday.department_id = self.env.user.employee_id.department_id else: holiday.department_id = False @api.depends('date_from', 'date_to', 'employee_id') def _compute_number_of_days(self): for holiday in self: if holiday.date_from and holiday.date_to: holiday.number_of_days = holiday._get_number_of_days(holiday.date_from, holiday.date_to, holiday.employee_id.id)['days'] else: holiday.number_of_days = 0 @api.depends('tz') @api.depends_context('uid') def _compute_tz_mismatch(self): for leave in self: leave.tz_mismatch = leave.tz != self.env.user.tz @api.depends('request_unit_custom', 'employee_id', 'holiday_type', 'department_id.company_id.resource_calendar_id.tz', 'mode_company_id.resource_calendar_id.tz') def _compute_tz(self): for leave in self: tz = False if leave.request_unit_custom: tz = 'UTC' # custom -> already in UTC elif leave.holiday_type == 'employee': tz = leave.employee_id.tz elif leave.holiday_type == 'department': tz = leave.department_id.company_id.resource_calendar_id.tz elif leave.holiday_type == 'company': tz = leave.mode_company_id.resource_calendar_id.tz leave.tz = tz or self.env.company.resource_calendar_id.tz or self.env.user.tz or 'UTC' @api.depends('number_of_days') def _compute_number_of_days_display(self): for holiday in self: holiday.number_of_days_display = holiday.number_of_days def _get_calendar(self): self.ensure_one() return self.employee_id.resource_calendar_id or self.env.company.resource_calendar_id @api.depends('number_of_days') def _compute_number_of_hours_display(self): for holiday in self: calendar = holiday._get_calendar() if holiday.date_from and holiday.date_to: # Take attendances into account, in case the leave validated # Otherwise, this will result into number_of_hours = 0 # and number_of_hours_display = 0 or (#day * calendar.hours_per_day), # which could be wrong if the employee doesn't work the same number # hours each day if holiday.state == 'validate': start_dt = holiday.date_from end_dt = holiday.date_to if not start_dt.tzinfo: start_dt = start_dt.replace(tzinfo=UTC) if not end_dt.tzinfo: end_dt = end_dt.replace(tzinfo=UTC) resource = holiday.employee_id.resource_id intervals = calendar._attendance_intervals_batch(start_dt, end_dt, resource)[resource.id] \ - calendar._leave_intervals_batch(start_dt, end_dt, None)[False] # Substract Global Leaves number_of_hours = sum((stop - start).total_seconds() / 3600 for start, stop, dummy in intervals) else: number_of_hours = holiday._get_number_of_days(holiday.date_from, holiday.date_to, holiday.employee_id.id)['hours'] holiday.number_of_hours_display = number_of_hours or (holiday.number_of_days * (calendar.hours_per_day or HOURS_PER_DAY)) else: holiday.number_of_hours_display = 0 @api.depends('number_of_hours_display', 'number_of_days_display') def _compute_duration_display(self): for leave in self: leave.duration_display = '%g %s' % ( (float_round(leave.number_of_hours_display, precision_digits=2) if leave.leave_type_request_unit == 'hour' else float_round(leave.number_of_days_display, precision_digits=2)), _('hours') if leave.leave_type_request_unit == 'hour' else _('days')) @api.depends('number_of_hours_display') def _compute_number_of_hours_text(self): # YTI Note: All this because a readonly field takes all the width on edit mode... for leave in self: leave.number_of_hours_text = '%s%g %s%s' % ( '' if leave.request_unit_half or leave.request_unit_hours else '(', float_round(leave.number_of_hours_display, precision_digits=2), _('Hours'), '' if leave.request_unit_half or leave.request_unit_hours else ')') @api.depends('state', 'employee_id', 'department_id') def _compute_can_reset(self): for holiday in self: try: holiday._check_approval_update('draft') except (AccessError, UserError): holiday.can_reset = False else: holiday.can_reset = True @api.depends('state', 'employee_id', 'department_id') def _compute_can_approve(self): for holiday in self: try: if holiday.state == 'confirm' and holiday.validation_type == 'both': holiday._check_approval_update('validate1') else: holiday._check_approval_update('validate') except (AccessError, UserError): holiday.can_approve = False else: holiday.can_approve = True @api.depends('state') def _compute_is_hatched(self): for holiday in self: holiday.is_striked = holiday.state == 'refuse' holiday.is_hatched = holiday.state not in ['refuse', 'validate'] @api.depends('leave_type_support_document', 'attachment_ids') def _compute_supported_attachment_ids(self): for holiday in self: holiday.supported_attachment_ids = holiday.attachment_ids holiday.supported_attachment_ids_count = len(holiday.attachment_ids.ids) def _inverse_supported_attachment_ids(self): for holiday in self: holiday.attachment_ids = holiday.supported_attachment_ids @api.constrains('date_from', 'date_to', 'employee_id') def _check_date(self): if self.env.context.get('leave_skip_date_check', False): return for holiday in self.filtered('employee_id'): domain = [ ('date_from', '<', holiday.date_to), ('date_to', '>', holiday.date_from), ('employee_id', '=', holiday.employee_id.id), ('id', '!=', holiday.id), ('state', 'not in', ['cancel', 'refuse']), ] nholidays = self.search_count(domain) if nholidays: raise ValidationError( _('You can not set 2 time off that overlaps on the same day for the same employee.') + '\n- %s' % (holiday.display_name)) @api.constrains('state', 'number_of_days', 'holiday_status_id') def _check_holidays(self): mapped_days = self.holiday_status_id.get_employees_days((self.employee_id | self.sudo().employee_ids).ids) for holiday in self: if holiday.holiday_type != 'employee'\ or not holiday.employee_id and not holiday.employee_ids\ or holiday.holiday_status_id.requires_allocation == 'no': continue if holiday.employee_id: leave_days = mapped_days[holiday.employee_id.id][holiday.holiday_status_id.id] if float_compare(leave_days['remaining_leaves'], 0, precision_digits=2) == -1\ or float_compare(leave_days['virtual_remaining_leaves'], 0, precision_digits=2) == -1: raise ValidationError(_('The number of remaining time off is not sufficient for this time off type.\n' 'Please also check the time off waiting for validation.')) else: unallocated_employees = [] for employee in holiday.employee_ids: leave_days = mapped_days[employee.id][holiday.holiday_status_id.id] if float_compare(leave_days['remaining_leaves'], self.number_of_days, precision_digits=2) == -1\ or float_compare(leave_days['virtual_remaining_leaves'], self.number_of_days, precision_digits=2) == -1: unallocated_employees.append(employee.name) if unallocated_employees: raise ValidationError(_('The number of remaining time off is not sufficient for this time off type.\n' 'Please also check the time off waiting for validation.') + _('\nThe employees that lack allocation days are:\n%s', (', '.join(unallocated_employees)))) @api.constrains('date_from', 'date_to', 'employee_id') def _check_date_state(self): if self.env.context.get('leave_skip_state_check'): return for holiday in self: if holiday.state in ['cancel', 'refuse', 'validate1', 'validate']: raise ValidationError(_("This modification is not allowed in the current state.")) def _get_number_of_days(self, date_from, date_to, employee_id): """ Returns a float equals to the timedelta between two dates given as string.""" if employee_id: employee = self.env['hr.employee'].browse(employee_id) # We force the company in the domain as we are more than likely in a compute_sudo domain = [('company_id', 'in', self.env.company.ids + self.env.context.get('allowed_company_ids', []))] result = employee._get_work_days_data_batch(date_from, date_to, domain=domain)[employee.id] if self.request_unit_half and result['hours'] > 0: result['days'] = 0.5 return result today_hours = self.env.company.resource_calendar_id.get_work_hours_count( datetime.combine(date_from.date(), time.min), datetime.combine(date_from.date(), time.max), False) hours = self.env.company.resource_calendar_id.get_work_hours_count(date_from, date_to) days = hours / (today_hours or HOURS_PER_DAY) if not self.request_unit_half else 0.5 return {'days': days, 'hours': hours} def _adjust_date_based_on_tz(self, leave_date, hour): """ request_date_{from,to} are local to the user's tz but hour_{from,to} are in UTC. In some cases they are combined (assuming they are in the same tz) as a datetime. When that happens it's possible we need to adjust one of the dates. This function adjust the date, so that it can be passed to datetime(). E.g. a leave in US/Pacific for one day: - request_date_from: 1st of Jan - request_date_to: 1st of Jan - hour_from: 15:00 (7:00 local) - hour_to: 03:00 (19:00 local) <-- this happens on the 2nd of Jan in UTC """ user_tz = timezone(self.env.user.tz if self.env.user.tz else 'UTC') request_date_to_utc = UTC.localize(datetime.combine(leave_date, hour)).astimezone(user_tz).replace(tzinfo=None) if request_date_to_utc.date() < leave_date: return leave_date + timedelta(days=1) elif request_date_to_utc.date() > leave_date: return leave_date - timedelta(days=1) else: return leave_date #################################################### # ORM Overrides methods #################################################### def name_get(self): res = [] for leave in self: user_tz = timezone(leave.tz) date_from_utc = leave.date_from and leave.date_from.astimezone(user_tz).date() date_to_utc = leave.date_to and leave.date_to.astimezone(user_tz).date() if self.env.context.get('short_name'): if leave.leave_type_request_unit == 'hour': res.append((leave.id, _("%s : %.2f hours") % (leave.name or leave.holiday_status_id.name, leave.number_of_hours_display))) else: res.append((leave.id, _("%s : %.2f days") % (leave.name or leave.holiday_status_id.name, leave.number_of_days))) else: if leave.holiday_type == 'company': target = leave.mode_company_id.name elif leave.holiday_type == 'department': target = leave.department_id.name elif leave.holiday_type == 'category': target = leave.category_id.name elif leave.employee_id: target = leave.employee_id.name else: target = ', '.join(leave.employee_ids.mapped('name')) display_date = format_date(self.env, date_from_utc) or "" if leave.leave_type_request_unit == 'hour': if self.env.context.get('hide_employee_name') and 'employee_id' in self.env.context.get('group_by', []): res.append(( leave.id, _("%(person)s on %(leave_type)s: %(duration).2f hours on %(date)s", person=target, leave_type=leave.holiday_status_id.name, duration=leave.number_of_hours_display, date=display_date, ) )) else: res.append(( leave.id, _("%(person)s on %(leave_type)s: %(duration).2f hours on %(date)s", person=target, leave_type=leave.holiday_status_id.name, duration=leave.number_of_hours_display, date=display_date, ) )) else: if leave.number_of_days > 1 and date_from_utc and date_to_utc: display_date += ' / %s' % format_date(self.env, date_to_utc) or "" if self.env.context.get('hide_employee_name') and 'employee_id' in self.env.context.get('group_by', []): res.append(( leave.id, _("%(leave_type)s: %(duration).2f days (%(start)s)", leave_type=leave.holiday_status_id.name, duration=leave.number_of_days, start=display_date, ) )) else: res.append(( leave.id, _("%(person)s on %(leave_type)s: %(duration).2f days (%(start)s)", person=target, leave_type=leave.holiday_status_id.name, duration=leave.number_of_days, start=display_date, ) )) return res def add_follower(self, employee_id): employee = self.env['hr.employee'].browse(employee_id) if employee.user_id: self.message_subscribe(partner_ids=employee.user_id.partner_id.ids) @api.constrains('holiday_allocation_id') def _check_allocation_id(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master return @api.constrains('holiday_allocation_id', 'date_to', 'date_from') def _check_leave_type_validity(self): # Deprecated as part of https://github.com/odoo/odoo/pull/96545 # TODO: remove in master return def _check_double_validation_rules(self, employees, state): if self.user_has_groups('hr_holidays.group_hr_holidays_manager'): return is_leave_user = self.user_has_groups('hr_holidays.group_hr_holidays_user') if state == 'validate1': employees = employees.filtered(lambda employee: employee.leave_manager_id != self.env.user) if employees and not is_leave_user: raise AccessError(_('You cannot first approve a time off for %s, because you are not his time off manager', employees[0].name)) elif state == 'validate' and not is_leave_user: # Is probably handled via ir.rule raise AccessError(_('You don\'t have the rights to apply second approval on a time off request')) @api.model_create_multi def create(self, vals_list): """ Override to avoid automatic logging of creation """ if not self._context.get('leave_fast_create'): leave_types = self.env['hr.leave.type'].browse([values.get('holiday_status_id') for values in vals_list if values.get('holiday_status_id')]) mapped_validation_type = {leave_type.id: leave_type.leave_validation_type for leave_type in leave_types} for values in vals_list: employee_id = values.get('employee_id', False) leave_type_id = values.get('holiday_status_id') # Handle automatic department_id if not values.get('department_id'): values.update({'department_id': self.env['hr.employee'].browse(employee_id).department_id.id}) # Handle no_validation if mapped_validation_type[leave_type_id] == 'no_validation': values.update({'state': 'confirm'}) if 'state' not in values: # To mimic the behavior of compute_state that was always triggered, as the field was readonly values['state'] = 'confirm' if mapped_validation_type[leave_type_id] != 'no_validation' else 'draft' # Handle double validation if mapped_validation_type[leave_type_id] == 'both': self._check_double_validation_rules(employee_id, values.get('state', False)) holidays = super(HolidaysRequest, self.with_context(mail_create_nosubscribe=True)).create(vals_list) for holiday in holidays: if not self._context.get('leave_fast_create'): # Everything that is done here must be done using sudo because we might # have different create and write rights # eg : holidays_user can create a leave request with validation_type = 'manager' for someone else # but they can only write on it if they are leave_manager_id holiday_sudo = holiday.sudo() holiday_sudo.add_follower(employee_id) if holiday.validation_type == 'manager': holiday_sudo.message_subscribe(partner_ids=holiday.employee_id.leave_manager_id.partner_id.ids) if holiday.validation_type == 'no_validation': # Automatic validation should be done in sudo, because user might not have the rights to do it by himself holiday_sudo.action_validate() holiday_sudo.message_subscribe(partner_ids=[holiday._get_responsible_for_approval().partner_id.id]) holiday_sudo.message_post(body=_("The time off has been automatically approved"), subtype_xmlid="mail.mt_comment") # Message from OdooBot (sudo) elif not self._context.get('import_file'): holiday_sudo.activity_update() return holidays def write(self, values): is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') or self.env.is_superuser() if not is_officer and values.keys() - {'attachment_ids', 'supported_attachment_ids', 'message_main_attachment_id'}: if any(hol.date_from.date() < fields.Date.today() and hol.employee_id.leave_manager_id != self.env.user for hol in self): raise UserError(_('You must have manager rights to modify/validate a time off that already begun')) # Unlink existing resource.calendar.leaves for validated time off if 'state' in values and values['state'] != 'validate': validated_leaves = self.filtered(lambda l: l.state == 'validate') validated_leaves._remove_resource_leave() employee_id = values.get('employee_id', False) if not self.env.context.get('leave_fast_create'): if values.get('state'): self._check_approval_update(values['state']) if any(holiday.validation_type == 'both' for holiday in self): if values.get('employee_id'): employees = self.env['hr.employee'].browse(values.get('employee_id')) else: employees = self.mapped('employee_id') self._check_double_validation_rules(employees, values['state']) if 'date_from' in values: values['request_date_from'] = values['date_from'] if 'date_to' in values: values['request_date_to'] = values['date_to'] result = super(HolidaysRequest, self).write(values) if not self.env.context.get('leave_fast_create'): for holiday in self: if employee_id: holiday.add_follower(employee_id) return result @api.ondelete(at_uninstall=False) def _unlink_if_correct_states(self): error_message = _('You cannot delete a time off which is in %s state') state_description_values = {elem[0]: elem[1] for elem in self._fields['state']._description_selection(self.env)} now = fields.Datetime.now() if not self.user_has_groups('hr_holidays.group_hr_holidays_user'): if any(hol.state not in ['draft', 'confirm'] for hol in self): raise UserError(error_message % state_description_values.get(self[:1].state)) if any(hol.date_from < now for hol in self): raise UserError(_('You cannot delete a time off which is in the past')) else: for holiday in self.filtered(lambda holiday: holiday.state not in ['draft', 'cancel', 'confirm']): raise UserError(error_message % (state_description_values.get(holiday.state),)) def unlink(self): return super(HolidaysRequest, self.with_context(leave_skip_date_check=True)).unlink() def copy_data(self, default=None): if default and 'date_from' in default and 'date_to' in default: default['request_date_from'] = default.get('date_from') default['request_date_to'] = default.get('date_to') return super().copy_data(default) raise UserError(_('A time off cannot be duplicated.')) def _get_mail_redirect_suggested_company(self): return self.holiday_status_id.company_id @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): if not self.user_has_groups('hr_holidays.group_hr_holidays_user') and 'private_name' in groupby: raise UserError(_('Such grouping is not allowed.')) return super(HolidaysRequest, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) #################################################### # Business methods #################################################### def _prepare_resource_leave_vals_list(self): """Hook method for others to inject data """ return [{ 'name': _("%s: Time Off", leave.employee_id.name), 'date_from': leave.date_from, 'holiday_id': leave.id, 'date_to': leave.date_to, 'resource_id': leave.employee_id.resource_id.id, 'calendar_id': leave.employee_id.resource_calendar_id.id, 'time_type': leave.holiday_status_id.time_type, } for leave in self] def _create_resource_leave(self): """ This method will create entry in resource calendar time off object at the time of holidays validated :returns: created `resource.calendar.leaves` """ vals_list = self._prepare_resource_leave_vals_list() return self.env['resource.calendar.leaves'].sudo().create(vals_list) def _remove_resource_leave(self): """ This method will create entry in resource calendar time off object at the time of holidays cancel/removed """ return self.env['resource.calendar.leaves'].search([('holiday_id', 'in', self.ids)]).unlink() def _validate_leave_request(self): """ Validate time off requests (holiday_type='employee') by creating a calendar event and a resource time off. """ holidays = self.filtered(lambda request: request.holiday_type == 'employee' and request.employee_id) holidays._create_resource_leave() meeting_holidays = holidays.filtered(lambda l: l.holiday_status_id.create_calendar_meeting) meetings = self.env['calendar.event'] if meeting_holidays: meeting_values_for_user_id = meeting_holidays._prepare_holidays_meeting_values() Meeting = self.env['calendar.event'] for user_id, meeting_values in meeting_values_for_user_id.items(): meetings += Meeting.with_user(user_id or self.env.uid).with_context( allowed_company_ids=[], no_mail_to_attendees=True, calendar_no_videocall=True, active_model=self._name ).create(meeting_values) Holiday = self.env['hr.leave'] for meeting in meetings: Holiday.browse(meeting.res_id).meeting_id = meeting def _prepare_holidays_meeting_values(self): result = defaultdict(list) company_calendar = self.env.company.resource_calendar_id for holiday in self: calendar = holiday.employee_id.resource_calendar_id or company_calendar user = holiday.user_id if holiday.leave_type_request_unit == 'hour': meeting_name = _("%s on Time Off : %.2f hour(s)") % (holiday.employee_id.name or holiday.category_id.name, holiday.number_of_hours_display) else: meeting_name = _("%s on Time Off : %.2f day(s)") % (holiday.employee_id.name or holiday.category_id.name, holiday.number_of_days) meeting_values = { 'name': meeting_name, 'duration': holiday.number_of_days * (calendar.hours_per_day or HOURS_PER_DAY), 'description': holiday.notes, 'user_id': user.id, 'start': holiday.date_from, 'stop': holiday.date_to, 'allday': False, 'privacy': 'confidential', 'event_tz': user.tz, 'activity_ids': [(5, 0, 0)], 'res_id': holiday.id, } # Add the partner_id (if exist) as an attendee if user and user.partner_id: meeting_values['partner_ids'] = [ (4, user.partner_id.id)] result[user.id].append(meeting_values) return result def _prepare_employees_holiday_values(self, employees): self.ensure_one() work_days_data = employees._get_work_days_data_batch(self.date_from, self.date_to) return [{ 'name': self.name, 'holiday_type': 'employee', 'holiday_status_id': self.holiday_status_id.id, 'date_from': self.date_from, 'date_to': self.date_to, 'request_date_from': self.request_date_from, 'request_date_to': self.request_date_to, 'notes': self.notes, 'number_of_days': work_days_data[employee.id]['days'], 'parent_id': self.id, 'employee_id': employee.id, 'employee_ids': employee, 'state': 'validate', } for employee in employees if work_days_data[employee.id]['days']] def action_draft(self): if any(holiday.state not in ['confirm', 'refuse'] for holiday in self): raise UserError(_('Time off request state must be "Refused" or "To Approve" in order to be reset to draft.')) self.write({ 'state': 'draft', 'first_approver_id': False, 'second_approver_id': False, }) linked_requests = self.mapped('linked_request_ids') if linked_requests: linked_requests.action_draft() linked_requests.unlink() self.activity_update() return True def action_confirm(self): if self.filtered(lambda holiday: holiday.state != 'draft'): raise UserError(_('Time off request must be in Draft state ("To Submit") in order to confirm it.')) self.write({'state': 'confirm'}) holidays = self.filtered(lambda leave: leave.validation_type == 'no_validation') if holidays: # Automatic validation should be done in sudo, because user might not have the rights to do it by himself holidays.sudo().action_validate() self.activity_update() return True def action_approve(self): # if validation_type == 'both': this method is the first approval approval # if validation_type != 'both': this method calls action_validate() below if any(holiday.state != 'confirm' for holiday in self): raise UserError(_('Time off request must be confirmed ("To Approve") in order to approve it.')) current_employee = self.env.user.employee_id self.filtered(lambda hol: hol.validation_type == 'both').write({'state': 'validate1', 'first_approver_id': current_employee.id}) # Post a second message, more verbose than the tracking message for holiday in self.filtered(lambda holiday: holiday.employee_id.user_id): user_tz = timezone(holiday.tz) utc_tz = pytz.utc.localize(holiday.date_from).astimezone(user_tz) holiday.message_post( body=_( 'Your %(leave_type)s planned on %(date)s has been accepted', leave_type=holiday.holiday_status_id.display_name, date=utc_tz.replace(tzinfo=None) ), partner_ids=holiday.employee_id.user_id.partner_id.ids) self.filtered(lambda hol: not hol.validation_type == 'both').action_validate() if not self.env.context.get('leave_fast_create'): self.activity_update() return True def _get_leaves_on_public_holiday(self): return self.filtered(lambda l: l.employee_id and not l.number_of_days) def action_validate(self): current_employee = self.env.user.employee_id leaves = self._get_leaves_on_public_holiday() if leaves: raise ValidationError(_('The following employees are not supposed to work during that period:\n %s') % ','.join(leaves.mapped('employee_id.name'))) if any(holiday.state not in ['confirm', 'validate1'] and holiday.validation_type != 'no_validation' for holiday in self): raise UserError(_('Time off request must be confirmed in order to approve it.')) self.write({'state': 'validate'}) leaves_second_approver = self.env['hr.leave'] leaves_first_approver = self.env['hr.leave'] for leave in self: if leave.validation_type == 'both': leaves_second_approver += leave else: leaves_first_approver += leave if leave.holiday_type != 'employee' or\ (leave.holiday_type == 'employee' and len(leave.employee_ids) > 1): if leave.holiday_type == 'employee': employees = leave.employee_ids elif leave.holiday_type == 'category': employees = leave.category_id.employee_ids elif leave.holiday_type == 'company': employees = self.env['hr.employee'].search([('company_id', '=', leave.mode_company_id.id)]) else: employees = leave.department_id.member_ids conflicting_leaves = self.env['hr.leave'].with_context( tracking_disable=True, mail_activity_automation_skip=True, leave_fast_create=True ).search([ ('date_from', '<=', leave.date_to), ('date_to', '>', leave.date_from), ('state', 'not in', ['cancel', 'refuse']), ('holiday_type', '=', 'employee'), ('employee_id', 'in', employees.ids)]) if conflicting_leaves: # YTI: More complex use cases could be managed in master if leave.leave_type_request_unit != 'day' or any(l.leave_type_request_unit == 'hour' for l in conflicting_leaves): raise ValidationError(_('You can not have 2 time off that overlaps on the same day.')) # keep track of conflicting leaves states before refusal target_states = {l.id: l.state for l in conflicting_leaves} conflicting_leaves.action_refuse() split_leaves_vals = [] for conflicting_leave in conflicting_leaves: if conflicting_leave.leave_type_request_unit == 'half_day' and conflicting_leave.request_unit_half: continue # Leaves in days if conflicting_leave.date_from < leave.date_from: before_leave_vals = conflicting_leave.copy_data({ 'date_from': conflicting_leave.date_from.date(), 'date_to': leave.date_from.date() + timedelta(days=-1), 'state': target_states[conflicting_leave.id], })[0] before_leave = self.env['hr.leave'].new(before_leave_vals) before_leave._compute_date_from_to() # Could happen for part-time contract, that time off is not necessary # anymore. # Imagine you work on monday-wednesday-friday only. # You take a time off on friday. # We create a company time off on friday. # By looking at the last attendance before the company time off # start date to compute the date_to, you would have a date_from > date_to. # Just don't create the leave at that time. That's the reason why we use # new instead of create. As the leave is not actually created yet, the sql # constraint didn't check date_from < date_to yet. if before_leave.date_from < before_leave.date_to: split_leaves_vals.append(before_leave._convert_to_write(before_leave._cache)) if conflicting_leave.date_to > leave.date_to: after_leave_vals = conflicting_leave.copy_data({ 'date_from': leave.date_to.date() + timedelta(days=1), 'date_to': conflicting_leave.date_to.date(), 'state': target_states[conflicting_leave.id], })[0] after_leave = self.env['hr.leave'].new(after_leave_vals) after_leave._compute_date_from_to() # Could happen for part-time contract, that time off is not necessary # anymore. if after_leave.date_from < after_leave.date_to: split_leaves_vals.append(after_leave._convert_to_write(after_leave._cache)) split_leaves = self.env['hr.leave'].with_context( tracking_disable=True, mail_activity_automation_skip=True, leave_fast_create=True, leave_skip_state_check=True ).create(split_leaves_vals) split_leaves.filtered(lambda l: l.state in 'validate')._validate_leave_request() values = leave._prepare_employees_holiday_values(employees) leaves = self.env['hr.leave'].with_context( tracking_disable=True, mail_activity_automation_skip=True, leave_fast_create=True, no_calendar_sync=True, leave_skip_state_check=True, ).create(values) leaves._validate_leave_request() leaves_second_approver.write({'second_approver_id': current_employee.id}) leaves_first_approver.write({'first_approver_id': current_employee.id}) employee_requests = self.filtered(lambda hol: hol.holiday_type == 'employee') employee_requests._validate_leave_request() if not self.env.context.get('leave_fast_create'): employee_requests.filtered(lambda holiday: holiday.validation_type != 'no_validation').activity_update() return True def action_refuse(self): current_employee = self.env.user.employee_id if any(holiday.state not in ['draft', 'confirm', 'validate', 'validate1'] for holiday in self): raise UserError(_('Time off request must be confirmed or validated in order to refuse it.')) validated_holidays = self.filtered(lambda hol: hol.state == 'validate1') validated_holidays.write({'state': 'refuse', 'first_approver_id': current_employee.id}) (self - validated_holidays).write({'state': 'refuse', 'second_approver_id': current_employee.id}) # Delete the meeting self.mapped('meeting_id').write({'active': False}) # If a category that created several holidays, cancel all related linked_requests = self.mapped('linked_request_ids') if linked_requests: linked_requests.action_refuse() # Post a second message, more verbose than the tracking message for holiday in self: if holiday.employee_id.user_id: holiday.message_post( body=_('Your %(leave_type)s planned on %(date)s has been refused', leave_type=holiday.holiday_status_id.display_name, date=holiday.date_from), partner_ids=holiday.employee_id.user_id.partner_id.ids) self.activity_update() return True def action_documents(self): domain = [('id', 'in', self.attachment_ids.ids)] return { 'name': _("Supporting Documents"), 'type': 'ir.actions.act_window', 'res_model': 'ir.attachment', 'context': {'create': False}, 'view_mode': 'list', 'domain': domain } def _check_approval_update(self, state): """ Check if target state is achievable. """ if self.env.is_superuser(): return current_employee = self.env.user.employee_id is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') is_manager = self.env.user.has_group('hr_holidays.group_hr_holidays_manager') for holiday in self: val_type = holiday.validation_type if not is_manager and state != 'confirm': if state == 'draft': if holiday.state == 'refuse': raise UserError(_('Only a Time Off Manager can reset a refused leave.')) if holiday.date_from and holiday.date_from.date() <= fields.Date.today(): raise UserError(_('Only a Time Off Manager can reset a started leave.')) if holiday.employee_id != current_employee: raise UserError(_('Only a Time Off Manager can reset other people leaves.')) else: if val_type == 'no_validation' and current_employee == holiday.employee_id: continue # use ir.rule based first access check: department, members, ... (see security.xml) holiday.check_access_rule('write') # This handles states validate1 validate and refuse if holiday.employee_id == current_employee: raise UserError(_('Only a Time Off Manager can approve/refuse its own requests.')) if (state == 'validate1' and val_type == 'both') and holiday.holiday_type == 'employee': if not is_officer and self.env.user != holiday.employee_id.leave_manager_id: raise UserError(_('You must be either %s\'s manager or Time off Manager to approve this leave') % (holiday.employee_id.name)) if (state == 'validate' and val_type == 'manager') and self.env.user != (holiday.employee_id | holiday.sudo().employee_ids).leave_manager_id: if holiday.employee_id: employees = holiday.employee_id else: employees = ', '.join(holiday.employee_ids.filtered(lambda e: e.leave_manager_id != self.env.user).mapped('name')) raise UserError(_('You must be %s\'s Manager to approve this leave', employees)) if not is_officer and (state == 'validate' and val_type == 'hr') and holiday.holiday_type == 'employee': raise UserError(_('You must either be a Time off Officer or Time off Manager to approve this leave')) # ------------------------------------------------------------ # Activity methods # ------------------------------------------------------------ def _get_responsible_for_approval(self): self.ensure_one() responsible = self.env.user if self.holiday_type != 'employee': return responsible if self.validation_type == 'manager' or (self.validation_type == 'both' and self.state == 'confirm'): if self.employee_id.leave_manager_id: responsible = self.employee_id.leave_manager_id elif self.employee_id.parent_id.user_id: responsible = self.employee_id.parent_id.user_id elif self.validation_type == 'hr' or (self.validation_type == 'both' and self.state == 'validate1'): if self.holiday_status_id.responsible_id: responsible = self.holiday_status_id.responsible_id return responsible def activity_update(self): to_clean, to_do = self.env['hr.leave'], self.env['hr.leave'] for holiday in self: note = _( 'New %(leave_type)s Request created by %(user)s', leave_type=holiday.holiday_status_id.name, user=holiday.create_uid.name, ) if holiday.state == 'draft': to_clean |= holiday elif holiday.state == 'confirm': holiday.activity_schedule( 'hr_holidays.mail_act_leave_approval', note=note, user_id=holiday.sudo()._get_responsible_for_approval().id or self.env.user.id) elif holiday.state == 'validate1': holiday.activity_feedback(['hr_holidays.mail_act_leave_approval']) holiday.activity_schedule( 'hr_holidays.mail_act_leave_second_approval', note=note, user_id=holiday.sudo()._get_responsible_for_approval().id or self.env.user.id) elif holiday.state == 'validate': to_do |= holiday elif holiday.state == 'refuse': to_clean |= holiday if to_clean: to_clean.activity_unlink(['hr_holidays.mail_act_leave_approval', 'hr_holidays.mail_act_leave_second_approval']) if to_do: to_do.activity_feedback(['hr_holidays.mail_act_leave_approval', 'hr_holidays.mail_act_leave_second_approval']) #################################################### # Messaging methods #################################################### def _track_subtype(self, init_values): if 'state' in init_values and self.state == 'validate': leave_notif_subtype = self.holiday_status_id.leave_notif_subtype_id return leave_notif_subtype or self.env.ref('hr_holidays.mt_leave') return super(HolidaysRequest, self)._track_subtype(init_values) def _notify_get_groups(self, msg_vals=None): """ Handle HR users and officers recipients that can validate or refuse holidays directly from email. """ groups = super(HolidaysRequest, self)._notify_get_groups(msg_vals=msg_vals) local_msg_vals = dict(msg_vals or {}) self.ensure_one() hr_actions = [] if self.state == 'confirm': app_action = self._notify_get_action_link('controller', controller='/leave/validate', **local_msg_vals) hr_actions += [{'url': app_action, 'title': _('Approve')}] if self.state in ['confirm', 'validate', 'validate1']: ref_action = self._notify_get_action_link('controller', controller='/leave/refuse', **local_msg_vals) hr_actions += [{'url': ref_action, 'title': _('Refuse')}] holiday_user_group_id = self.env.ref('hr_holidays.group_hr_holidays_user').id new_group = ( 'group_hr_holidays_user', lambda pdata: pdata['type'] == 'user' and holiday_user_group_id in pdata['groups'], { 'actions': hr_actions, }) return [new_group] + groups def message_subscribe(self, partner_ids=None, subtype_ids=None): # due to record rule can not allow to add follower and mention on validated leave so subscribe through sudo if self.state in ['validate', 'validate1']: self.check_access_rights('read') self.check_access_rule('read') return super(HolidaysRequest, self.sudo()).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids) return super(HolidaysRequest, self).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids) @api.model def get_unusual_days(self, date_from, date_to=None): return self.env.user.employee_id.sudo(False)._get_unusual_days(date_from, date_to)
56.172943
80,552
1,673
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, models _logger = logging.getLogger(__name__) class MailMessageSubtype(models.Model): _inherit = 'mail.message.subtype' def _get_department_subtype(self): return self.search([ ('res_model', '=', 'hr.department'), ('parent_id', '=', self.id)]) def _update_department_subtype(self): for subtype in self: department_subtype = subtype._get_department_subtype() if department_subtype: department_subtype.write({ 'name': subtype.name, 'default': subtype.default, }) else: department_subtype = self.create({ 'name': subtype.name, 'res_model': 'hr.department', 'default': subtype.default or False, 'parent_id': subtype.id, 'relation_field': 'department_id', }) return department_subtype @api.model_create_multi def create(self, vals_list): result = super(MailMessageSubtype, self).create(vals_list) result.filtered( lambda st: st.res_model in ['hr.leave', 'hr.leave.allocation'] )._update_department_subtype() return result def write(self, vals): result = super(MailMessageSubtype, self).write(vals) self.filtered( lambda subtype: subtype.res_model in ['hr.leave', 'hr.leave.allocation'] )._update_department_subtype() return result
33.46
1,673
3,002
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 AccrualPlan(models.Model): _name = "hr.leave.accrual.plan" _description = "Accrual Plan" name = fields.Char('Name', required=True) time_off_type_id = fields.Many2one('hr.leave.type', string="Time Off Type", help="""Specify if this accrual plan can only be used with this Time Off Type. Leave empty if this accrual plan can be used with any Time Off Type.""") employees_count = fields.Integer("Employees", compute='_compute_employee_count') level_ids = fields.One2many('hr.leave.accrual.level', 'accrual_plan_id', copy=True) allocation_ids = fields.One2many('hr.leave.allocation', 'accrual_plan_id') transition_mode = fields.Selection([ ('immediately', 'Immediately'), ('end_of_accrual', "After this accrual's period")], string="Level Transition", default="immediately", required=True, help="""Immediately: When the date corresponds to the new level, your accrual is automatically computed, granted and you switch to new level After this accrual's period: When the accrual is complete (a week, a month), and granted, you switch to next level if allocation date corresponds""") level_count = fields.Integer('Levels', compute='_compute_level_count') @api.depends('level_ids') def _compute_level_count(self): level_read_group = self.env['hr.leave.accrual.level'].read_group( [('accrual_plan_id', 'in', self.ids)], fields=['accrual_plan_id'], groupby=['accrual_plan_id'], ) mapped_count = {group['accrual_plan_id'][0]: group['accrual_plan_id_count'] for group in level_read_group} for plan in self: plan.level_count = mapped_count.get(plan.id, 0) @api.depends('allocation_ids') def _compute_employee_count(self): allocations_read_group = self.env['hr.leave.allocation'].read_group( [('accrual_plan_id', 'in', self.ids)], ['accrual_plan_id', 'employee_count:count_distinct(employee_id)'], ['accrual_plan_id'], ) allocations_dict = {res['accrual_plan_id'][0]: res['employee_count'] for res in allocations_read_group} for plan in self: plan.employees_count = allocations_dict.get(plan.id, 0) def action_open_accrual_plan_employees(self): self.ensure_one() return { 'name': _("Accrual Plan's Employees"), 'type': 'ir.actions.act_window', 'view_mode': 'kanban,tree,form', 'res_model': 'hr.employee', 'domain': [('id', 'in', self.allocation_ids.employee_id.ids)], } @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}, name=_("%s (copy)", self.name)) return super().copy(default=default)
47.650794
3,002
2,253
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from dateutil.relativedelta import relativedelta from odoo import api, fields, models class Department(models.Model): _inherit = 'hr.department' absence_of_today = fields.Integer( compute='_compute_leave_count', string='Absence by Today') leave_to_approve_count = fields.Integer( compute='_compute_leave_count', string='Time Off to Approve') allocation_to_approve_count = fields.Integer( compute='_compute_leave_count', string='Allocation to Approve') def _compute_leave_count(self): Requests = self.env['hr.leave'] Allocations = self.env['hr.leave.allocation'] today_date = datetime.datetime.utcnow().date() today_start = fields.Datetime.to_string(today_date) # get the midnight of the current utc day today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59)) leave_data = Requests.read_group( [('department_id', 'in', self.ids), ('state', '=', 'confirm')], ['department_id'], ['department_id']) allocation_data = Allocations.read_group( [('department_id', 'in', self.ids), ('state', '=', 'confirm')], ['department_id'], ['department_id']) absence_data = Requests.read_group( [('department_id', 'in', self.ids), ('state', 'not in', ['cancel', 'refuse']), ('date_from', '<=', today_end), ('date_to', '>=', today_start)], ['department_id'], ['department_id']) res_leave = dict((data['department_id'][0], data['department_id_count']) for data in leave_data) res_allocation = dict((data['department_id'][0], data['department_id_count']) for data in allocation_data) res_absence = dict((data['department_id'][0], data['department_id_count']) for data in absence_data) for department in self: department.leave_to_approve_count = res_leave.get(department.id, 0) department.allocation_to_approve_count = res_allocation.get(department.id, 0) department.absence_of_today = res_absence.get(department.id, 0)
46.9375
2,253
282
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 CalendarLeaves(models.Model): _inherit = "resource.calendar.leaves" holiday_id = fields.Many2one("hr.leave", string='Leave Request')
28.2
282
13,726
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import calendar from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.tools.date_utils import get_timedelta DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] # Used for displaying the days and reversing selection -> integer DAY_SELECT_VALUES = [str(i) for i in range(1, 29)] + ['last'] DAY_SELECT_SELECTION_NO_LAST = tuple(zip(DAY_SELECT_VALUES, (str(i) for i in range(1, 29)))) def _get_selection_days(self): return DAY_SELECT_SELECTION_NO_LAST + (("last", _("last day")),) class AccrualPlanLevel(models.Model): _name = "hr.leave.accrual.level" _description = "Accrual Plan Level" _order = 'sequence asc' sequence = fields.Integer( string='sequence', compute='_compute_sequence', store=True, help='Sequence is generated automatically by start time delta.') level = fields.Integer(compute='_compute_level', help='Level computed through the sequence.') accrual_plan_id = fields.Many2one('hr.leave.accrual.plan', "Accrual Plan", required=True) start_count = fields.Integer( "Start after", help="The accrual starts after a defined period from the allocation start date. This field defines the number of days, months or years after which accrual is used.", default="1") start_type = fields.Selection( [('day', 'day(s)'), ('month', 'month(s)'), ('year', 'year(s)')], default='day', string=" ", required=True, help="This field defines the unit of time after which the accrual starts.") is_based_on_worked_time = fields.Boolean("Based on worked time", help="Only accrue for the time worked by the employee. This is the time when the employee did not take time off.") # Accrue of added_value = fields.Float( "Rate", digits=(16, 5), required=True, help="The number of hours/days that will be incremented in the specified Time Off Type for every period") added_value_type = fields.Selection( [('days', 'Days'), ('hours', 'Hours')], default='days', required=True) frequency = fields.Selection([ ('daily', 'Daily'), ('weekly', 'Weekly'), ('bimonthly', 'Twice a month'), ('monthly', 'Monthly'), ('biyearly', 'Twice a year'), ('yearly', 'Yearly'), ], default='daily', required=True, string="Frequency") week_day = fields.Selection([ ('mon', 'Monday'), ('tue', 'Tuesday'), ('wed', 'Wednesday'), ('thu', 'Thursday'), ('fri', 'Friday'), ('sat', 'Saturday'), ('sun', 'Sunday'), ], default='mon', required=True, string="Allocation on") first_day = fields.Integer(default=1) first_day_display = fields.Selection( _get_selection_days, compute='_compute_days_display', inverse='_inverse_first_day_display') second_day = fields.Integer(default=15) second_day_display = fields.Selection( _get_selection_days, compute='_compute_days_display', inverse='_inverse_second_day_display') first_month_day = fields.Integer(default=1) first_month_day_display = fields.Selection( _get_selection_days, compute='_compute_days_display', inverse='_inverse_first_month_day_display') first_month = fields.Selection([ ('jan', 'January'), ('feb', 'February'), ('mar', 'March'), ('apr', 'April'), ('may', 'May'), ('jun', 'June'), ], default="jan") second_month_day = fields.Integer(default=1) second_month_day_display = fields.Selection( _get_selection_days, compute='_compute_days_display', inverse='_inverse_second_month_day_display') second_month = fields.Selection([ ('jul', 'July'), ('aug', 'August'), ('sep', 'September'), ('oct', 'October'), ('nov', 'November'), ('dec', 'December') ], default="jul") yearly_month = fields.Selection([ ('jan', 'January'), ('feb', 'February'), ('mar', 'March'), ('apr', 'April'), ('may', 'May'), ('jun', 'June'), ('jul', 'July'), ('aug', 'August'), ('sep', 'September'), ('oct', 'October'), ('nov', 'November'), ('dec', 'December') ], default="jan") yearly_day = fields.Integer(default=1) yearly_day_display = fields.Selection( _get_selection_days, compute='_compute_days_display', inverse='_inverse_yearly_day_display') maximum_leave = fields.Float( 'Limit to', required=False, default=100, help="Choose a cap for this accrual. 0 means no cap.") parent_id = fields.Many2one( 'hr.leave.accrual.level', string="Previous Level", help="If this field is empty, this level is the first one.") action_with_unused_accruals = fields.Selection( [('postponed', 'Transferred to the next year'), ('lost', 'Lost')], string="At the end of the calendar year, unused accruals will be", default='postponed', required='True') _sql_constraints = [ ('check_dates', "CHECK( (frequency = 'daily') or" "(week_day IS NOT NULL AND frequency = 'weekly') or " "(first_day > 0 AND second_day > first_day AND first_day <= 31 AND second_day <= 31 AND frequency = 'bimonthly') or " "(first_day > 0 AND first_day <= 31 AND frequency = 'monthly')or " "(first_month_day > 0 AND first_month_day <= 31 AND second_month_day > 0 AND second_month_day <= 31 AND frequency = 'biyearly') or " "(yearly_day > 0 AND yearly_day <= 31 AND frequency = 'yearly'))", "The dates you've set up aren't correct. Please check them."), ('start_count_check', "CHECK( start_count >= 0 )", "You can not start an accrual in the past."), ('added_value_greater_than_zero', 'CHECK(added_value > 0)', 'You must give a rate greater than 0 in accrual plan levels.') ] @api.depends('start_count', 'start_type') def _compute_sequence(self): # Not 100% accurate because of odd months/years, but good enough start_type_multipliers = { 'day': 1, 'month': 30, 'year': 365, } for level in self: level.sequence = level.start_count * start_type_multipliers[level.start_type] @api.depends('sequence', 'accrual_plan_id') def _compute_level(self): #Mapped level_ids.ids ordered by sequence per plan mapped_level_ids = {} for plan in self.accrual_plan_id: # We can not use .ids here because we also deal with NewIds mapped_level_ids[plan] = [level.id for level in plan.level_ids.sorted('sequence')] for level in self: if level.accrual_plan_id: level.level = mapped_level_ids[level.accrual_plan_id].index(level.id) + 1 else: level.level = 1 @api.depends('first_day', 'second_day', 'first_month_day', 'second_month_day', 'yearly_day') def _compute_days_display(self): days_select = _get_selection_days(self) for level in self: level.first_day_display = days_select[min(level.first_day - 1, 28)][0] level.second_day_display = days_select[min(level.second_day - 1, 28)][0] level.first_month_day_display = days_select[min(level.first_month_day - 1, 28)][0] level.second_month_day_display = days_select[min(level.second_month_day - 1, 28)][0] level.yearly_day_display = days_select[min(level.yearly_day - 1, 28)][0] def _inverse_first_day_display(self): for level in self: if level.first_day_display == 'last': level.first_day = 31 else: level.first_day = DAY_SELECT_VALUES.index(level.first_day_display) + 1 def _inverse_second_day_display(self): for level in self: if level.second_day_display == 'last': level.second_day = 31 else: level.second_day = DAY_SELECT_VALUES.index(level.second_day_display) + 1 def _inverse_first_month_day_display(self): for level in self: if level.first_month_day_display == 'last': level.first_month_day = 31 else: level.first_month_day = DAY_SELECT_VALUES.index(level.first_month_day_display) + 1 def _inverse_second_month_day_display(self): for level in self: if level.second_month_day_display == 'last': level.second_month_day = 31 else: level.second_month_day = DAY_SELECT_VALUES.index(level.second_month_day_display) + 1 def _inverse_yearly_day_display(self): for level in self: if level.yearly_day_display == 'last': level.yearly_day = 31 else: level.yearly_day = DAY_SELECT_VALUES.index(level.yearly_day_display) + 1 def _get_next_date(self, last_call): """ Returns the next date with the given last call """ self.ensure_one() if self.frequency == 'daily': return last_call + relativedelta(days=1) elif self.frequency == 'weekly': daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] weekday = daynames.index(self.week_day) return last_call + relativedelta(days=1, weekday=weekday) elif self.frequency == 'bimonthly': first_date = last_call + relativedelta(day=self.first_day) second_date = last_call + relativedelta(day=self.second_day) if last_call < first_date: return first_date elif last_call < second_date: return second_date else: return last_call + relativedelta(months=1, day=self.first_day) elif self.frequency == 'monthly': date = last_call + relativedelta(day=self.first_day) if last_call < date: return date else: return last_call + relativedelta(months=1, day=self.first_day) elif self.frequency == 'biyearly': first_month = MONTHS.index(self.first_month) + 1 second_month = MONTHS.index(self.second_month) + 1 first_date = last_call + relativedelta(month=first_month, day=self.first_month_day) second_date = last_call + relativedelta(month=second_month, day=self.second_month_day) if last_call < first_date: return first_date elif last_call < second_date: return second_date else: return last_call + relativedelta(years=1, month=first_month, day=self.first_month_day) elif self.frequency == 'yearly': month = MONTHS.index(self.yearly_month) + 1 date = last_call + relativedelta(month=month, day=self.yearly_day) if last_call < date: return date else: return last_call + relativedelta(years=1, month=month, day=self.yearly_day) else: return False def _get_previous_date(self, last_call): """ Returns the date a potential previous call would have been at For example if you have a monthly level giving 16/02 would return 01/02 Contrary to `_get_next_date` this function will return the 01/02 if that date is given """ self.ensure_one() if self.frequency == 'daily': return last_call elif self.frequency == 'weekly': daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] weekday = daynames.index(self.week_day) return last_call + relativedelta(days=-6, weekday=weekday) elif self.frequency == 'bimonthly': second_date = last_call + relativedelta(day=self.second_day) first_date = last_call + relativedelta(day=self.first_day) if last_call >= second_date: return second_date elif last_call >= first_date: return first_date else: return last_call + relativedelta(months=-1, day=self.second_day) elif self.frequency == 'monthly': date = last_call + relativedelta(day=self.first_day) if last_call >= date: return date else: return last_call + relativedelta(months=-1, day=self.first_day) elif self.frequency == 'biyearly': first_month = MONTHS.index(self.first_month) + 1 second_month = MONTHS.index(self.second_month) + 1 first_date = last_call + relativedelta(month=first_month, day=self.first_month_day) second_date = last_call + relativedelta(month=second_month, day=self.second_month_day) if last_call >= second_date: return second_date elif last_call >= first_date: return first_date else: return last_call + relativedelta(years=-1, month=second_month, day=self.second_month_day) elif self.frequency == 'yearly': month = MONTHS.index(self.yearly_month) + 1 year_date = last_call + relativedelta(month=month, day=self.yearly_day) if last_call >= year_date: return year_date else: return last_call + relativedelta(years=-1, month=month, day=self.yearly_day) else: return False
45.450331
13,726
12,928
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools.float_utils import float_round class HrEmployeeBase(models.AbstractModel): _inherit = "hr.employee.base" leave_manager_id = fields.Many2one( 'res.users', string='Time Off', compute='_compute_leave_manager', store=True, readonly=False, help='Select the user responsible for approving "Time Off" of this employee.\n' 'If empty, the approval is done by an Administrator or Approver (determined in settings/users).') remaining_leaves = fields.Float( compute='_compute_remaining_leaves', string='Remaining Paid Time Off', help='Total number of paid time off allocated to this employee, change this value to create allocation/time off request. ' 'Total based on all the time off types without overriding limit.') current_leave_state = fields.Selection(compute='_compute_leave_status', string="Current Time Off Status", selection=[ ('draft', 'New'), ('confirm', 'Waiting Approval'), ('refuse', 'Refused'), ('validate1', 'Waiting Second Approval'), ('validate', 'Approved'), ('cancel', 'Cancelled') ]) leave_date_from = fields.Date('From Date', compute='_compute_leave_status') leave_date_to = fields.Date('To Date', compute='_compute_leave_status') leaves_count = fields.Float('Number of Time Off', compute='_compute_remaining_leaves') allocation_count = fields.Float('Total number of days allocated.', compute='_compute_allocation_count') allocations_count = fields.Integer('Total number of allocations', compute="_compute_allocation_count") allocation_used_count = fields.Float('Total number of days off used', compute='_compute_total_allocation_used') show_leaves = fields.Boolean('Able to see Remaining Time Off', compute='_compute_show_leaves') is_absent = fields.Boolean('Absent Today', compute='_compute_leave_status', search='_search_absent_employee') allocation_display = fields.Char(compute='_compute_allocation_count') allocation_used_display = fields.Char(compute='_compute_total_allocation_used') hr_icon_display = fields.Selection(selection_add=[('presence_holiday_absent', 'On leave'), ('presence_holiday_present', 'Present but on leave')]) def _get_remaining_leaves(self): """ Helper to compute the remaining leaves for the current employees :returns dict where the key is the employee id, and the value is the remain leaves """ self._cr.execute(""" SELECT sum(h.number_of_days) AS days, h.employee_id FROM ( SELECT holiday_status_id, number_of_days, state, employee_id FROM hr_leave_allocation UNION ALL SELECT holiday_status_id, (number_of_days * -1) as number_of_days, state, employee_id FROM hr_leave ) h join hr_leave_type s ON (s.id=h.holiday_status_id) WHERE s.active = true AND h.state='validate' AND s.requires_allocation='yes' AND h.employee_id in %s GROUP BY h.employee_id""", (tuple(self.ids),)) return dict((row['employee_id'], row['days']) for row in self._cr.dictfetchall()) def _compute_remaining_leaves(self): remaining = {} if self.ids: remaining = self._get_remaining_leaves() for employee in self: value = float_round(remaining.get(employee.id, 0.0), precision_digits=2) employee.leaves_count = value employee.remaining_leaves = value def _compute_allocation_count(self): data = self.env['hr.leave.allocation'].read_group([ ('employee_id', 'in', self.ids), ('holiday_status_id.active', '=', True), ('state', '=', 'validate'), ], ['number_of_days:sum', 'employee_id'], ['employee_id']) rg_results = dict((d['employee_id'][0], {"employee_id_count": d['employee_id_count'], "number_of_days": d['number_of_days']}) for d in data) for employee in self: result = rg_results.get(employee.id) employee.allocation_count = float_round(result['number_of_days'], precision_digits=2) if result else 0.0 employee.allocation_display = "%g" % employee.allocation_count employee.allocations_count = result['employee_id_count'] if result else 0.0 def _compute_total_allocation_used(self): for employee in self: employee.allocation_used_count = float_round(employee.allocation_count - employee.remaining_leaves, precision_digits=2) employee.allocation_used_display = "%g" % employee.allocation_used_count def _compute_presence_state(self): super()._compute_presence_state() employees = self.filtered(lambda employee: employee.hr_presence_state != 'present' and employee.is_absent) employees.update({'hr_presence_state': 'absent'}) def _compute_presence_icon(self): super()._compute_presence_icon() employees_absent = self.filtered(lambda employee: employee.hr_icon_display not in ['presence_present', 'presence_absent_active'] and employee.is_absent) employees_absent.update({'hr_icon_display': 'presence_holiday_absent'}) employees_present = self.filtered(lambda employee: employee.hr_icon_display in ['presence_present', 'presence_absent_active'] and employee.is_absent) employees_present.update({'hr_icon_display': 'presence_holiday_present'}) def _compute_leave_status(self): # Used SUPERUSER_ID to forcefully get status of other user's leave, to bypass record rule holidays = self.env['hr.leave'].sudo().search([ ('employee_id', 'in', self.ids), ('date_from', '<=', fields.Datetime.now()), ('date_to', '>=', fields.Datetime.now()), ('state', '=', 'validate'), ]) leave_data = {} for holiday in holidays: leave_data[holiday.employee_id.id] = {} leave_data[holiday.employee_id.id]['leave_date_from'] = holiday.date_from.date() leave_data[holiday.employee_id.id]['leave_date_to'] = holiday.date_to.date() leave_data[holiday.employee_id.id]['current_leave_state'] = holiday.state for employee in self: employee.leave_date_from = leave_data.get(employee.id, {}).get('leave_date_from') employee.leave_date_to = leave_data.get(employee.id, {}).get('leave_date_to') employee.current_leave_state = leave_data.get(employee.id, {}).get('current_leave_state') employee.is_absent = leave_data.get(employee.id) and leave_data.get(employee.id, {}).get('current_leave_state') in ['validate'] @api.depends('parent_id') def _compute_leave_manager(self): for employee in self: previous_manager = employee._origin.parent_id.user_id manager = employee.parent_id.user_id if manager and employee.leave_manager_id == previous_manager or not employee.leave_manager_id: employee.leave_manager_id = manager elif not employee.leave_manager_id: employee.leave_manager_id = False def _compute_show_leaves(self): show_leaves = self.env['res.users'].has_group('hr_holidays.group_hr_holidays_user') for employee in self: if show_leaves or employee.user_id == self.env.user: employee.show_leaves = True else: employee.show_leaves = False def _search_absent_employee(self, operator, value): if operator not in ('=', '!=') or not isinstance(value, bool): raise UserError(_('Operation not supported')) # This search is only used for the 'Absent Today' filter however # this only returns employees that are absent right now. today_date = datetime.datetime.utcnow().date() today_start = fields.Datetime.to_string(today_date) today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59)) holidays = self.env['hr.leave'].sudo().search([ ('employee_id', '!=', False), ('state', '=', 'validate'), ('date_from', '<=', today_end), ('date_to', '>=', today_start), ]) operator = ['in', 'not in'][(operator == '=') != value] return [('id', operator, holidays.mapped('employee_id').ids)] @api.model def create(self, values): if 'parent_id' in values: manager = self.env['hr.employee'].browse(values['parent_id']).user_id values['leave_manager_id'] = values.get('leave_manager_id', manager.id) if values.get('leave_manager_id', False): approver_group = self.env.ref('hr_holidays.group_hr_holidays_responsible', raise_if_not_found=False) if approver_group: approver_group.sudo().write({'users': [(4, values['leave_manager_id'])]}) return super(HrEmployeeBase, self).create(values) def write(self, values): if 'parent_id' in values: manager = self.env['hr.employee'].browse(values['parent_id']).user_id if manager: to_change = self.filtered(lambda e: e.leave_manager_id == e.parent_id.user_id or not e.leave_manager_id) to_change.write({'leave_manager_id': values.get('leave_manager_id', manager.id)}) old_managers = self.env['res.users'] if 'leave_manager_id' in values: old_managers = self.mapped('leave_manager_id') if values['leave_manager_id']: old_managers -= self.env['res.users'].browse(values['leave_manager_id']) approver_group = self.env.ref('hr_holidays.group_hr_holidays_responsible', raise_if_not_found=False) if approver_group: approver_group.sudo().write({'users': [(4, values['leave_manager_id'])]}) res = super(HrEmployeeBase, self).write(values) # remove users from the Responsible group if they are no longer leave managers old_managers._clean_leave_responsible_users() if 'parent_id' in values or 'department_id' in values: today_date = fields.Datetime.now() hr_vals = {} if values.get('parent_id') is not None: hr_vals['manager_id'] = values['parent_id'] if values.get('department_id') is not None: hr_vals['department_id'] = values['department_id'] holidays = self.env['hr.leave'].sudo().search(['|', ('state', 'in', ['draft', 'confirm']), ('date_from', '>', today_date), ('employee_id', 'in', self.ids)]) holidays.write(hr_vals) allocations = self.env['hr.leave.allocation'].sudo().search([('state', 'in', ['draft', 'confirm']), ('employee_id', 'in', self.ids)]) allocations.write(hr_vals) return res class HrEmployee(models.Model): _inherit = 'hr.employee' current_leave_id = fields.Many2one('hr.leave.type', compute='_compute_current_leave', string="Current Time Off Type", groups="hr.group_hr_user") def _compute_current_leave(self): self.current_leave_id = False holidays = self.env['hr.leave'].sudo().search([ ('employee_id', 'in', self.ids), ('date_from', '<=', fields.Datetime.now()), ('date_to', '>=', fields.Datetime.now()), ('state', '=', 'validate') ]) for holiday in holidays: employee = self.filtered(lambda e: e.id == holiday.employee_id.id) employee.current_leave_id = holiday.holiday_status_id.id def _get_user_m2o_to_empty_on_archived_employees(self): return super()._get_user_m2o_to_empty_on_archived_employees() + ['leave_manager_id'] def action_time_off_dashboard(self): return { 'name': _('Time Off Dashboard'), 'type': 'ir.actions.act_window', 'res_model': 'hr.leave', 'views': [[self.env.ref('hr_holidays.hr_leave_employee_view_dashboard').id, 'calendar']], 'domain': [('employee_id', 'in', self.ids)], 'context': { 'employee_id': self.ids, }, }
52.340081
12,928
44,063
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com) from collections import defaultdict import logging from datetime import datetime, time, timedelta from dateutil.relativedelta import relativedelta from odoo import api, fields, models from odoo.addons.resource.models.resource import HOURS_PER_DAY from odoo.exceptions import AccessError, UserError, ValidationError from odoo.tools.translate import _ from odoo.tools.float_utils import float_round from odoo.tools.date_utils import get_timedelta from odoo.osv import expression _logger = logging.getLogger(__name__) class HolidaysAllocation(models.Model): """ Allocation Requests Access specifications: similar to leave requests """ _name = "hr.leave.allocation" _description = "Time Off Allocation" _order = "create_date desc" _inherit = ['mail.thread', 'mail.activity.mixin'] _mail_post_access = 'read' def _default_holiday_status_id(self): if self.user_has_groups('hr_holidays.group_hr_holidays_user'): domain = [('has_valid_allocation', '=', True), ('requires_allocation', '=', 'yes')] else: domain = [('has_valid_allocation', '=', True), ('requires_allocation', '=', 'yes'), ('employee_requests', '=', 'yes')] return self.env['hr.leave.type'].search(domain, limit=1) def _domain_holiday_status_id(self): if self.user_has_groups('hr_holidays.group_hr_holidays_user'): return [('requires_allocation', '=', 'yes')] return [('employee_requests', '=', 'yes')] name = fields.Char('Description', compute='_compute_description', inverse='_inverse_description', search='_search_description', compute_sudo=False) name_validity = fields.Char('Description with validity', compute='_compute_description_validity') active = fields.Boolean(default=True) private_name = fields.Char('Allocation Description', groups='hr_holidays.group_hr_holidays_user') state = fields.Selection([ ('draft', 'To Submit'), ('cancel', 'Cancelled'), ('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate', 'Approved') ], string='Status', readonly=True, tracking=True, copy=False, default='draft', help="The status is set to 'To Submit', when an allocation request is created." + "\nThe status is 'To Approve', when an allocation request is confirmed by user." + "\nThe status is 'Refused', when an allocation request is refused by manager." + "\nThe status is 'Approved', when an allocation request is approved by manager.") date_from = fields.Date('Start Date', index=True, copy=False, default=fields.Date.context_today, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, tracking=True, required=True) date_to = fields.Date('End Date', copy=False, tracking=True, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}) holiday_status_id = fields.Many2one( "hr.leave.type", compute='_compute_holiday_status_id', store=True, string="Time Off Type", required=True, readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]}, domain=_domain_holiday_status_id, default=_default_holiday_status_id) employee_id = fields.Many2one( 'hr.employee', compute='_compute_from_employee_ids', store=True, string='Employee', index=True, readonly=False, ondelete="restrict", tracking=True, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate': [('readonly', True)]}) employee_company_id = fields.Many2one(related='employee_id.company_id', readonly=True, store=True) active_employee = fields.Boolean('Active Employee', related='employee_id.active', readonly=True) manager_id = fields.Many2one('hr.employee', compute='_compute_manager_id', store=True, string='Manager') notes = fields.Text('Reasons', readonly=True, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}) # duration number_of_days = fields.Float( 'Number of Days', compute='_compute_from_holiday_status_id', store=True, readonly=False, tracking=True, default=1, help='Duration in days. Reference field to use when necessary.') number_of_days_display = fields.Float( 'Duration (days)', compute='_compute_number_of_days_display', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help="If Accrual Allocation: Number of days allocated in addition to the ones you will get via the accrual' system.") number_of_hours_display = fields.Float( 'Duration (hours)', compute='_compute_number_of_hours_display', help="If Accrual Allocation: Number of hours allocated in addition to the ones you will get via the accrual' system.") duration_display = fields.Char('Allocated (Days/Hours)', compute='_compute_duration_display', help="Field allowing to see the allocation duration in days or hours depending on the type_request_unit") # details parent_id = fields.Many2one('hr.leave.allocation', string='Parent') linked_request_ids = fields.One2many('hr.leave.allocation', 'parent_id', string='Linked Requests') approver_id = fields.Many2one( 'hr.employee', string='First Approval', readonly=True, copy=False, help='This area is automatically filled by the user who validates the allocation') validation_type = fields.Selection(string='Validation Type', related='holiday_status_id.allocation_validation_type', readonly=True) can_reset = fields.Boolean('Can reset', compute='_compute_can_reset') can_approve = fields.Boolean('Can Approve', compute='_compute_can_approve') type_request_unit = fields.Selection(related='holiday_status_id.request_unit', readonly=True) # mode holiday_type = fields.Selection([ ('employee', 'By Employee'), ('company', 'By Company'), ('department', 'By Department'), ('category', 'By Employee Tag')], string='Allocation Mode', readonly=True, required=True, default='employee', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help="Allow to create requests in batchs:\n- By Employee: for a specific employee" "\n- By Company: all employees of the specified company" "\n- By Department: all employees of the specified department" "\n- By Employee Tag: all employees of the specific employee group category") employee_ids = fields.Many2many( 'hr.employee', compute='_compute_from_holiday_type', store=True, string='Employees', readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate': [('readonly', True)]}) multi_employee = fields.Boolean( compute='_compute_from_employee_ids', store=True, help='Holds whether this allocation concerns more than 1 employee') mode_company_id = fields.Many2one( 'res.company', compute='_compute_from_holiday_type', store=True, string='Company Mode', readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate': [('readonly', True)]}) department_id = fields.Many2one( 'hr.department', compute='_compute_department_id', store=True, string='Department', states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}) category_id = fields.Many2one( 'hr.employee.category', compute='_compute_from_holiday_type', store=True, string='Employee Tag', readonly=False, states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate': [('readonly', True)]}) # accrual configuration lastcall = fields.Date("Date of the last accrual allocation", readonly=True, default=fields.Date.context_today) nextcall = fields.Date("Date of the next accrual allocation", default=False, readonly=True) allocation_type = fields.Selection( [ ('regular', 'Regular Allocation'), ('accrual', 'Accrual Allocation') ], string="Allocation Type", default="regular", required=True, readonly=True, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}) is_officer = fields.Boolean(compute='_compute_is_officer') accrual_plan_id = fields.Many2one('hr.leave.accrual.plan', compute="_compute_from_holiday_status_id", store=True, readonly=False, domain="['|', ('time_off_type_id', '=', False), ('time_off_type_id', '=', holiday_status_id)]", tracking=True) max_leaves = fields.Float(compute='_compute_leaves') leaves_taken = fields.Float(compute='_compute_leaves') taken_leave_ids = fields.One2many('hr.leave', 'holiday_allocation_id', domain="[('state', 'in', ['confirm', 'validate1', 'validate'])]") _sql_constraints = [ ('type_value', "CHECK( (holiday_type='employee' AND (employee_id IS NOT NULL OR multi_employee IS TRUE)) or " "(holiday_type='category' AND category_id IS NOT NULL) or " "(holiday_type='department' AND department_id IS NOT NULL) or " "(holiday_type='company' AND mode_company_id IS NOT NULL))", "The employee, department, company or employee category of this request is missing. Please make sure that your user login is linked to an employee."), ('duration_check', "CHECK( ( number_of_days > 0 AND allocation_type='regular') or (allocation_type != 'regular'))", "The duration must be greater than 0."), ] # The compute does not get triggered without a depends on record creation # aka keep the 'useless' depends @api.depends_context('uid') @api.depends('allocation_type') def _compute_is_officer(self): self.is_officer = self.env.user.has_group("hr_holidays.group_hr_holidays_user") @api.depends_context('uid') def _compute_description(self): self.check_access_rights('read') self.check_access_rule('read') is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') for allocation in self: if is_officer or allocation.employee_id.user_id == self.env.user or allocation.employee_id.leave_manager_id == self.env.user: allocation.name = allocation.sudo().private_name else: allocation.name = '*****' def _inverse_description(self): is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') for allocation in self: if is_officer or allocation.employee_id.user_id == self.env.user or allocation.employee_id.leave_manager_id == self.env.user: allocation.sudo().private_name = allocation.name def _search_description(self, operator, value): is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') domain = [('private_name', operator, value)] if not is_officer: domain = expression.AND([domain, [('employee_id.user_id', '=', self.env.user.id)]]) allocations = self.sudo().search(domain) return [('id', 'in', allocations.ids)] @api.depends('name', 'date_from', 'date_to') def _compute_description_validity(self): for allocation in self: if allocation.date_to: name_validity = _("%s (from %s to %s)", allocation.name, allocation.date_from.strftime("%b %d %Y"), allocation.date_to.strftime("%b %d %Y")) else: name_validity = _("%s (from %s to No Limit)", allocation.name, allocation.date_from.strftime("%b %d %Y")) allocation.name_validity = name_validity @api.depends('employee_id', 'holiday_status_id', 'taken_leave_ids.number_of_days', 'taken_leave_ids.state') def _compute_leaves(self): employee_days_per_allocation = self.holiday_status_id._get_employees_days_per_allocation(self.employee_id.ids) for allocation in self: allocation.max_leaves = allocation.number_of_hours_display if allocation.type_request_unit == 'hour' else allocation.number_of_days allocation.leaves_taken = employee_days_per_allocation[allocation.employee_id.id][allocation.holiday_status_id][allocation]['leaves_taken'] @api.depends('number_of_days') def _compute_number_of_days_display(self): for allocation in self: allocation.number_of_days_display = allocation.number_of_days @api.depends('number_of_days', 'employee_id') def _compute_number_of_hours_display(self): for allocation in self: if allocation.parent_id and allocation.parent_id.type_request_unit == "hour": allocation.number_of_hours_display = allocation.number_of_days * HOURS_PER_DAY elif allocation.number_of_days: allocation.number_of_hours_display = allocation.number_of_days * (allocation.employee_id.sudo().resource_id.calendar_id.hours_per_day or HOURS_PER_DAY) else: allocation.number_of_hours_display = 0.0 @api.depends('number_of_hours_display', 'number_of_days_display') def _compute_duration_display(self): for allocation in self: allocation.duration_display = '%g %s' % ( (float_round(allocation.number_of_hours_display, precision_digits=2) if allocation.type_request_unit == 'hour' else float_round(allocation.number_of_days_display, precision_digits=2)), _('hours') if allocation.type_request_unit == 'hour' else _('days')) @api.depends('state', 'employee_id', 'department_id') def _compute_can_reset(self): for allocation in self: try: allocation._check_approval_update('draft') except (AccessError, UserError): allocation.can_reset = False else: allocation.can_reset = True @api.depends('state', 'employee_id', 'department_id') def _compute_can_approve(self): for allocation in self: try: if allocation.state == 'confirm' and allocation.validation_type != 'no': allocation._check_approval_update('validate') except (AccessError, UserError): allocation.can_approve = False else: allocation.can_approve = True @api.depends('employee_ids') def _compute_from_employee_ids(self): for allocation in self: if len(allocation.employee_ids) == 1: allocation.employee_id = allocation.employee_ids[0]._origin else: allocation.employee_id = False allocation.multi_employee = (len(allocation.employee_ids) > 1) @api.depends('holiday_type') def _compute_from_holiday_type(self): default_employee_ids = self.env['hr.employee'].browse(self.env.context.get('default_employee_id')) or self.env.user.employee_id for allocation in self: if allocation.holiday_type == 'employee': if not allocation.employee_ids: allocation.employee_ids = self.env.user.employee_id allocation.mode_company_id = False allocation.category_id = False elif allocation.holiday_type == 'company': allocation.employee_ids = False if not allocation.mode_company_id: allocation.mode_company_id = self.env.company allocation.category_id = False elif allocation.holiday_type == 'department': allocation.employee_ids = False allocation.mode_company_id = False allocation.category_id = False elif allocation.holiday_type == 'category': allocation.employee_ids = False allocation.mode_company_id = False else: allocation.employee_ids = default_employee_ids @api.depends('holiday_type', 'employee_id') def _compute_department_id(self): for allocation in self: if allocation.holiday_type == 'employee': allocation.department_id = allocation.employee_id.department_id elif allocation.holiday_type == 'department': if not allocation.department_id: allocation.department_id = self.env.user.employee_id.department_id elif allocation.holiday_type == 'category': allocation.department_id = False @api.depends('employee_id') def _compute_manager_id(self): for allocation in self: allocation.manager_id = allocation.employee_id and allocation.employee_id.parent_id @api.depends('accrual_plan_id') def _compute_holiday_status_id(self): default_holiday_status_id = None for holiday in self: if not holiday.holiday_status_id: if holiday.accrual_plan_id: holiday.holiday_status_id = holiday.accrual_plan_id.time_off_type_id else: if not default_holiday_status_id: # fetch when we need it default_holiday_status_id = self._default_holiday_status_id() holiday.holiday_status_id = default_holiday_status_id @api.depends('holiday_status_id', 'allocation_type', 'number_of_hours_display', 'number_of_days_display', 'date_to') def _compute_from_holiday_status_id(self): accrual_allocations = self.filtered(lambda alloc: alloc.allocation_type == 'accrual' and not alloc.accrual_plan_id and alloc.holiday_status_id) accruals_dict = {} if accrual_allocations: accruals_read_group = self.env['hr.leave.accrual.plan'].read_group( [('time_off_type_id', 'in', accrual_allocations.holiday_status_id.ids)], ['time_off_type_id', 'ids:array_agg(id)'], ['time_off_type_id'], ) accruals_dict = {res['time_off_type_id'][0]: res['ids'] for res in accruals_read_group} for allocation in self: allocation.number_of_days = allocation.number_of_days_display if allocation.type_request_unit == 'hour': allocation.number_of_days = allocation.number_of_hours_display / (allocation.employee_id.sudo().resource_calendar_id.hours_per_day or HOURS_PER_DAY) if allocation.accrual_plan_id.time_off_type_id.id not in (False, allocation.holiday_status_id.id): allocation.accrual_plan_id = False if allocation.allocation_type == 'accrual' and not allocation.accrual_plan_id: if allocation.holiday_status_id: allocation.accrual_plan_id = accruals_dict.get(allocation.holiday_status_id.id, [False])[0] def _end_of_year_accrual(self): # to override in payroll first_day_this_year = fields.Date.today() + relativedelta(month=1, day=1) for allocation in self: current_level = allocation._get_current_accrual_plan_level_id(first_day_this_year)[0] if current_level and current_level.action_with_unused_accruals == 'lost': lastcall = current_level._get_previous_date(first_day_this_year) nextcall = current_level._get_next_date(first_day_this_year) if lastcall == first_day_this_year: lastcall = current_level._get_previous_date(first_day_this_year - relativedelta(days=1)) nextcall = first_day_this_year # Allocations are lost but number_of_days should not be lower than leaves_taken allocation.write({'number_of_days': allocation.leaves_taken, 'lastcall': lastcall, 'nextcall': nextcall}) def _get_current_accrual_plan_level_id(self, date, level_ids=False): """ Returns a pair (accrual_plan_level, idx) where accrual_plan_level is the level for the given date and idx is the index for the plan in the ordered set of levels """ self.ensure_one() if not self.accrual_plan_id.level_ids: return (False, False) # Sort by sequence which should be equivalent to the level if not level_ids: level_ids = self.accrual_plan_id.level_ids.sorted('sequence') current_level = False current_level_idx = -1 for idx, level in enumerate(level_ids): if date > self.date_from + get_timedelta(level.start_count, level.start_type): current_level = level current_level_idx = idx # If transition_mode is set to `immediately` or we are currently on the first level # the current_level is simply the first level in the list. if current_level_idx <= 0 or self.accrual_plan_id.transition_mode == "immediately": return (current_level, current_level_idx) # In this case we have to verify that the 'previous level' is not the current one due to `end_of_accrual` level_start_date = self.date_from + get_timedelta(current_level.start_count, current_level.start_type) previous_level = level_ids[current_level_idx - 1] # If the next date from the current level's start date is before the last call of the previous level # return the previous level if current_level._get_next_date(level_start_date) < previous_level._get_next_date(level_start_date): return (previous_level, current_level_idx - 1) return (current_level, current_level_idx) def _process_accrual_plan_level(self, level, start_period, start_date, end_period, end_date): """ Returns the added days for that level """ self.ensure_one() if level.is_based_on_worked_time: start_dt = datetime.combine(start_date, datetime.min.time()) end_dt = datetime.combine(end_date, datetime.min.time()) worked = self.employee_id._get_work_days_data_batch(start_dt, end_dt, calendar=self.employee_id.resource_calendar_id)\ [self.employee_id.id]['hours'] if start_period != start_date or end_period != end_date: start_dt = datetime.combine(start_period, datetime.min.time()) end_dt = datetime.combine(end_period, datetime.min.time()) planned_worked = self.employee_id._get_work_days_data_batch(start_dt, end_dt, calendar=self.employee_id.resource_calendar_id)\ [self.employee_id.id]['hours'] else: planned_worked = worked left = self.employee_id.sudo()._get_leave_days_data_batch(start_dt, end_dt, domain=[('time_type', '=', 'leave')])[self.employee_id.id]['hours'] work_entry_prorata = worked / (left + planned_worked) if (left + planned_worked) else 0 added_value = work_entry_prorata * level.added_value else: added_value = level.added_value # Convert time in hours to time in days in case the level is encoded in hours if level.added_value_type == 'hours': added_value = added_value / (self.employee_id.sudo().resource_id.calendar_id.hours_per_day or HOURS_PER_DAY) period_prorata = 1 if (start_period != start_date or end_period != end_date) and not level.is_based_on_worked_time: period_days = (end_period - start_period) call_days = (end_date - start_date) period_prorata = min(1, call_days / period_days) if period_days else 1 return added_value * period_prorata def _process_accrual_plans(self): """ This method is part of the cron's process. The goal of this method is to retroactively apply accrual plan levels and progress from nextcall to today """ today = fields.Date.today() first_allocation = _("""This allocation have already ran once, any modification won't be effective to the days allocated to the employee. If you need to change the configuration of the allocation, cancel and create a new one.""") for allocation in self: level_ids = allocation.accrual_plan_id.level_ids.sorted('sequence') if not level_ids: continue if not allocation.nextcall: first_level = level_ids[0] first_level_start_date = allocation.date_from + get_timedelta(first_level.start_count, first_level.start_type) if today < first_level_start_date: # Accrual plan is not configured properly or has not started continue allocation.lastcall = max(allocation.lastcall, first_level_start_date) allocation.nextcall = first_level._get_next_date(allocation.lastcall) if len(level_ids) > 1: second_level_start_date = allocation.date_from + get_timedelta(level_ids[1].start_count, level_ids[1].start_type) allocation.nextcall = min(second_level_start_date, allocation.nextcall) allocation._message_log(body=first_allocation) days_added_per_level = defaultdict(lambda: 0) while allocation.nextcall <= today: (current_level, current_level_idx) = allocation._get_current_accrual_plan_level_id(allocation.nextcall) current_level_maximum_leave = current_level.maximum_leave if current_level.added_value_type == "days" else current_level.maximum_leave / (allocation.employee_id.sudo().resource_id.calendar_id.hours_per_day or HOURS_PER_DAY) nextcall = current_level._get_next_date(allocation.nextcall) # Since _get_previous_date returns the given date if it corresponds to a call date # this will always return lastcall except possibly on the first call # this is used to prorate the first number of days given to the employee period_start = current_level._get_previous_date(allocation.lastcall) period_end = current_level._get_next_date(allocation.lastcall) # Also prorate this accrual in the event that we are passing from one level to another if current_level_idx < (len(level_ids) - 1) and allocation.accrual_plan_id.transition_mode == 'immediately': next_level = level_ids[current_level_idx + 1] current_level_last_date = allocation.date_from + get_timedelta(next_level.start_count, next_level.start_type) if allocation.nextcall != current_level_last_date: nextcall = min(nextcall, current_level_last_date) days_added_per_level[current_level] += allocation._process_accrual_plan_level( current_level, period_start, allocation.lastcall, period_end, allocation.nextcall) if current_level_maximum_leave > 0 and sum(days_added_per_level.values()) > current_level_maximum_leave: days_added_per_level[current_level] -= sum(days_added_per_level.values()) - current_level_maximum_leave allocation.lastcall = allocation.nextcall allocation.nextcall = nextcall if days_added_per_level: number_of_days_to_add = allocation.number_of_days + sum(days_added_per_level.values()) max_allocation_days = current_level_maximum_leave + (allocation.leaves_taken if allocation.type_request_unit != "hour" else allocation.leaves_taken / (allocation.employee_id.sudo().resource_id.calendar_id.hours_per_day or HOURS_PER_DAY)) # Let's assume the limit of the last level is the correct one allocation.number_of_days = min(number_of_days_to_add, max_allocation_days) if current_level_maximum_leave > 0 else number_of_days_to_add @api.model def _update_accrual(self): """ Method called by the cron task in order to increment the number_of_days when necessary. """ # Get the current date to determine the start and end of the accrual period today = datetime.combine(fields.Date.today(), time(0, 0, 0)) this_year_first_day = today + relativedelta(day=1, month=1) end_of_year_allocations = self.search( [('allocation_type', '=', 'accrual'), ('state', '=', 'validate'), ('accrual_plan_id', '!=', False), ('employee_id', '!=', False), '|', ('date_to', '=', False), ('date_to', '>', fields.Datetime.now()), ('lastcall', '<', this_year_first_day)]) end_of_year_allocations._end_of_year_accrual() end_of_year_allocations.flush() allocations = self.search( [('allocation_type', '=', 'accrual'), ('state', '=', 'validate'), ('accrual_plan_id', '!=', False), ('employee_id', '!=', False), '|', ('date_to', '=', False), ('date_to', '>', fields.Datetime.now()), '|', ('nextcall', '=', False), ('nextcall', '<=', today)]) allocations._process_accrual_plans() #################################################### # ORM Overrides methods #################################################### def name_get(self): res = [] for allocation in self: if allocation.holiday_type == 'company': target = allocation.mode_company_id.name elif allocation.holiday_type == 'department': target = allocation.department_id.name elif allocation.holiday_type == 'category': target = allocation.category_id.name elif allocation.employee_id: target = allocation.employee_id.name else: target = ', '.join(allocation.employee_ids.sudo().mapped('name')) res.append( (allocation.id, _("Allocation of %(allocation_name)s : %(duration).2f %(duration_type)s to %(person)s", allocation_name=allocation.holiday_status_id.sudo().name, duration=allocation.number_of_hours_display if allocation.type_request_unit == 'hour' else allocation.number_of_days, duration_type=_('hours') if allocation.type_request_unit == 'hour' else _('days'), person=target )) ) return res def add_follower(self, employee_id): employee = self.env['hr.employee'].browse(employee_id) if employee.user_id: self.message_subscribe(partner_ids=employee.user_id.partner_id.ids) @api.model_create_multi def create(self, vals_list): """ Override to avoid automatic logging of creation """ for values in vals_list: employee_id = values.get('employee_id', False) if not values.get('department_id'): values.update({'department_id': self.env['hr.employee'].browse(employee_id).department_id.id}) # default `lastcall` to `nextcall` if 'date_from' in values and 'lastcall' not in values: values['lastcall'] = values['date_from'] holidays = super(HolidaysAllocation, self.with_context(mail_create_nosubscribe=True)).create(vals_list) for holiday in holidays: partners_to_subscribe = set() if holiday.employee_id.user_id: partners_to_subscribe.add(holiday.employee_id.user_id.partner_id.id) if holiday.validation_type == 'officer': partners_to_subscribe.add(holiday.employee_id.parent_id.user_id.partner_id.id) partners_to_subscribe.add(holiday.employee_id.leave_manager_id.partner_id.id) holiday.message_subscribe(partner_ids=tuple(partners_to_subscribe)) if not self._context.get('import_file'): holiday.activity_update() if holiday.validation_type == 'no': if holiday.state == 'draft': holiday.action_confirm() holiday.action_validate() return holidays def write(self, values): if not self.env.context.get('toggle_active') and not bool(values.get('active', True)): if any(allocation.state not in ['draft', 'cancel', 'refuse'] for allocation in self): raise UserError(_('You cannot archive an allocation which is in confirm or validate state.')) employee_id = values.get('employee_id', False) if values.get('state'): self._check_approval_update(values['state']) result = super(HolidaysAllocation, self).write(values) self.add_follower(employee_id) return result @api.ondelete(at_uninstall=False) def _unlink_if_correct_states(self): state_description_values = {elem[0]: elem[1] for elem in self._fields['state']._description_selection(self.env)} for holiday in self.filtered(lambda holiday: holiday.state not in ['draft', 'cancel', 'confirm']): raise UserError(_('You cannot delete an allocation request which is in %s state.') % (state_description_values.get(holiday.state),)) @api.ondelete(at_uninstall=False) def _unlink_if_no_leaves(self): if any(allocation.holiday_status_id.requires_allocation == 'yes' and allocation.leaves_taken > 0 for allocation in self): raise UserError(_('You cannot delete an allocation request which has some validated leaves.')) def _get_mail_redirect_suggested_company(self): return self.holiday_status_id.company_id #################################################### # Business methods #################################################### def _prepare_holiday_values(self, employees): self.ensure_one() return [{ 'name': self.name, 'holiday_type': 'employee', 'holiday_status_id': self.holiday_status_id.id, 'notes': self.notes, 'number_of_days': self.number_of_days, 'parent_id': self.id, 'employee_id': employee.id, 'employee_ids': [(6, 0, [employee.id])], 'state': 'confirm', 'allocation_type': self.allocation_type, 'date_from': self.date_from, 'date_to': self.date_to, 'accrual_plan_id': self.accrual_plan_id.id, } for employee in employees] def action_draft(self): if any(holiday.state not in ['confirm', 'refuse'] for holiday in self): raise UserError(_('Allocation request state must be "Refused" or "To Approve" in order to be reset to Draft.')) self.write({ 'state': 'draft', 'approver_id': False, }) linked_requests = self.mapped('linked_request_ids') if linked_requests: linked_requests.action_draft() linked_requests.unlink() self.activity_update() return True def action_confirm(self): if self.filtered(lambda holiday: holiday.state != 'draft'): raise UserError(_('Allocation request must be in Draft state ("To Submit") in order to confirm it.')) res = self.write({'state': 'confirm'}) self.activity_update() return res def action_validate(self): current_employee = self.env.user.employee_id if any(holiday.state != 'confirm' for holiday in self): raise UserError(_('Allocation request must be confirmed in order to approve it.')) self.write({ 'state': 'validate', 'approver_id': current_employee.id }) for holiday in self: holiday._action_validate_create_childs() self.activity_update() return True def _action_validate_create_childs(self): childs = self.env['hr.leave.allocation'] # In the case we are in holiday_type `employee` and there is only one employee we can keep the same allocation # Otherwise we do need to create an allocation for all employees to have a behaviour that is in line # with the other holiday_type if self.state == 'validate' and (self.holiday_type in ['category', 'department', 'company'] or (self.holiday_type == 'employee' and len(self.employee_ids) > 1)): if self.holiday_type == 'employee': employees = self.employee_ids elif self.holiday_type == 'category': employees = self.category_id.employee_ids elif self.holiday_type == 'department': employees = self.department_id.member_ids else: employees = self.env['hr.employee'].search([('company_id', '=', self.mode_company_id.id)]) allocation_create_vals = self._prepare_holiday_values(employees) childs += self.with_context( mail_notify_force_send=False, mail_activity_automation_skip=True ).create(allocation_create_vals) if childs: childs.action_validate() return childs def action_refuse(self): current_employee = self.env.user.employee_id if any(holiday.state not in ['confirm', 'validate', 'validate1'] for holiday in self): raise UserError(_('Allocation request must be confirmed or validated in order to refuse it.')) self.write({'state': 'refuse', 'approver_id': current_employee.id}) # If a category that created several holidays, cancel all related linked_requests = self.mapped('linked_request_ids') if linked_requests: linked_requests.action_refuse() self.activity_update() return True def _check_approval_update(self, state): """ Check if target state is achievable. """ if self.env.is_superuser(): return current_employee = self.env.user.employee_id if not current_employee: return is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') is_manager = self.env.user.has_group('hr_holidays.group_hr_holidays_manager') for holiday in self: val_type = holiday.holiday_status_id.sudo().allocation_validation_type if state == 'confirm': continue if state == 'draft': if holiday.employee_id != current_employee and not is_manager: raise UserError(_('Only a time off Manager can reset other people allocation.')) continue if not is_officer and self.env.user != holiday.employee_id.leave_manager_id and not val_type == 'no': raise UserError(_('Only a time off Officer/Responsible or Manager can approve or refuse time off requests.')) if is_officer or self.env.user == holiday.employee_id.leave_manager_id: # use ir.rule based first access check: department, members, ... (see security.xml) holiday.check_access_rule('write') if holiday.employee_id == current_employee and not is_manager and not val_type == 'no': raise UserError(_('Only a time off Manager can approve its own requests.')) @api.onchange('allocation_type') def _onchange_allocation_type(self): if self.allocation_type == 'accrual': self.number_of_days = 0.0 elif not self.number_of_days_display: self.number_of_days = 1.0 # ------------------------------------------------------------ # Activity methods # ------------------------------------------------------------ def _get_responsible_for_approval(self): self.ensure_one() responsible = self.env.user if self.validation_type == 'officer' or self.validation_type == 'set': if self.holiday_status_id.responsible_id: responsible = self.holiday_status_id.responsible_id return responsible def activity_update(self): to_clean, to_do = self.env['hr.leave.allocation'], self.env['hr.leave.allocation'] for allocation in self: note = _( 'New Allocation Request created by %(user)s: %(count)s Days of %(allocation_type)s', user=allocation.create_uid.name, count=allocation.number_of_days, allocation_type=allocation.holiday_status_id.name ) if allocation.state == 'draft': to_clean |= allocation elif allocation.state == 'confirm': allocation.activity_schedule( 'hr_holidays.mail_act_leave_allocation_approval', note=note, user_id=allocation.sudo()._get_responsible_for_approval().id or self.env.user.id) elif allocation.state == 'validate1': allocation.activity_feedback(['hr_holidays.mail_act_leave_allocation_approval']) allocation.activity_schedule( 'hr_holidays.mail_act_leave_allocation_second_approval', note=note, user_id=allocation.sudo()._get_responsible_for_approval().id or self.env.user.id) elif allocation.state == 'validate': to_do |= allocation elif allocation.state == 'refuse': to_clean |= allocation if to_clean: to_clean.activity_unlink(['hr_holidays.mail_act_leave_allocation_approval', 'hr_holidays.mail_act_leave_allocation_second_approval']) if to_do: to_do.activity_feedback(['hr_holidays.mail_act_leave_allocation_approval', 'hr_holidays.mail_act_leave_allocation_second_approval']) #################################################### # Messaging methods #################################################### def _track_subtype(self, init_values): if 'state' in init_values and self.state == 'validate': allocation_notif_subtype_id = self.holiday_status_id.allocation_notif_subtype_id return allocation_notif_subtype_id or self.env.ref('hr_holidays.mt_leave_allocation') return super(HolidaysAllocation, self)._track_subtype(init_values) def _notify_get_groups(self, msg_vals=None): """ Handle HR users and officers recipients that can validate or refuse holidays directly from email. """ groups = super(HolidaysAllocation, self)._notify_get_groups(msg_vals=msg_vals) local_msg_vals = dict(msg_vals or {}) self.ensure_one() hr_actions = [] if self.state == 'confirm': app_action = self._notify_get_action_link('controller', controller='/allocation/validate', **local_msg_vals) hr_actions += [{'url': app_action, 'title': _('Approve')}] if self.state in ['confirm', 'validate', 'validate1']: ref_action = self._notify_get_action_link('controller', controller='/allocation/refuse', **local_msg_vals) hr_actions += [{'url': ref_action, 'title': _('Refuse')}] holiday_user_group_id = self.env.ref('hr_holidays.group_hr_holidays_user').id new_group = ( 'group_hr_holidays_user', lambda pdata: pdata['type'] == 'user' and holiday_user_group_id in pdata['groups'], { 'actions': hr_actions, }) return [new_group] + groups def message_subscribe(self, partner_ids=None, subtype_ids=None): # due to record rule can not allow to add follower and mention on validated leave so subscribe through sudo if self.state in ['validate', 'validate1']: self.check_access_rights('read') self.check_access_rule('read') return super(HolidaysAllocation, self.sudo()).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids) return super(HolidaysAllocation, self).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids)
56.636247
44,063
3,375
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 User(models.Model): _inherit = "res.users" leave_manager_id = fields.Many2one(related='employee_id.leave_manager_id') show_leaves = fields.Boolean(related='employee_id.show_leaves') allocation_used_count = fields.Float(related='employee_id.allocation_used_count') allocation_count = fields.Float(related='employee_id.allocation_count') leave_date_to = fields.Date(related='employee_id.leave_date_to') current_leave_state = fields.Selection(related='employee_id.current_leave_state') is_absent = fields.Boolean(related='employee_id.is_absent') allocation_used_display = fields.Char(related='employee_id.allocation_used_display') allocation_display = fields.Char(related='employee_id.allocation_display') hr_icon_display = fields.Selection(related='employee_id.hr_icon_display') @property def SELF_READABLE_FIELDS(self): return super().SELF_READABLE_FIELDS + [ 'leave_manager_id', 'show_leaves', 'allocation_used_count', 'allocation_count', 'leave_date_to', 'current_leave_state', 'is_absent', 'allocation_used_display', 'allocation_display', 'hr_icon_display', ] def _compute_im_status(self): super(User, self)._compute_im_status() on_leave_user_ids = self._get_on_leave_ids() for user in self: if user.id in on_leave_user_ids: if user.im_status == 'online': user.im_status = 'leave_online' elif user.im_status == 'away': user.im_status = 'leave_away' else: user.im_status = 'leave_offline' @api.model def _get_on_leave_ids(self, partner=False): now = fields.Datetime.now() field = 'partner_id' if partner else 'id' self.env['res.users'].flush(fnames=['active']) self.env['hr.leave'].flush(fnames=['user_id', 'state', 'date_from', 'date_to']) self.env.cr.execute('''SELECT res_users.%s FROM res_users JOIN hr_leave ON hr_leave.user_id = res_users.id AND state not in ('cancel', 'refuse') AND res_users.active = 't' AND date_from <= %%s AND date_to >= %%s''' % field, (now, now)) return [r[0] for r in self.env.cr.fetchall()] def _clean_leave_responsible_users(self): # self = old bunch of leave responsibles # This method compares the current leave managers # and remove the access rights to those who don't # need them anymore approver_group = self.env.ref('hr_holidays.group_hr_holidays_responsible', raise_if_not_found=False) if not self or not approver_group: return res = self.env['hr.employee'].read_group( [('leave_manager_id', 'in', self.ids)], ['leave_manager_id'], ['leave_manager_id']) responsibles_to_remove_ids = set(self.ids) - {x['leave_manager_id'][0] for x in res} approver_group.sudo().write({ 'users': [(3, manager_id) for manager_id in responsibles_to_remove_ids]})
45
3,375
1,459
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.tools.misc import DEFAULT_SERVER_DATE_FORMAT class ResPartner(models.Model): _inherit = 'res.partner' def _compute_im_status(self): super(ResPartner, self)._compute_im_status() absent_now = self._get_on_leave_ids() for partner in self: if partner.id in absent_now: if partner.im_status == 'online': partner.im_status = 'leave_online' elif partner.im_status == 'away': partner.im_status = 'leave_away' else: partner.im_status = 'leave_offline' @api.model def _get_on_leave_ids(self): return self.env['res.users']._get_on_leave_ids(partner=True) def mail_partner_format(self): """Override to add the current leave status.""" partners_format = super().mail_partner_format() for partner in self: # in the rare case of multi-user partner, return the earliest possible return date dates = partner.mapped('user_ids.leave_date_to') date = sorted(dates)[0] if dates and all(dates) else False partners_format.get(partner).update({ 'out_of_office_date_end': date.strftime(DEFAULT_SERVER_DATE_FORMAT) if date else False, }) return partners_format
39.432432
1,459
30,947
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com) import datetime import logging from collections import defaultdict from datetime import time, timedelta from odoo import api, fields, models from odoo.osv import expression from odoo.tools.translate import _ from odoo.tools.float_utils import float_round from odoo.addons.resource.models.resource import Intervals _logger = logging.getLogger(__name__) class HolidaysType(models.Model): _name = "hr.leave.type" _description = "Time Off Type" _order = 'sequence' @api.model def _model_sorting_key(self, leave_type): remaining = leave_type.virtual_remaining_leaves > 0 taken = leave_type.leaves_taken > 0 return -1*leave_type.sequence, leave_type.employee_requests == 'no' and remaining, leave_type.employee_requests == 'yes' and remaining, taken name = fields.Char('Time Off Type', required=True, translate=True) sequence = fields.Integer(default=100, help='The type with the smallest sequence is the default value in time off request') create_calendar_meeting = fields.Boolean(string="Display Time Off in Calendar", default=True) color_name = fields.Selection([ ('red', 'Red'), ('blue', 'Blue'), ('lightgreen', 'Light Green'), ('lightblue', 'Light Blue'), ('lightyellow', 'Light Yellow'), ('magenta', 'Magenta'), ('lightcyan', 'Light Cyan'), ('black', 'Black'), ('lightpink', 'Light Pink'), ('brown', 'Brown'), ('violet', 'Violet'), ('lightcoral', 'Light Coral'), ('lightsalmon', 'Light Salmon'), ('lavender', 'Lavender'), ('wheat', 'Wheat'), ('ivory', 'Ivory')], string='Color in Report', required=True, default='red', help='This color will be used in the time off summary located in Reporting > Time off by Department.') color = fields.Integer(string='Color', help="The color selected here will be used in every screen with the time off type.") icon_id = fields.Many2one('ir.attachment', string='Cover Image', domain="[('res_model', '=', 'hr.leave.type'), ('res_field', '=', 'icon_id')]") active = fields.Boolean('Active', default=True, help="If the active field is set to false, it will allow you to hide the time off type without removing it.") max_leaves = fields.Float(compute='_compute_leaves', string='Maximum Allowed', search='_search_max_leaves', help='This value is given by the sum of all time off requests with a positive value.') leaves_taken = fields.Float( compute='_compute_leaves', string='Time off Already Taken', help='This value is given by the sum of all time off requests with a negative value.') remaining_leaves = fields.Float( compute='_compute_leaves', string='Remaining Time Off', help='Maximum Time Off Allowed - Time Off Already Taken') virtual_remaining_leaves = fields.Float( compute='_compute_leaves', search='_search_virtual_remaining_leaves', string='Virtual Remaining Time Off', help='Maximum Time Off Allowed - Time Off Already Taken - Time Off Waiting Approval') virtual_leaves_taken = fields.Float( compute='_compute_leaves', string='Virtual Time Off Already Taken', help='Sum of validated and non validated time off requests.') # KBA TODO in master: rename, change to int group_days_allocation = fields.Float( compute='_compute_group_days_allocation', string='Days Allocated') group_days_leave = fields.Float( compute='_compute_group_days_leave', string='Group Time Off') company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) responsible_id = fields.Many2one( 'res.users', 'Responsible Time Off Officer', domain=lambda self: [('groups_id', 'in', self.env.ref('hr_holidays.group_hr_holidays_user').id)], help="Choose the Time Off Officer who will be notified to approve allocation or Time Off request") leave_validation_type = fields.Selection([ ('no_validation', 'No Validation'), ('hr', 'By Time Off Officer'), ('manager', "By Employee's Approver"), ('both', "By Employee's Approver and Time Off Officer")], default='hr', string='Leave Validation') requires_allocation = fields.Selection([ ('yes', 'Yes'), ('no', 'No Limit')], default="yes", required=True, string='Requires allocation') employee_requests = fields.Selection([ ('yes', 'Extra Days Requests Allowed'), ('no', 'Not Allowed')], default="no", required=True, string="Employee Requests") allocation_validation_type = fields.Selection([ ('no', 'No validation needed'), ('officer', 'Approved by Time Off Officer'), ('set', "Set by Time Off Officer")], default='officer', string='Approval') has_valid_allocation = fields.Boolean(compute='_compute_valid', search='_search_valid', help='This indicates if it is still possible to use this type of leave') time_type = fields.Selection([('leave', 'Time Off'), ('other', 'Other')], default='leave', string="Kind of Leave", help="Whether this should be computed as a holiday or as work time (eg: formation)") request_unit = fields.Selection([ ('day', 'Day'), ('half_day', 'Half Day'), ('hour', 'Hours')], default='day', string='Take Time Off in', required=True) unpaid = fields.Boolean('Is Unpaid', default=False) leave_notif_subtype_id = fields.Many2one('mail.message.subtype', string='Time Off Notification Subtype', default=lambda self: self.env.ref('hr_holidays.mt_leave', raise_if_not_found=False)) allocation_notif_subtype_id = fields.Many2one('mail.message.subtype', string='Allocation Notification Subtype', default=lambda self: self.env.ref('hr_holidays.mt_leave_allocation', raise_if_not_found=False)) support_document = fields.Boolean(string='Supporting Document') accruals_ids = fields.One2many('hr.leave.accrual.plan', 'time_off_type_id') accrual_count = fields.Float(compute="_compute_accrual_count", string="Accruals count") @api.model def _search_valid(self, operator, value): """ Returns leave_type ids for which a valid allocation exists or that don't need an allocation return [('id', domain_operator, [x['id'] for x in res])] """ date_to = self._context.get('default_date_from') or fields.Date.today().strftime('%Y-1-1') date_from = self._context.get('default_date_to') or fields.Date.today().strftime('%Y-12-31') employee_id = self._context.get('default_employee_id', self._context.get('employee_id')) or self.env.user.employee_id.id if not isinstance(value, bool): raise ValueError('Invalid value: %s' % (value)) if operator not in ['=', '!=']: raise ValueError('Invalid operator: %s' % (operator)) new_operator = 'in' if operator == '=' else 'not in' query = ''' SELECT holiday_status_id FROM hr_leave_allocation alloc WHERE alloc.employee_id = %s AND alloc.active = True AND alloc.state = 'validate' AND (alloc.date_to >= %s OR alloc.date_to IS NULL) AND alloc.date_from <= %s ''' self._cr.execute(query, (employee_id or None, date_to, date_from)) return [('id', new_operator, [x['holiday_status_id'] for x in self._cr.dictfetchall()])] @api.depends('requires_allocation') def _compute_valid(self): date_to = self._context.get('default_date_to', fields.Datetime.today()) date_from = self._context.get('default_date_from', fields.Datetime.today()) employee_id = self._context.get('default_employee_id', self._context.get('employee_id', self.env.user.employee_id.id)) for holiday_type in self: if holiday_type.requires_allocation == 'yes': allocation = self.env['hr.leave.allocation'].search([ ('holiday_status_id', '=', holiday_type.id), ('employee_id', '=', employee_id), '|', ('date_to', '>=', date_to), '&', ('date_to', '=', False), ('date_from', '<=', date_from)]) holiday_type.has_valid_allocation = bool(allocation) else: holiday_type.has_valid_allocation = True def _search_max_leaves(self, operator, value): value = float(value) employee_id = self._get_contextual_employee_id() leaves = defaultdict(int) if employee_id: allocations = self.env['hr.leave.allocation'].search([ ('employee_id', '=', employee_id), ('state', '=', 'validate') ]) for allocation in allocations: leaves[allocation.holiday_status_id.id] += allocation.number_of_days valid_leave = [] for leave in leaves: if operator == '>': if leaves[leave] > value: valid_leave.append(leave) elif operator == '<': if leaves[leave] < value: valid_leave.append(leave) elif operator == '=': if leaves[leave] == value: valid_leave.append(leave) elif operator == '!=': if leaves[leave] != value: valid_leave.append(leave) return [('id', 'in', valid_leave)] def _search_virtual_remaining_leaves(self, operator, value): value = float(value) leave_types = self.env['hr.leave.type'].search([]) valid_leave_types = self.env['hr.leave.type'] for leave_type in leave_types: if leave_type.requires_allocation == "yes": if operator == '>' and leave_type.virtual_remaining_leaves > value: valid_leave_types |= leave_type elif operator == '<' and leave_type.virtual_remaining_leaves < value: valid_leave_types |= leave_type elif operator == '>=' and leave_type.virtual_remaining_leaves >= value: valid_leave_types |= leave_type elif operator == '<=' and leave_type.virtual_remaining_leaves <= value: valid_leave_types |= leave_type elif operator == '=' and leave_type.virtual_remaining_leaves == value: valid_leave_types |= leave_type elif operator == '!=' and leave_type.virtual_remaining_leaves != value: valid_leave_types |= leave_type else: valid_leave_types |= leave_type return [('id', 'in', valid_leave_types.ids)] def _get_employees_days_per_allocation(self, employee_ids, date=None): leaves = self.env['hr.leave'].search([ ('employee_id', 'in', employee_ids), ('state', 'in', ['confirm', 'validate1', 'validate']), ('holiday_status_id', 'in', self.ids) ]) allocations = self.env['hr.leave.allocation'].with_context(active_test=False).search([ ('employee_id', 'in', employee_ids), ('state', 'in', ['validate']), ('holiday_status_id', 'in', self.ids), ]) if not date: date = fields.Date.to_date(self.env.context.get('default_date_from')) or fields.Date.context_today(self) # The allocation_employees dictionary groups the allocations based on the employee and the holiday type # The structure is the following: # - KEYS: # allocation_employees # |--employee_id # |--holiday_status_id # - VALUES: # Intervals with the start and end date of each allocation and associated allocations within this interval allocation_employees = defaultdict(lambda: defaultdict(list)) ### Creation of the allocation intervals ### for holiday_status_id in allocations.holiday_status_id: for employee_id in employee_ids: allocation_intervals = Intervals([( fields.datetime.combine(allocation.date_from, time.min), fields.datetime.combine(allocation.date_to or datetime.date.max, time.max), allocation) for allocation in allocations.filtered(lambda allocation: allocation.employee_id.id == employee_id and allocation.holiday_status_id == holiday_status_id)]) allocation_employees[employee_id][holiday_status_id] = allocation_intervals # The leave_employees dictionary groups the leavess based on the employee and the holiday type # The structure is the following: # - KEYS: # leave_employees # |--employee_id # |--holiday_status_id # - VALUES: # Intervals with the start and end date of each leave and associated leave within this interval leaves_employees = defaultdict(lambda: defaultdict(list)) leave_intervals = [] ### Creation of the leave intervals ### if leaves: for holiday_status_id in leaves.holiday_status_id: for employee_id in employee_ids: leave_intervals = Intervals([( fields.datetime.combine(leave.date_from, time.min), fields.datetime.combine(leave.date_to, time.max), leave) for leave in leaves.filtered(lambda leave: leave.employee_id.id == employee_id and leave.holiday_status_id == holiday_status_id)]) leaves_employees[employee_id][holiday_status_id] = leave_intervals # allocation_days_consumed is a dictionary to map the number of days/hours of leaves taken per allocation # The structure is the following: # - KEYS: # allocation_days_consumed # |--employee_id # |--holiday_status_id # |--allocation # |--virtual_leaves_taken # |--leaves_taken # |--virtual_remaining_leaves # |--remaining_leaves # |--max_leaves # - VALUES: # Integer representing the number of (virtual) remaining leaves, (virtual) leaves taken or max leaves for each allocation. # The unit is in hour or days depending on the leave type request unit allocations_days_consumed = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0)))) company_domain = [('company_id', 'in', list(set(self.env.company.ids + self.env.context.get('allowed_company_ids', []))))] ### Existing leaves assigned to allocations ### if leaves_employees: for employee_id, leaves_interval_by_status in leaves_employees.items(): for holiday_status_id in leaves_interval_by_status: days_consumed = allocations_days_consumed[employee_id][holiday_status_id] if allocation_employees[employee_id][holiday_status_id]: allocations = allocation_employees[employee_id][holiday_status_id] & leaves_interval_by_status[holiday_status_id] available_allocations = self.env['hr.leave.allocation'] for allocation_interval in allocations._items: available_allocations |= allocation_interval[2] # Consume the allocations that are close to expiration first sorted_available_allocations = available_allocations.filtered('date_to').sorted(key='date_to') sorted_available_allocations += available_allocations.filtered(lambda allocation: not allocation.date_to) leave_intervals = leaves_interval_by_status[holiday_status_id]._items for leave_interval in leave_intervals: leaves = leave_interval[2] for leave in leaves: if leave.leave_type_request_unit in ['day', 'half_day']: leave_duration = leave.number_of_days leave_unit = 'days' else: leave_duration = leave.number_of_hours_display leave_unit = 'hours' if holiday_status_id.requires_allocation != 'no': for available_allocation in sorted_available_allocations: if (available_allocation.date_to and available_allocation.date_to < leave.date_from.date()) \ or (available_allocation.date_from > leave.date_to.date()): continue virtual_remaining_leaves = (available_allocation.number_of_days if leave_unit == 'days' else available_allocation.number_of_hours_display) - allocations_days_consumed[employee_id][holiday_status_id][available_allocation]['virtual_leaves_taken'] max_leaves = min(virtual_remaining_leaves, leave_duration) days_consumed[available_allocation]['virtual_leaves_taken'] += max_leaves if leave.state == 'validate': days_consumed[available_allocation]['leaves_taken'] += max_leaves leave_duration -= max_leaves if leave_duration > 0: # There are not enough allocation for the number of leaves days_consumed[False]['virtual_remaining_leaves'] -= leave_duration # Hack to make sure that a sum of several allocations does not hide an error days_consumed['error']['virtual_remaining_leaves'] -= leave_duration else: days_consumed[False]['virtual_leaves_taken'] += leave_duration if leave.state == 'validate': days_consumed[False]['leaves_taken'] += leave_duration # Future available leaves future_allocations_date_from = fields.datetime.combine(date, time.min) future_allocations_date_to = fields.datetime.combine(date, time.max) + timedelta(days=5*365) for employee_id, allocation_intervals_by_status in allocation_employees.items(): employee = self.env['hr.employee'].browse(employee_id) for holiday_status_id, intervals in allocation_intervals_by_status.items(): if not intervals: continue future_allocation_intervals = intervals & Intervals([( future_allocations_date_from, future_allocations_date_to, self.env['hr.leave'])]) search_date = date for interval_from, interval_to, interval_allocations in future_allocation_intervals._items: if interval_from.date() > search_date: continue interval_allocations = interval_allocations.filtered('active') if not interval_allocations: continue # If no end date to the allocation, consider the number of days remaining as infinite employee_quantity_available = ( employee._get_work_days_data_batch(interval_from, interval_to, compute_leaves=False, domain=company_domain)[employee_id] if interval_to != future_allocations_date_to else {'days': float('inf'), 'hours': float('inf')} ) for allocation in interval_allocations: if allocation.date_from > search_date: continue days_consumed = allocations_days_consumed[employee_id][holiday_status_id][allocation] if allocation.type_request_unit in ['day', 'half_day']: quantity_available = employee_quantity_available['days'] remaining_days_allocation = (allocation.number_of_days - days_consumed['virtual_leaves_taken']) else: quantity_available = employee_quantity_available['hours'] remaining_days_allocation = (allocation.number_of_hours_display - days_consumed['virtual_leaves_taken']) if quantity_available <= remaining_days_allocation: search_date = interval_to.date() + timedelta(days=1) days_consumed['virtual_remaining_leaves'] += min(quantity_available, remaining_days_allocation) days_consumed['max_leaves'] = allocation.number_of_days if allocation.type_request_unit in ['day', 'half_day'] else allocation.number_of_hours_display days_consumed['remaining_leaves'] = days_consumed['max_leaves'] - days_consumed['leaves_taken'] if remaining_days_allocation >= quantity_available: break return allocations_days_consumed def get_employees_days(self, employee_ids, date=None): result = { employee_id: { leave_type.id: { 'max_leaves': 0, 'leaves_taken': 0, 'remaining_leaves': 0, 'virtual_remaining_leaves': 0, 'virtual_leaves_taken': 0, } for leave_type in self } for employee_id in employee_ids } if not date: date = fields.Date.to_date(self.env.context.get('default_date_from')) or fields.Date.context_today(self) allocations_days_consumed = self._get_employees_days_per_allocation(employee_ids, date) leave_keys = ['max_leaves', 'leaves_taken', 'remaining_leaves', 'virtual_remaining_leaves', 'virtual_leaves_taken'] for employee_id in allocations_days_consumed: for holiday_status_id in allocations_days_consumed[employee_id]: if allocations_days_consumed[employee_id][holiday_status_id].get('error'): for leave_key in leave_keys: result[employee_id][holiday_status_id if isinstance(holiday_status_id, int) else holiday_status_id.id][leave_key] = allocations_days_consumed[employee_id][holiday_status_id]['error'][leave_key] continue for allocation in allocations_days_consumed[employee_id][holiday_status_id]: if allocation and allocation.date_to and (allocation.date_to < date or allocation.date_from > date): continue for leave_key in leave_keys: result[employee_id][holiday_status_id if isinstance(holiday_status_id, int) else holiday_status_id.id][leave_key] += allocations_days_consumed[employee_id][holiday_status_id][allocation][leave_key] return result @api.model def get_days_all_request(self): leave_types = sorted(self.search([]).filtered(lambda x: ((x.virtual_remaining_leaves > 0 or x.max_leaves))), key=self._model_sorting_key, reverse=True) return [lt._get_days_request() for lt in leave_types] def _get_days_request(self): self.ensure_one() return (self.name, { 'remaining_leaves': ('%.2f' % self.remaining_leaves).rstrip('0').rstrip('.'), 'virtual_remaining_leaves': ('%.2f' % self.virtual_remaining_leaves).rstrip('0').rstrip('.'), 'max_leaves': ('%.2f' % self.max_leaves).rstrip('0').rstrip('.'), 'leaves_taken': ('%.2f' % self.leaves_taken).rstrip('0').rstrip('.'), 'virtual_leaves_taken': ('%.2f' % self.virtual_leaves_taken).rstrip('0').rstrip('.'), 'request_unit': self.request_unit, 'icon': self.sudo().icon_id.url, }, self.requires_allocation, self.id) def _get_contextual_employee_id(self): if 'employee_id' in self._context: employee_id = self._context['employee_id'] elif 'default_employee_id' in self._context: employee_id = self._context['default_employee_id'] else: employee_id = self.env.user.employee_id.id return employee_id @api.depends_context('employee_id', 'default_employee_id') def _compute_leaves(self): data_days = {} employee_id = self._get_contextual_employee_id() if employee_id: data_days = (self.get_employees_days(employee_id)[employee_id[0]] if isinstance(employee_id, list) else self.get_employees_days([employee_id])[employee_id]) for holiday_status in self: result = data_days.get(holiday_status.id, {}) holiday_status.max_leaves = result.get('max_leaves', 0) holiday_status.leaves_taken = result.get('leaves_taken', 0) holiday_status.remaining_leaves = result.get('remaining_leaves', 0) holiday_status.virtual_remaining_leaves = result.get('virtual_remaining_leaves', 0) holiday_status.virtual_leaves_taken = result.get('virtual_leaves_taken', 0) def _compute_group_days_allocation(self): grouped_res = self.env['hr.leave.allocation'].read_group( [('holiday_status_id', 'in', self.ids), ], ['holiday_status_id'], ['holiday_status_id'], ) grouped_dict = dict((data['holiday_status_id'][0], data['holiday_status_id_count']) for data in grouped_res) for allocation in self: allocation.group_days_allocation = grouped_dict.get(allocation.id, 0) def _compute_group_days_leave(self): grouped_res = self.env['hr.leave'].read_group( [('holiday_status_id', 'in', self.ids), ('date_from', '>=', fields.Datetime.to_string(datetime.datetime.now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)))], ['holiday_status_id'], ['holiday_status_id'], ) grouped_dict = dict((data['holiday_status_id'][0], data['holiday_status_id_count']) for data in grouped_res) for allocation in self: allocation.group_days_leave = grouped_dict.get(allocation.id, 0) def _compute_accrual_count(self): accrual_allocations = self.env['hr.leave.accrual.plan'].read_group([('time_off_type_id', 'in', self.ids)], ['time_off_type_id'], ['time_off_type_id']) mapped_data = dict((data['time_off_type_id'][0], data['time_off_type_id_count']) for data in accrual_allocations) for leave_type in self: leave_type.accrual_count = mapped_data.get(leave_type.id, 0) def name_get(self): if not self._context.get('employee_id'): # leave counts is based on employee_id, would be inaccurate if not based on correct employee return super(HolidaysType, self).name_get() res = [] for record in self: name = record.name if record.requires_allocation == "yes" and not self._context.get('from_manager_leave_form'): name = "%(name)s (%(count)s)" % { 'name': name, 'count': _('%g remaining out of %g') % ( float_round(record.virtual_remaining_leaves, precision_digits=2) or 0.0, float_round(record.max_leaves, precision_digits=2) or 0.0, ) + (_(' hours') if record.request_unit == 'hour' else _(' days')) } res.append((record.id, name)) return res @api.model def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None): """ Override _search to order the results, according to some employee. The order is the following - allocation fixed first, then allowing allocation, then free allocation - virtual remaining leaves (higher the better, so using reverse on sorted) This override is necessary because those fields are not stored and depends on an employee_id given in context. This sort will be done when there is an employee_id in context and that no other order has been given to the method. """ employee_id = self._get_contextual_employee_id() post_sort = (not count and not order and employee_id) leave_ids = super(HolidaysType, self)._search(args, offset=offset, limit=(None if post_sort else limit), order=order, count=count, access_rights_uid=access_rights_uid) leaves = self.browse(leave_ids) if post_sort: return leaves.sorted(key=self._model_sorting_key, reverse=True).ids[:limit or None] return leave_ids def action_see_days_allocated(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("hr_holidays.hr_leave_allocation_action_all") action['domain'] = [ ('holiday_status_id', 'in', self.ids), ] action['context'] = { 'default_holiday_type': 'department', 'default_holiday_status_id': self.ids[0], } return action def action_see_group_leaves(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("hr_holidays.hr_leave_action_action_approve_department") action['domain'] = [ ('holiday_status_id', '=', self.ids[0]), ('date_from', '>=', fields.Datetime.to_string(datetime.datetime.now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0))) ] action['context'] = { 'default_holiday_status_id': self.ids[0], } return action def action_see_accrual_plans(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("hr_holidays.open_view_accrual_plans") action['domain'] = [ ('time_off_type_id', '=', self.id), ] action['context'] = { 'default_time_off_type_id': self.id, } return action
54.968028
30,947
3,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, SUPERUSER_ID from odoo.addons.base.models.res_partner import _tz_get class LeaveReportCalendar(models.Model): _name = "hr.leave.report.calendar" _description = 'Time Off Calendar' _auto = False _order = "start_datetime DESC, employee_id" name = fields.Char(string='Name', readonly=True) start_datetime = fields.Datetime(string='From', readonly=True) stop_datetime = fields.Datetime(string='To', readonly=True) tz = fields.Selection(_tz_get, string="Timezone", readonly=True) duration = fields.Float(string='Duration', readonly=True, store=False) employee_id = fields.Many2one('hr.employee', readonly=True) department_id = fields.Many2one('hr.department', readonly=True) job_id = fields.Many2one('hr.job', readonly=True) company_id = fields.Many2one('res.company', readonly=True) state = fields.Selection([ ('draft', 'To Submit'), ('cancel', 'Cancelled'), # YTI This state seems to be unused. To remove ('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved') ], readonly=True) is_hatched = fields.Boolean('Hatched', readonly=True) is_striked = fields.Boolean('Striked', readonly=True) def init(self): tools.drop_view_if_exists(self._cr, 'hr_leave_report_calendar') self._cr.execute("""CREATE OR REPLACE VIEW hr_leave_report_calendar AS (SELECT hl.id AS id, CONCAT(em.name, ': ', hl.duration_display) AS name, hl.date_from AS start_datetime, hl.date_to AS stop_datetime, hl.employee_id AS employee_id, hl.state AS state, hl.department_id AS department_id, em.company_id AS company_id, em.job_id AS job_id, COALESCE( CASE WHEN hl.holiday_type = 'employee' THEN COALESCE(rr.tz, rc.tz) END, cc.tz, 'UTC' ) AS tz, hl.state = 'refuse' as is_striked, hl.state not in ('validate', 'refuse') as is_hatched FROM hr_leave hl LEFT JOIN hr_employee em ON em.id = hl.employee_id LEFT JOIN resource_resource rr ON rr.id = em.resource_id LEFT JOIN resource_calendar rc ON rc.id = em.resource_calendar_id LEFT JOIN res_company co ON co.id = em.company_id LEFT JOIN resource_calendar cc ON cc.id = co.resource_calendar_id WHERE hl.state IN ('confirm', 'validate', 'validate1') ); """) def _read(self, fields): res = super()._read(fields) if self.env.context.get('hide_employee_name') and 'employee_id' in self.env.context.get('group_by', []): name_field = self._fields['name'] for record in self.with_user(SUPERUSER_ID): self.env.cache.set(record, name_field, record.name.split(':')[-1].strip()) return res @api.model def get_unusual_days(self, date_from, date_to=None): return self.env.user.employee_id._get_unusual_days(date_from, date_to)
40.829268
3,348
4,855
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, _ from odoo.osv import expression class LeaveReport(models.Model): _name = "hr.leave.report" _description = 'Time Off Summary / Report' _auto = False _order = "date_from DESC, employee_id" employee_id = fields.Many2one('hr.employee', string="Employee", readonly=True) active_employee = fields.Boolean(related='employee_id.active', readonly=True) name = fields.Char('Description', readonly=True) number_of_days = fields.Float('Number of Days', readonly=True) leave_type = fields.Selection([ ('allocation', 'Allocation'), ('request', 'Time Off') ], string='Request Type', readonly=True) department_id = fields.Many2one('hr.department', string='Department', readonly=True) category_id = fields.Many2one('hr.employee.category', string='Employee Tag', readonly=True) holiday_status_id = fields.Many2one("hr.leave.type", string="Leave Type", readonly=True) state = fields.Selection([ ('draft', 'To Submit'), ('cancel', 'Cancelled'), ('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved') ], string='Status', readonly=True) holiday_type = fields.Selection([ ('employee', 'By Employee'), ('category', 'By Employee Tag') ], string='Allocation Mode', readonly=True) date_from = fields.Datetime('Start Date', readonly=True) date_to = fields.Datetime('End Date', readonly=True) company_id = fields.Many2one('res.company', string="Company", readonly=True) def init(self): tools.drop_view_if_exists(self._cr, 'hr_leave_report') self._cr.execute(""" CREATE or REPLACE view hr_leave_report as ( SELECT row_number() over(ORDER BY leaves.employee_id) as id, leaves.employee_id as employee_id, leaves.name as name, leaves.number_of_days as number_of_days, leaves.leave_type as leave_type, leaves.category_id as category_id, leaves.department_id as department_id, leaves.holiday_status_id as holiday_status_id, leaves.state as state, leaves.holiday_type as holiday_type, leaves.date_from as date_from, leaves.date_to as date_to, leaves.company_id from (select allocation.employee_id as employee_id, allocation.private_name as name, allocation.number_of_days as number_of_days, allocation.category_id as category_id, allocation.department_id as department_id, allocation.holiday_status_id as holiday_status_id, allocation.state as state, allocation.holiday_type, allocation.date_from as date_from, allocation.date_to as date_to, 'allocation' as leave_type, allocation.employee_company_id as company_id from hr_leave_allocation as allocation union all select request.employee_id as employee_id, request.private_name as name, (request.number_of_days * -1) as number_of_days, request.category_id as category_id, request.department_id as department_id, request.holiday_status_id as holiday_status_id, request.state as state, request.holiday_type, request.date_from as date_from, request.date_to as date_to, 'request' as leave_type, request.employee_company_id as company_id from hr_leave as request) leaves ); """) @api.model def action_time_off_analysis(self): domain = [('holiday_type', '=', 'employee')] if self.env.context.get('active_ids'): domain = expression.AND([ domain, [('employee_id', 'in', self.env.context.get('active_ids', []))] ]) return { 'name': _('Time Off Analysis'), 'type': 'ir.actions.act_window', 'res_model': 'hr.leave.report', 'view_mode': 'tree,pivot,form', 'search_view_id': [self.env.ref('hr_holidays.view_hr_holidays_filter_report').id], 'domain': domain, 'context': { 'search_default_group_type': True, 'search_default_year': True, 'search_default_validated': True, 'search_default_active_employee': True, } }
45.373832
4,855
4,774
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 LeaveReport(models.Model): _name = "hr.leave.employee.type.report" _description = 'Time Off Summary / Report' _auto = False _order = "date_from DESC, employee_id" employee_id = fields.Many2one('hr.employee', string="Employee", readonly=True) active_employee = fields.Boolean(related='employee_id.active', readonly=True) number_of_days = fields.Float('Number of Days', readonly=True, group_operator="sum") department_id = fields.Many2one('hr.department', string='Department', readonly=True) leave_type = fields.Many2one("hr.leave.type", string="Leave Type", readonly=True) holiday_status = fields.Selection([ ('taken', 'Taken'), #taken = validated ('left', 'Left'), ('planned', 'Planned') ]) state = fields.Selection([ ('draft', 'To Submit'), ('cancel', 'Cancelled'), ('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved') ], string='Status', readonly=True) date_from = fields.Datetime('Start Date', readonly=True) date_to = fields.Datetime('End Date', readonly=True) company_id = fields.Many2one('res.company', string="Company", readonly=True) def init(self): tools.drop_view_if_exists(self._cr, 'hr_leave_employee_type_report') self._cr.execute(""" CREATE or REPLACE view hr_leave_employee_type_report as ( SELECT row_number() over(ORDER BY leaves.employee_id) as id, leaves.employee_id as employee_id, leaves.number_of_days as number_of_days, leaves.department_id as department_id, leaves.leave_type as leave_type, leaves.holiday_status as holiday_status, leaves.state as state, leaves.date_from as date_from, leaves.date_to as date_to, leaves.company_id as company_id FROM (SELECT allocation.employee_id as employee_id, CASE WHEN request.number_of_days > 0 THEN allocation.number_of_days - request.number_of_days ELSE allocation.number_of_days END as number_of_days, allocation.department_id as department_id, allocation.holiday_status_id as leave_type, allocation.state as state, allocation.date_from as date_from, allocation.date_to as date_to, 'left' as holiday_status, allocation.employee_company_id as company_id FROM hr_leave_allocation as allocation LEFT JOIN (SELECT holiday_status_id, employee_id, sum(number_of_days) as number_of_days FROM hr_leave GROUP BY holiday_status_id, employee_id) request on (allocation.employee_id=request.employee_id and allocation.holiday_status_id = request.holiday_status_id) UNION ALL SELECT request.employee_id as employee_id, request.number_of_days as number_of_days, request.department_id as department_id, request.holiday_status_id as leave_type, request.state as state, request.date_from as date_from, request.date_to as date_to, CASE WHEN request.state IN ('validate1', 'validate') THEN 'taken' WHEN request.state = 'confirm' THEN 'planned' END as holiday_status, request.employee_company_id as company_id FROM hr_leave as request) leaves ); """) @api.model def action_time_off_analysis(self): domain = [] if self.env.context.get('active_ids'): domain = [('employee_id', 'in', self.env.context.get('active_ids', []))] return { 'name': _('Time Off Analysis'), 'type': 'ir.actions.act_window', 'res_model': 'hr.leave.employee.type.report', 'view_mode': 'pivot', 'search_view_id': [self.env.ref('hr_holidays.view_search_hr_holidays_employee_type_report').id], 'domain': domain, 'context': { 'search_default_year': True, 'search_default_company': True, 'search_default_employee': True, 'group_expand': True, } }
45.903846
4,774
5,715
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import calendar from datetime import timedelta from dateutil.relativedelta import relativedelta from odoo import api, fields, models, _ from odoo.exceptions import UserError class HrHolidaySummaryReport(models.AbstractModel): _name = 'report.hr_holidays.report_holidayssummary' _description = 'Holidays Summary Report' def _get_header_info(self, start_date, holiday_type): st_date = fields.Date.from_string(start_date) return { 'start_date': fields.Date.to_string(st_date), 'end_date': fields.Date.to_string(st_date + relativedelta(days=59)), 'holiday_type': 'Confirmed and Approved' if holiday_type == 'both' else holiday_type } def _date_is_day_off(self, date): return date.weekday() in (calendar.SATURDAY, calendar.SUNDAY,) def _get_day(self, start_date): res = [] start_date = fields.Date.from_string(start_date) for x in range(0, 60): color = '#ababab' if self._date_is_day_off(start_date) else '' res.append({'day_str': start_date.strftime('%a'), 'day': start_date.day , 'color': color}) start_date = start_date + relativedelta(days=1) return res def _get_months(self, start_date): # it works for geting month name between two dates. res = [] start_date = fields.Date.from_string(start_date) end_date = start_date + relativedelta(days=59) while start_date <= end_date: last_date = start_date + relativedelta(day=1, months=+1, days=-1) if last_date > end_date: last_date = end_date month_days = (last_date - start_date).days + 1 res.append({'month_name': start_date.strftime('%B'), 'days': month_days}) start_date += relativedelta(day=1, months=+1) return res def _get_leaves_summary(self, start_date, empid, holiday_type): res = [] count = 0 start_date = fields.Date.from_string(start_date) end_date = start_date + relativedelta(days=59) for index in range(0, 60): current = start_date + timedelta(index) res.append({'day': current.day, 'color': ''}) if self._date_is_day_off(current) : res[index]['color'] = '#ababab' # count and get leave summary details. holiday_type = ['confirm','validate'] if holiday_type == 'both' else ['confirm'] if holiday_type == 'Confirmed' else ['validate'] holidays = self.env['hr.leave'].search([ ('employee_id', '=', empid), ('state', 'in', holiday_type), ('date_from', '<=', str(end_date)), ('date_to', '>=', str(start_date)) ]) for holiday in holidays: # Convert date to user timezone, otherwise the report will not be consistent with the # value displayed in the interface. date_from = fields.Datetime.from_string(holiday.date_from) date_from = fields.Datetime.context_timestamp(holiday, date_from).date() date_to = fields.Datetime.from_string(holiday.date_to) date_to = fields.Datetime.context_timestamp(holiday, date_to).date() for index in range(0, ((date_to - date_from).days + 1)): if date_from >= start_date and date_from <= end_date: res[(date_from-start_date).days]['color'] = holiday.holiday_status_id.color_name date_from += timedelta(1) count += holiday.number_of_days employee = self.env['hr.employee'].browse(empid) return {'emp': employee.name, 'display': res, 'sum': count} def _get_data_from_report(self, data): res = [] Employee = self.env['hr.employee'] if 'depts' in data: for department in self.env['hr.department'].browse(data['depts']): res.append({ 'dept': department.name, 'data': [ self._get_leaves_summary(data['date_from'], emp.id, data['holiday_type']) for emp in Employee.search([('department_id', '=', department.id)]) ], 'color': self._get_day(data['date_from']), }) elif 'emp' in data: res.append({'data': [ self._get_leaves_summary(data['date_from'], emp.id, data['holiday_type']) for emp in Employee.browse(data['emp']) ]}) return res def _get_holidays_status(self): res = [] for holiday in self.env['hr.leave.type'].search([]): res.append({'color': holiday.color_name, 'name': holiday.name}) return res @api.model def _get_report_values(self, docids, data=None): if not data.get('form'): raise UserError(_("Form content is missing, this report cannot be printed.")) holidays_report = self.env['ir.actions.report']._get_report_from_name('hr_holidays.report_holidayssummary') holidays = self.env['hr.leave'].browse(self.ids) return { 'doc_ids': self.ids, 'doc_model': holidays_report.model, 'docs': holidays, 'get_header_info': self._get_header_info(data['form']['date_from'], data['form']['holiday_type']), 'get_day': self._get_day(data['form']['date_from']), 'get_months': self._get_months(data['form']['date_from']), 'get_data_from_report': self._get_data_from_report(data['form']), 'get_holidays_status': self._get_holidays_status(), }
46.08871
5,715
2,130
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mail.controllers.mail import MailController from odoo import http class HrHolidaysController(http.Controller): @http.route('/leave/validate', type='http', auth='user', methods=['GET']) def hr_holidays_request_validate(self, res_id, token): comparison, record, redirect = MailController._check_token_and_record_or_redirect('hr.leave', int(res_id), token) if comparison and record: try: record.action_approve() except Exception: return MailController._redirect_to_messaging() return redirect @http.route('/leave/refuse', type='http', auth='user', methods=['GET']) def hr_holidays_request_refuse(self, res_id, token): comparison, record, redirect = MailController._check_token_and_record_or_redirect('hr.leave', int(res_id), token) if comparison and record: try: record.action_refuse() except Exception: return MailController._redirect_to_messaging() return redirect @http.route('/allocation/validate', type='http', auth='user', methods=['GET']) def hr_holidays_allocation_validate(self, res_id, token): comparison, record, redirect = MailController._check_token_and_record_or_redirect('hr.leave.allocation', int(res_id), token) if comparison and record: try: record.action_approve() except Exception: return MailController._redirect_to_messaging() return redirect @http.route('/allocation/refuse', type='http', auth='user', methods=['GET']) def hr_holidays_allocation_refuse(self, res_id, token): comparison, record, redirect = MailController._check_token_and_record_or_redirect('hr.leave.allocation', int(res_id), token) if comparison and record: try: record.action_refuse() except Exception: return MailController._redirect_to_messaging() return redirect
44.375
2,130
817
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Skills e-learning', 'category': 'Hidden', 'version': '1.0', 'summary': 'Add completed courses to resumé of your employees', 'description': """ E-learning and Skills for HR ============================ This module add completed courses to resumé for employees. """, 'depends': ['hr_skills', 'website_slides'], 'data': [ 'views/hr_templates.xml', 'data/hr_resume_data.xml', ], 'auto_install': True, 'assets': { 'web.assets_backend': [ 'hr_skills_slides/static/src/scss/**/*', ], 'web.assets_qweb': [ 'hr_skills_slides/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
26.290323
815
1,896
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.tools import html2plaintext class SlideChannelPartner(models.Model): _inherit = 'slide.channel.partner' def _recompute_completion(self): res = super(SlideChannelPartner, self)._recompute_completion() partner_has_completed = { channel_partner.partner_id.id: channel_partner.channel_id for channel_partner in self if channel_partner.completed} employees = self.env['hr.employee'].sudo().search( [('user_id.partner_id', 'in', list(partner_has_completed.keys()))]) if employees: HrResumeLine = self.env['hr.resume.line'].sudo() line_type = self.env.ref('hr_skills_slides.resume_type_training', raise_if_not_found=False) line_type_id = line_type and line_type.id for employee in employees: channel = partner_has_completed[employee.user_id.partner_id.id] already_added = HrResumeLine.search([ ("employee_id", "in", employees.ids), ("channel_id", "=", channel.id), ("line_type_id", "=", line_type_id), ("display_type", "=", "course") ]) if not already_added: HrResumeLine.create({ 'employee_id': employee.id, 'name': channel.name, 'date_start': fields.Date.today(), 'date_end': fields.Date.today(), 'description': html2plaintext(channel.description), 'line_type_id': line_type_id, 'display_type': 'course', 'channel_id': channel.id }) return res
42.133333
1,896
355
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 ResumeLine(models.Model): _inherit = 'hr.resume.line' display_type = fields.Selection(selection_add=[('course', 'Course')]) channel_id = fields.Many2one('slide.channel', string="Course", readonly=True)
32.272727
355
530
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project Expenses', 'version': '1.0', 'category': 'Services/expenses', 'summary': 'Project expenses', 'description': 'Bridge created to add the number of expenses linked to an AA to a project form', 'depends': ['project', 'hr_expense'], 'data': [ 'views/project_project_views.xml', ], 'demo': [], 'installable': True, 'auto_install': True, 'license': 'LGPL-3', }
27.894737
530
2,426
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, _, _lt class Project(models.Model): _inherit = 'project.project' expenses_count = fields.Integer('# Expenses', compute='_compute_expenses_count', groups='hr_expense.group_hr_expense_team_approver') @api.depends('analytic_account_id') def _compute_expenses_count(self): expenses_data = self.env['hr.expense'].read_group([ ('analytic_account_id', '!=', False), ('analytic_account_id', 'in', self.analytic_account_id.ids) ], ['analytic_account_id'], ['analytic_account_id']) mapped_data = {data['analytic_account_id'][0]: data['analytic_account_id_count'] for data in expenses_data} for project in self: project.expenses_count = mapped_data.get(project.analytic_account_id.id, 0) # ---------------------------- # Actions # ---------------------------- def action_open_project_expenses(self): expenses = self.env['hr.expense'].search([ ('analytic_account_id', '!=', False), ('analytic_account_id', 'in', self.analytic_account_id.ids) ]) action = self.env["ir.actions.actions"]._for_xml_id("hr_expense.hr_expense_actions_all") action.update({ 'display_name': _('Expenses'), 'views': [[False, 'tree'], [False, 'form'], [False, 'kanban'], [False, 'graph'], [False, 'pivot']], 'context': {'default_analytic_account_id': self.analytic_account_id.id}, 'domain': [('id', 'in', expenses.ids)] }) if(len(expenses) == 1): action["views"] = [[False, 'form']] action["res_id"] = expenses.id return action # ---------------------------- # Project Updates # ---------------------------- def _get_stat_buttons(self): buttons = super(Project, self)._get_stat_buttons() if self.user_has_groups('hr_expense.group_hr_expense_team_approver'): buttons.append({ 'icon': 'money', 'text': _lt('Expenses'), 'number': self.expenses_count, 'action_type': 'object', 'action': 'action_open_project_expenses', 'show': self.expenses_count > 0, 'sequence': 10, }) return buttons
41.118644
2,426
12,371
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Point of Sale', 'version': '1.0.1', 'category': 'Sales/Point of Sale', 'sequence': 40, 'summary': 'User-friendly PoS interface for shops and restaurants', 'description': "", 'depends': ['stock_account', 'barcodes', 'web_editor', 'digest'], 'data': [ 'security/point_of_sale_security.xml', 'security/ir.model.access.csv', 'data/default_barcode_patterns.xml', 'data/digest_data.xml', 'wizard/pos_box.xml', 'wizard/pos_details.xml', 'wizard/pos_payment.xml', 'wizard/pos_close_session_wizard.xml', 'views/pos_assets_common.xml', 'views/pos_assets_index.xml', 'views/pos_assets_qunit.xml', 'views/point_of_sale_report.xml', 'views/point_of_sale_view.xml', 'views/pos_order_view.xml', 'views/pos_category_view.xml', 'views/product_view.xml', 'views/account_journal_view.xml', 'views/res_config_settings_views.xml', 'views/pos_payment_method_views.xml', 'views/pos_payment_views.xml', 'views/pos_config_view.xml', 'views/pos_bill_view.xml', 'views/pos_session_view.xml', 'views/point_of_sale_sequence.xml', 'data/point_of_sale_data.xml', 'views/pos_order_report_view.xml', 'views/account_statement_view.xml', 'views/digest_views.xml', 'views/res_partner_view.xml', 'views/report_userlabel.xml', 'views/report_saledetails.xml', 'views/point_of_sale_dashboard.xml', 'views/report_invoice.xml', ], 'demo': [ 'data/point_of_sale_demo.xml', ], 'installable': True, 'application': True, 'website': 'https://www.odoo.com/app/point-of-sale-shop', 'assets': { 'web.assets_tests': [ 'point_of_sale/static/tests/tours/**/*', ], 'point_of_sale.assets': [ 'web/static/fonts/fonts.scss', 'web/static/lib/fontawesome/css/font-awesome.css', 'web/static/lib/daterangepicker/daterangepicker.css', 'point_of_sale/static/src/css/pos.css', 'point_of_sale/static/src/css/keyboard.css', 'point_of_sale/static/src/css/pos_receipts.css', 'point_of_sale/static/src/css/popups/product_info_popup.css', 'point_of_sale/static/src/css/popups/common.css', 'point_of_sale/static/src/css/popups/cash_opening_popup.css', 'point_of_sale/static/src/css/popups/closing_pos_popup.css', 'point_of_sale/static/src/css/popups/money_details_popup.css', 'web/static/src/legacy/scss/fontawesome_overridden.scss', 'point_of_sale/static/lib/html2canvas.js', 'point_of_sale/static/lib/backbone/backbone.js', 'point_of_sale/static/lib/waitfont.js', 'point_of_sale/static/lib/sha1.js', 'point_of_sale/static/src/js/utils.js', 'point_of_sale/static/src/js/ClassRegistry.js', 'point_of_sale/static/src/js/PosComponent.js', 'point_of_sale/static/src/js/PosContext.js', 'point_of_sale/static/src/js/ComponentRegistry.js', 'point_of_sale/static/src/js/Registries.js', 'point_of_sale/static/src/js/db.js', 'point_of_sale/static/src/js/models.js', 'point_of_sale/static/src/js/keyboard.js', 'point_of_sale/static/src/js/barcode_reader.js', 'point_of_sale/static/src/js/printers.js', 'point_of_sale/static/src/js/Gui.js', 'point_of_sale/static/src/js/PopupControllerMixin.js', 'point_of_sale/static/src/js/ControlButtonsMixin.js', 'point_of_sale/static/src/js/Chrome.js', 'point_of_sale/static/src/js/devices.js', 'point_of_sale/static/src/js/payment.js', 'point_of_sale/static/src/js/custom_hooks.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ProductScreen.js', 'point_of_sale/static/src/js/Screens/ClientListScreen/ClientLine.js', 'point_of_sale/static/src/js/Screens/ClientListScreen/ClientDetailsEdit.js', 'point_of_sale/static/src/js/Screens/ClientListScreen/ClientListScreen.js', 'point_of_sale/static/src/js/Screens/TicketScreen/ControlButtons/InvoiceButton.js', 'point_of_sale/static/src/js/Screens/TicketScreen/ControlButtons/ReprintReceiptButton.js', 'point_of_sale/static/src/js/Screens/TicketScreen/OrderDetails.js', 'point_of_sale/static/src/js/Screens/TicketScreen/OrderlineDetails.js', 'point_of_sale/static/src/js/Screens/TicketScreen/ReprintReceiptScreen.js', 'point_of_sale/static/src/js/Screens/TicketScreen/TicketScreen.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PSNumpadInputButton.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentScreenNumpad.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentScreenElectronicPayment.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentScreenPaymentLines.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentScreenStatus.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentMethodButton.js', 'point_of_sale/static/src/js/Screens/PaymentScreen/PaymentScreen.js', 'point_of_sale/static/src/js/Screens/ProductScreen/Orderline.js', 'point_of_sale/static/src/js/Screens/ProductScreen/OrderSummary.js', 'point_of_sale/static/src/js/Screens/ProductScreen/OrderWidget.js', 'point_of_sale/static/src/js/Screens/ProductScreen/NumpadWidget.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ActionpadWidget.js', 'point_of_sale/static/src/js/Screens/ProductScreen/CategoryBreadcrumb.js', 'point_of_sale/static/src/js/Screens/ProductScreen/CategoryButton.js', 'point_of_sale/static/src/js/Screens/ProductScreen/CategorySimpleButton.js', 'point_of_sale/static/src/js/Screens/ProductScreen/HomeCategoryBreadcrumb.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ProductsWidgetControlPanel.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ProductItem.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ProductList.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ProductsWidget.js', 'point_of_sale/static/src/js/Screens/ReceiptScreen/WrappedProductNameLines.js', 'point_of_sale/static/src/js/Screens/ReceiptScreen/OrderReceipt.js', 'point_of_sale/static/src/js/Screens/ReceiptScreen/ReceiptScreen.js', 'point_of_sale/static/src/js/Screens/ScaleScreen/ScaleScreen.js', 'point_of_sale/static/src/js/ChromeWidgets/CashierName.js', 'point_of_sale/static/src/js/ChromeWidgets/ProxyStatus.js', 'point_of_sale/static/src/js/ChromeWidgets/SyncNotification.js', 'point_of_sale/static/src/js/ChromeWidgets/HeaderButton.js', 'point_of_sale/static/src/js/ChromeWidgets/SaleDetailsButton.js', 'point_of_sale/static/src/js/ChromeWidgets/CashMoveButton.js', 'point_of_sale/static/src/js/ChromeWidgets/TicketButton.js', 'point_of_sale/static/src/js/Misc/CurrencyAmount.js', 'point_of_sale/static/src/js/Misc/Draggable.js', 'point_of_sale/static/src/js/Misc/NotificationSound.js', 'point_of_sale/static/src/js/Misc/IndependentToOrderScreen.js', 'point_of_sale/static/src/js/Misc/AbstractReceiptScreen.js', 'point_of_sale/static/src/js/Misc/SearchBar.js', 'point_of_sale/static/src/js/ChromeWidgets/DebugWidget.js', 'point_of_sale/static/src/js/Popups/AbstractAwaitablePopup.js', 'point_of_sale/static/src/js/Popups/ErrorPopup.js', 'point_of_sale/static/src/js/Popups/ErrorBarcodePopup.js', 'point_of_sale/static/src/js/Popups/ConfirmPopup.js', 'point_of_sale/static/src/js/Popups/CashMovePopup.js', 'point_of_sale/static/src/js/Popups/ControlButtonPopup.js', 'point_of_sale/static/src/js/Popups/TextInputPopup.js', 'point_of_sale/static/src/js/Popups/TextAreaPopup.js', 'point_of_sale/static/src/js/Popups/ErrorTracebackPopup.js', 'point_of_sale/static/src/js/Popups/SelectionPopup.js', 'point_of_sale/static/src/js/Popups/EditListInput.js', 'point_of_sale/static/src/js/Popups/EditListPopup.js', 'point_of_sale/static/src/js/Popups/NumberPopup.js', 'point_of_sale/static/src/js/Popups/OfflineErrorPopup.js', 'point_of_sale/static/src/js/Popups/OrderImportPopup.js', 'point_of_sale/static/src/js/Popups/ProductConfiguratorPopup.js', 'point_of_sale/static/src/js/Popups/CashOpeningPopup.js', 'point_of_sale/static/src/js/Popups/ProductInfoPopup.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ControlButtons/OrderlineCustomerNoteButton.js', 'point_of_sale/static/src/js/Popups/ClosePosPopup.js', 'point_of_sale/static/src/js/Popups/MoneyDetailsPopup.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ControlButtons/SetPricelistButton.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ControlButtons/SetFiscalPositionButton.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ControlButtons/ProductInfoButton.js', 'point_of_sale/static/src/js/Screens/ProductScreen/ControlButtons/RefundButton.js', 'point_of_sale/static/src/js/ChromeWidgets/ClientScreenButton.js', 'point_of_sale/static/src/js/Misc/NumberBuffer.js', 'point_of_sale/static/src/js/Misc/MobileOrderWidget.js', 'point_of_sale/static/src/js/Notification.js', ], 'web.assets_backend': [ 'point_of_sale/static/src/scss/pos_dashboard.scss', 'point_of_sale/static/src/js/tours/point_of_sale.js', 'point_of_sale/static/src/js/debug_manager.js', 'point_of_sale/static/src/js/web_overrides/pos_config_form.js', ], 'point_of_sale.pos_assets_backend': [ ('include', 'web.assets_backend'), ('remove', 'web/static/src/core/errors/error_handlers.js'), ('remove', 'web/static/src/legacy/legacy_rpc_error_handler.js'), ], 'point_of_sale.pos_assets_backend_style': [ "web/static/src/core/ui/**/*.scss", ], 'point_of_sale.tests_assets': [ 'web/static/lib/qunit/qunit-2.9.1.css', 'web/static/lib/qunit/qunit-2.9.1.js', 'web/static/tests/legacy/helpers/**/*', ('remove', 'web/static/tests/legacy/helpers/test_utils_tests.js'), 'web/static/tests/legacy/legacy_setup.js', 'web/static/tests/helpers/**/*.js', 'web/static/tests/qunit.js', 'web/static/tests/main.js', 'web/static/tests/setup.js', # These 2 lines below are taken from web.assets_frontend # They're required for the web.frontend_legacy to work properly # It is expected to add other lines coming from the web.assets_frontend # if we need to add more and more legacy stuff that would require other scss or js. ('include', 'web._assets_helpers'), 'web/static/lib/bootstrap/scss/_variables.scss', ('include', 'web.frontend_legacy'), ], 'point_of_sale.qunit_suite_tests': [ 'web/static/tests/legacy/component_extension_tests.js', 'point_of_sale/static/tests/unit/**/*', ], 'point_of_sale.assets_backend_prod_only': [ 'point_of_sale/static/src/js/chrome_adapter.js', 'point_of_sale/static/src/js/main.js', 'web/static/src/start.js', 'web/static/src/legacy/legacy_setup.js', ], 'web.assets_qweb': [ 'point_of_sale/static/src/xml/**/*', ], }, 'license': 'LGPL-3', }
55.977376
12,371
103
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. {}
25.75
103
45,993
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPosSimpleInvoicedOrders(TestPoSCommon): """ Each test case only make a single **invoiced** order. Name of each test corresponds to a sheet in: https://docs.google.com/spreadsheets/d/1mt2jRSDU7OONPBFjwyTcnhRjITQI8rGMLLQA5K3fAjo/edit?usp=sharing """ def setUp(self): super(TestPosSimpleInvoicedOrders, self).setUp() self.config = self.basic_config self.product100 = self.create_product('Product_100', self.categ_basic, 100, 50) def test_01b(self): self._run_test({ 'payment_methods': self.cash_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_02b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'journal_id': self.config.invoice_journal_id.id, 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 100), { 'journal_id': self.config.journal_id.id, 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'journal_id': self.config.journal_id.id, 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'journal_id': self.bank_pm1.journal_id.id, 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_03b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.pay_later_pm, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'journal_id': self.config.invoice_journal_id.id, 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }, 'payments': [], } }, 'journal_entries_after_closing': { 'session_journal_entry': False, 'cash_statement': [], 'bank_payments': [], }, }) def test_04b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'journal_id': self.config.invoice_journal_id.id, 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_split_pm1, 100), { 'journal_id': self.config.journal_id.id, 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'journal_id': self.config.journal_id.id, 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'journal_id': self.bank_split_pm1.journal_id.id, 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_05b(self): self._run_test({ 'payment_methods': self.cash_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_split_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_10b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 200), { 'line_ids': [ # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': False, 'amount_residual': -100}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False, 'amount_residual': 200}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_11b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 200), { 'line_ids': [ # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': False, 'amount_residual': -100}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False, 'amount_residual': 200}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_12b(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_split_pm1, 200), { 'line_ids': [ # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': False, 'amount_residual': -100}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False, 'amount_residual': 200}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_13b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_split_pm1, 200), { 'line_ids': [ # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': False, 'amount_residual': -100}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False, 'amount_residual': 200}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_14b(self): self._run_test({ 'payment_methods': self.cash_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 200), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, ] }), ((self.cash_pm1, -100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_15b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 200), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, ] }), ((self.cash_pm1, -100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((-100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_16b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_split_pm1, 200), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, ] }), ((self.cash_pm1, -100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ], }, 'cash_statement': [ ((-100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_17b(self): self._run_test({ 'payment_methods': self.cash_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 200), (self.cash_split_pm1, -100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_split_pm1, 200), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, ] }), ((self.cash_split_pm1, -100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }), ((-100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_18b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False, 'amount_residual': 0}, # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False, 'amount_residual': 50}, ] }, 'payments': [ ((self.cash_pm1, 50), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ], }, 'cash_statement': [ ((50, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_19b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False, 'amount_residual': 0}, # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False, 'amount_residual': 50}, ] }, 'payments': [ ((self.bank_pm1, 50), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((50, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], }, }) def test_20b(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False, 'amount_residual': 0}, # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False, 'amount_residual': 50}, ] }, 'payments': [ ((self.bank_split_pm1, 50), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((50, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], }, }) def test_21b(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False, 'amount_residual': 0}, # needs to check the residual because it's supposed to be partial reconciled {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False, 'amount_residual': 50}, ] }, 'payments': [ ((self.cash_split_pm1, 50), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ], }, 'cash_statement': [ ((50, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], 'bank_payments': [], }, })
57.635338
45,993
30,383
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools from odoo.api import Environment from odoo.tools import DEFAULT_SERVER_DATE_FORMAT from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon from datetime import date, timedelta import odoo.tests class TestPointOfSaleHttpCommon(AccountTestInvoicingHttpCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) env = cls.env cls.env.user.groups_id += env.ref('point_of_sale.group_pos_manager') journal_obj = env['account.journal'] account_obj = env['account.account'] main_company = cls.company_data['company'] account_receivable = account_obj.create({'code': 'X1012', 'name': 'Account Receivable - Test', 'user_type_id': env.ref('account.data_account_type_receivable').id, 'reconcile': True}) env.company.account_default_pos_receivable_account_id = account_receivable env['ir.property']._set_default('property_account_receivable_id', 'res.partner', account_receivable, main_company) # Pricelists are set below, do not take demo data into account env['ir.property'].sudo().search([('name', '=', 'property_product_pricelist')]).unlink() cls.bank_journal = journal_obj.create({ 'name': 'Bank Test', 'type': 'bank', 'company_id': main_company.id, 'code': 'BNK', 'sequence': 10, }) env['pos.payment.method'].create({ 'name': 'Bank', 'journal_id': cls.bank_journal.id, }) cls.main_pos_config = env['pos.config'].create({ 'name': 'Shop', 'barcode_nomenclature_id': env.ref('barcodes.default_barcode_nomenclature').id, 'iface_orderline_customer_notes': True, }) env['res.partner'].create({ 'name': 'Deco Addict', }) cash_journal = journal_obj.create({ 'name': 'Cash Test', 'type': 'cash', 'company_id': main_company.id, 'code': 'CSH', 'sequence': 10, }) # Archive all existing product to avoid noise during the tours all_pos_product = env['product.product'].search([('available_in_pos', '=', True)]) discount = env.ref('point_of_sale.product_product_consumable') cls.tip = env.ref('point_of_sale.product_product_tip') (all_pos_product - discount - cls.tip)._write({'active': False}) # In DESKS categ: Desk Pad pos_categ_desks = env.ref('point_of_sale.pos_category_desks') # In DESKS categ: Whiteboard Pen pos_categ_misc = env.ref('point_of_sale.pos_category_miscellaneous') # In CHAIR categ: Letter Tray pos_categ_chairs = env.ref('point_of_sale.pos_category_chairs') # test an extra price on an attribute cls.whiteboard_pen = env['product.product'].create({ 'name': 'Whiteboard Pen', 'available_in_pos': True, 'list_price': 1.20, 'taxes_id': False, 'weight': 0.01, 'to_weight': True, 'pos_categ_id': pos_categ_misc.id, }) cls.wall_shelf = env['product.product'].create({ 'name': 'Wall Shelf Unit', 'available_in_pos': True, 'list_price': 1.98, 'taxes_id': False, 'barcode': '2100005000000', }) cls.small_shelf = env['product.product'].create({ 'name': 'Small Shelf', 'available_in_pos': True, 'list_price': 2.83, 'taxes_id': False, }) cls.magnetic_board = env['product.product'].create({ 'name': 'Magnetic Board', 'available_in_pos': True, 'list_price': 1.98, 'taxes_id': False, 'barcode': '2305000000004', }) cls.monitor_stand = env['product.product'].create({ 'name': 'Monitor Stand', 'available_in_pos': True, 'list_price': 3.19, 'taxes_id': False, 'barcode': '0123456789', # No pattern in barcode nomenclature }) cls.desk_pad = env['product.product'].create({ 'name': 'Desk Pad', 'available_in_pos': True, 'list_price': 1.98, 'taxes_id': False, 'pos_categ_id': pos_categ_desks.id, }) cls.letter_tray = env['product.product'].create({ 'name': 'Letter Tray', 'available_in_pos': True, 'list_price': 4.80, 'taxes_id': False, 'pos_categ_id': pos_categ_chairs.id, }) cls.desk_organizer = env['product.product'].create({ 'name': 'Desk Organizer', 'available_in_pos': True, 'list_price': 5.10, 'taxes_id': False, }) configurable_chair = env['product.product'].create({ 'name': 'Configurable Chair', 'available_in_pos': True, 'list_price': 10, 'taxes_id': False, }) attribute = env['product.attribute'].create({ 'name': 'add 2', }) attribute_value = env['product.attribute.value'].create({ 'name': 'add 2', 'attribute_id': attribute.id, }) line = env['product.template.attribute.line'].create({ 'product_tmpl_id': cls.whiteboard_pen.product_tmpl_id.id, 'attribute_id': attribute.id, 'value_ids': [(6, 0, attribute_value.ids)] }) line.product_template_value_ids[0].price_extra = 2 chair_color_attribute = env['product.attribute'].create({ 'name': 'Color', 'display_type': 'color', 'create_variant': 'no_variant', }) chair_color_red = env['product.attribute.value'].create({ 'name': 'Red', 'attribute_id': chair_color_attribute.id, 'html_color': '#ff0000', }) chair_color_blue = env['product.attribute.value'].create({ 'name': 'Blue', 'attribute_id': chair_color_attribute.id, 'html_color': '#0000ff', }) chair_color_line = env['product.template.attribute.line'].create({ 'product_tmpl_id': configurable_chair.product_tmpl_id.id, 'attribute_id': chair_color_attribute.id, 'value_ids': [(6, 0, [chair_color_red.id, chair_color_blue.id])] }) chair_color_line.product_template_value_ids[0].price_extra = 1 chair_legs_attribute = env['product.attribute'].create({ 'name': 'Chair Legs', 'display_type': 'select', 'create_variant': 'no_variant', }) chair_legs_metal = env['product.attribute.value'].create({ 'name': 'Metal', 'attribute_id': chair_legs_attribute.id, }) chair_legs_wood = env['product.attribute.value'].create({ 'name': 'Wood', 'attribute_id': chair_legs_attribute.id, }) chair_legs_line = env['product.template.attribute.line'].create({ 'product_tmpl_id': configurable_chair.product_tmpl_id.id, 'attribute_id': chair_legs_attribute.id, 'value_ids': [(6, 0, [chair_legs_metal.id, chair_legs_wood.id])] }) chair_fabrics_attribute = env['product.attribute'].create({ 'name': 'Fabrics', 'display_type': 'radio', 'create_variant': 'no_variant', }) chair_fabrics_leather = env['product.attribute.value'].create({ 'name': 'Leather', 'attribute_id': chair_fabrics_attribute.id, }) chair_fabrics_other = env['product.attribute.value'].create({ 'name': 'Other', 'attribute_id': chair_fabrics_attribute.id, 'is_custom': True, }) chair_fabrics_line = env['product.template.attribute.line'].create({ 'product_tmpl_id': configurable_chair.product_tmpl_id.id, 'attribute_id': chair_fabrics_attribute.id, 'value_ids': [(6, 0, [chair_fabrics_leather.id, chair_fabrics_other.id])] }) chair_color_line.product_template_value_ids[1].is_custom = True fixed_pricelist = env['product.pricelist'].create({ 'name': 'Fixed', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, 'applied_on': '0_product_variant', 'product_id': cls.wall_shelf.id, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 13.95, # test for issues like in 7f260ab517ebde634fc274e928eb062463f0d88f 'applied_on': '0_product_variant', 'product_id': cls.small_shelf.id, })], }) env['product.pricelist'].create({ 'name': 'Percentage', 'item_ids': [(0, 0, { 'compute_price': 'percentage', 'percent_price': 100, 'applied_on': '0_product_variant', 'product_id': cls.wall_shelf.id, }), (0, 0, { 'compute_price': 'percentage', 'percent_price': 99, 'applied_on': '0_product_variant', 'product_id': cls.small_shelf.id, }), (0, 0, { 'compute_price': 'percentage', 'percent_price': 0, 'applied_on': '0_product_variant', 'product_id': cls.magnetic_board.id, })], }) env['product.pricelist'].create({ 'name': 'Formula', 'item_ids': [(0, 0, { 'compute_price': 'formula', 'price_discount': 6, 'price_surcharge': 5, 'applied_on': '0_product_variant', 'product_id': cls.wall_shelf.id, }), (0, 0, { # .99 prices 'compute_price': 'formula', 'price_surcharge': -0.01, 'price_round': 1, 'applied_on': '0_product_variant', 'product_id': cls.small_shelf.id, }), (0, 0, { 'compute_price': 'formula', 'price_min_margin': 10, 'price_max_margin': 100, 'applied_on': '0_product_variant', 'product_id': cls.magnetic_board.id, }), (0, 0, { 'compute_price': 'formula', 'price_surcharge': 10, 'price_max_margin': 5, 'applied_on': '0_product_variant', 'product_id': cls.monitor_stand.id, }), (0, 0, { 'compute_price': 'formula', 'price_discount': -100, 'price_min_margin': 5, 'price_max_margin': 20, 'applied_on': '0_product_variant', 'product_id': cls.desk_pad.id, })], }) env['product.pricelist'].create({ 'name': 'min_quantity ordering', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, 'applied_on': '0_product_variant', 'min_quantity': 2, 'product_id': cls.wall_shelf.id, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, 'applied_on': '0_product_variant', 'min_quantity': 1, 'product_id': cls.wall_shelf.id, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, 'applied_on': '0_product_variant', 'min_quantity': 2, 'product_id': env.ref('point_of_sale.product_product_consumable').id, })], }) env['product.pricelist'].create({ 'name': 'Product template', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, 'applied_on': '1_product', 'product_tmpl_id': cls.wall_shelf.product_tmpl_id.id, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, })], }) product_category_3 = env['product.category'].create({ 'name': 'Services', 'parent_id': env.ref('product.product_category_1').id, }) env['product.pricelist'].create({ # no category has precedence over category 'name': 'Category vs no category', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, 'applied_on': '2_product_category', 'categ_id': product_category_3.id, # All / Saleable / Services }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, })], }) p = env['product.pricelist'].create({ 'name': 'Category', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, 'applied_on': '2_product_category', 'categ_id': env.ref('product.product_category_all').id, }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, 'applied_on': '2_product_category', 'categ_id': product_category_3.id, # All / Saleable / Services })], }) today = date.today() one_week_ago = today - timedelta(weeks=1) two_weeks_ago = today - timedelta(weeks=2) one_week_from_now = today + timedelta(weeks=1) two_weeks_from_now = today + timedelta(weeks=2) public_pricelist = env['product.pricelist'].create({ 'name': 'Public Pricelist', }) env['product.pricelist'].create({ 'name': 'Dates', 'item_ids': [(0, 0, { 'compute_price': 'fixed', 'fixed_price': 1, 'date_start': two_weeks_ago.strftime(DEFAULT_SERVER_DATE_FORMAT), 'date_end': one_week_ago.strftime(DEFAULT_SERVER_DATE_FORMAT), }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 2, 'date_start': today.strftime(DEFAULT_SERVER_DATE_FORMAT), 'date_end': one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT), }), (0, 0, { 'compute_price': 'fixed', 'fixed_price': 3, 'date_start': one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT), 'date_end': two_weeks_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT), })], }) cost_base_pricelist = env['product.pricelist'].create({ 'name': 'Cost base', 'item_ids': [(0, 0, { 'base': 'standard_price', 'compute_price': 'percentage', 'percent_price': 55, })], }) pricelist_base_pricelist = env['product.pricelist'].create({ 'name': 'Pricelist base', 'item_ids': [(0, 0, { 'base': 'pricelist', 'base_pricelist_id': cost_base_pricelist.id, 'compute_price': 'percentage', 'percent_price': 15, })], }) env['product.pricelist'].create({ 'name': 'Pricelist base 2', 'item_ids': [(0, 0, { 'base': 'pricelist', 'base_pricelist_id': pricelist_base_pricelist.id, 'compute_price': 'percentage', 'percent_price': 3, })], }) env['product.pricelist'].create({ 'name': 'Pricelist base rounding', 'item_ids': [(0, 0, { 'base': 'pricelist', 'base_pricelist_id': fixed_pricelist.id, 'compute_price': 'percentage', 'percent_price': 0.01, })], }) excluded_pricelist = env['product.pricelist'].create({ 'name': 'Not loaded' }) res_partner_18 = env['res.partner'].create({ 'name': 'Lumber Inc', 'is_company': True, }) res_partner_18.property_product_pricelist = excluded_pricelist test_sale_journal = journal_obj.create({'name': 'Sales Journal - Test', 'code': 'TSJ', 'type': 'sale', 'company_id': main_company.id}) all_pricelists = env['product.pricelist'].search([('id', '!=', excluded_pricelist.id)]) all_pricelists.write(dict(currency_id=main_company.currency_id.id)) src_tax = env['account.tax'].create({'name': "SRC", 'amount': 10}) dst_tax = env['account.tax'].create({'name': "DST", 'amount': 5}) cls.letter_tray.taxes_id = [(6, 0, [src_tax.id])] cls.main_pos_config.write({ 'tax_regime_selection': True, 'fiscal_position_ids': [(0, 0, { 'name': "FP-POS-2M", 'tax_ids': [ (0,0,{'tax_src_id': src_tax.id, 'tax_dest_id': src_tax.id}), (0,0,{'tax_src_id': src_tax.id, 'tax_dest_id': dst_tax.id})] })], 'journal_id': test_sale_journal.id, 'invoice_journal_id': test_sale_journal.id, 'payment_method_ids': [(0, 0, { 'name': 'Cash', 'journal_id': cash_journal.id, 'receivable_account_id': account_receivable.id, })], 'use_pricelist': True, 'pricelist_id': public_pricelist.id, 'available_pricelist_ids': [(4, pricelist.id) for pricelist in all_pricelists], 'module_pos_loyalty': False, }) # Change the default sale pricelist of customers, # so the js tests can expect deterministically this pricelist when selecting a customer. env['ir.property']._set_default("property_product_pricelist", "res.partner", public_pricelist, main_company) @odoo.tests.tagged('post_install', '-at_install') class TestUi(TestPointOfSaleHttpCommon): def test_01_pos_basic_order(self): self.main_pos_config.write({ 'iface_tipproduct': True, 'tip_product_id': self.tip.id, }) # open a session, the /pos/ui controller will redirect to it self.main_pos_config.open_session_cb(check_coa=False) # needed because tests are run before the module is marked as # installed. In js web will only load qweb coming from modules # that are returned by the backend in module_boot. Without # this you end up with js, css but no qweb. self.env['ir.module.module'].search([('name', '=', 'point_of_sale')], limit=1).state = 'installed' self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'pos_pricelist', login="accountman") self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'pos_basic_order', login="accountman") self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'ProductScreenTour', login="accountman") self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PaymentScreenTour', login="accountman") self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'ReceiptScreenTour', login="accountman") for order in self.env['pos.order'].search([]): self.assertEqual(order.state, 'paid', "Validated order has payment of " + str(order.amount_paid) + " and total of " + str(order.amount_total)) # check if email from ReceiptScreenTour is properly sent email_count = self.env['mail.mail'].search_count([('email_to', '=', 'test@receiptscreen.com')]) self.assertEqual(email_count, 1) def test_02_pos_with_invoiced(self): self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'ChromeTour', login="accountman") n_invoiced = self.env['pos.order'].search_count([('state', '=', 'invoiced')]) n_paid = self.env['pos.order'].search_count([('state', '=', 'paid')]) self.assertEqual(n_invoiced, 1, 'There should be 1 invoiced order.') self.assertEqual(n_paid, 2, 'There should be 2 paid order.') def test_04_product_configurator(self): self.main_pos_config.write({ 'product_configurator': True }) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config, 'ProductConfiguratorTour', login="accountman") def test_05_ticket_screen(self): self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'TicketScreenTour', login="accountman") def test_fixed_tax_negative_qty(self): """ Assert the negative amount of a negative-quantity orderline with zero-amount product with fixed tax. """ # setup the zero-amount product tax_received_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.env.company.id, }) fixed_tax = self.env['account.tax'].create({ 'name': 'fixed amount tax', 'amount_type': 'fixed', 'amount': 1, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_received_account.id, }), ], }) zero_amount_product = self.env['product.product'].create({ 'name': 'Zero Amount Product', 'available_in_pos': True, 'list_price': 0, 'taxes_id': [(6, 0, [fixed_tax.id])], }) # Make an order with the zero-amount product from the frontend. # We need to do this because of the fix in the "compute_all" port. self.main_pos_config.write({'iface_tax_included': 'total'}) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'FixedTaxNegativeQty', login="accountman") pos_session = self.main_pos_config.current_session_id # Close the session and check the session journal entry. pos_session.action_pos_session_validate() lines = pos_session.move_id.line_ids.sorted('balance') # order in the tour is paid using the bank payment method. bank_pm = self.main_pos_config.payment_method_ids.filtered(lambda pm: pm.name == 'Bank') self.assertEqual(lines[0].account_id, bank_pm.receivable_account_id or self.env.company.account_default_pos_receivable_account_id) self.assertAlmostEqual(lines[0].balance, -1) self.assertEqual(lines[1].account_id, zero_amount_product.categ_id.property_account_income_categ_id) self.assertAlmostEqual(lines[1].balance, 0) self.assertEqual(lines[2].account_id, tax_received_account) self.assertAlmostEqual(lines[2].balance, 1) def test_change_without_cash_method(self): #create bank payment method bank_pm = self.env['pos.payment.method'].create({ 'name': 'Bank', 'receivable_account_id': self.env.company.account_default_pos_receivable_account_id.id, 'is_cash_count': False, 'split_transactions': False, 'company_id': self.env.company.id, }) self.main_pos_config.write({'payment_method_ids': [(6, 0, bank_pm.ids)]}) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PaymentScreenTour2', login="accountman") def test_refund_without_cash_method(self): """ Assert that a refund cannot be made without cash payment method. """ bank_pm = self.env['pos.payment.method'].create({ 'name': 'Bank', 'journal_id': self.bank_journal.id, }) self.main_pos_config.write({"payment_method_ids": [(6, 0, bank_pm.ids)]}) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'PaymentScreenTour3', login="accountman") def test_pos_closing_cash_details(self): """Test if the cash closing details correctly show the cash difference if there is a difference at the opening of the PoS session. This also test if the accounting move are correctly created for the opening cash difference. e.g. If the previous session was closed with 100$ and the opening count is 50$, the closing popup should show a difference of 50$. """ self.main_pos_config.open_session_cb(check_coa=False) current_session = self.main_pos_config.current_session_id current_session.post_closing_cash_details(100) current_session.close_session_from_ui() self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'CashClosingDetails', login="accountman") #check accounting move for the pos opening cash difference pos_session = self.main_pos_config.current_session_id self.assertEqual(len(pos_session.statement_ids.line_ids), 1) self.assertEqual(pos_session.statement_ids.line_ids[0].amount, -10) def test_fiscal_position_no_tax(self): #create a tax of 15% with price included tax = self.env['account.tax'].create({ 'name': 'Tax 15%', 'amount': 15, 'price_include': True, 'amount_type': 'percent', 'type_tax_use': 'sale', }) #create a product with the tax self.product = self.env['product.product'].create({ 'name': 'Test Product', 'taxes_id': [(6, 0, [tax.id])], 'list_price': 100, 'available_in_pos': True, }) #create a fiscal position that map the tax to no tax fiscal_position = self.env['account.fiscal.position'].create({ 'name': 'No Tax', 'tax_ids': [(0, 0, { 'tax_src_id': tax.id, 'tax_dest_id': False, })], }) pricelist = self.env['product.pricelist'].create({ 'name': 'Test Pricelist', 'discount_policy': 'without_discount', }) self.main_pos_config.write({ 'tax_regime_selection': True, 'fiscal_position_ids': [(6, 0, [fiscal_position.id])], 'available_pricelist_ids': [(6, 0, [pricelist.id])], 'pricelist_id': pricelist.id, }) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'FiscalPositionNoTax', login="accountman") def test_06_pos_discount_display_with_multiple_pricelist(self): """ Test the discount display on the POS screen when multiple pricelists are used.""" test_product = self.env['product.product'].create({ 'name': 'Test Product', 'available_in_pos': True, 'list_price': 10, }) base_pricelist = self.env['product.pricelist'].create({ 'name': 'base_pricelist', 'discount_policy': 'without_discount', }) self.env['product.pricelist.item'].create({ 'pricelist_id': base_pricelist.id, 'product_tmpl_id': test_product.product_tmpl_id.id, 'compute_price': 'fixed', 'applied_on': '1_product', 'fixed_price': 7, }) special_pricelist = self.env['product.pricelist'].create({ 'name': 'special_pricelist', 'discount_policy': 'without_discount', }) self.env['product.pricelist.item'].create({ 'pricelist_id': special_pricelist.id, 'base': 'pricelist', 'base_pricelist_id': base_pricelist.id, 'compute_price': 'formula', 'applied_on': '3_global', 'price_discount': 10, }) self.main_pos_config.write({ 'pricelist_id': base_pricelist.id, 'available_pricelist_ids': [(6, 0, [base_pricelist.id, special_pricelist.id])], }) self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?config_id=%d" % self.main_pos_config.id, 'ReceiptScreenDiscountWithPricelistTour', login="accountman") def test_07_pos_barcodes_scan(self): barcode_rule = self.env.ref("point_of_sale.barcode_rule_client") barcode_rule.pattern = barcode_rule.pattern + "|234" # should in theory be changed in the JS code to `|^234` # If not, it will fail as it will mistakenly match with the product barcode "0123456789" self.main_pos_config.open_session_cb(check_coa=False) self.start_tour("/pos/ui?debug=1&config_id=%d" % self.main_pos_config.id, 'BarcodeScanningTour', login="accountman")
42.140083
30,383
1,354
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestReportPoSOrder(TestPoSCommon): def setUp(self): super(TestReportPoSOrder, self).setUp() self.config = self.basic_config def test_report_pos_order(self): product1 = self.create_product('Product 1', self.categ_basic, 150) self.open_new_session() session = self.pos_session self.env['pos.order'].create({ 'session_id': session.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': product1.id, 'price_unit': 150, 'discount': 0, 'qty': 1.0, 'price_subtotal': 150, 'price_subtotal_incl': 150, }),], 'amount_total': 150.0, 'amount_tax': 0.0, 'amount_paid': 0.0, 'amount_return': 0.0, }) # PoS Orders have negative IDs to avoid conflict, so reports[0] will correspond to the newest order reports = self.env['report.pos.order'].sudo().search([('product_id', '=', product1.id)], order='id') self.assertEqual(reports[0].margin, 150)
33.02439
1,354
2,447
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestPointOfSale(TransactionCase): def setUp(self): super(TestPointOfSale, self).setUp() # ignore pre-existing pricelists for the purpose of this test self.env["product.pricelist"].search([]).write({"active": False}) self.currency = self.env.ref("base.USD") self.company1 = self.env["res.company"].create({ "name": "company 1", "currency_id": self.currency.id }) self.company2 = self.env["res.company"].create({ "name": "company 2", "currency_id": self.currency.id }) self.company2_pricelist = self.env["product.pricelist"].create({ "name": "company 2 pricelist", "currency_id": self.currency.id, "company_id": self.company2.id, "sequence": 1, # force this pricelist to be first }) self.env.user.company_id = self.company1 def test_default_pricelist_with_company(self): """ Verify that the default pricelist belongs to the same company as the config """ company1_pricelist = self.env["product.pricelist"].create({ "name": "company 1 pricelist", "currency_id": self.currency.id, "company_id": self.company1.id, "sequence": 2, }) # make sure this doesn't pick the company2 pricelist new_config = self.env["pos.config"].create({ "name": "usd config" }) self.assertEqual(new_config.pricelist_id, company1_pricelist, "POS config incorrectly has pricelist %s" % new_config.pricelist_id.display_name) def test_default_pricelist_without_company(self): """ Verify that a default pricelist without a company works """ universal_pricelist = self.env["product.pricelist"].create({ "name": "universal pricelist", "currency_id": self.currency.id, "sequence": 2, }) # make sure this doesn't pick the company2 pricelist new_config = self.env["pos.config"].create({ "name": "usd config" }) self.assertEqual(new_config.pricelist_id, universal_pricelist, "POS config incorrectly has pricelist %s" % new_config.pricelist_id.display_name)
38.84127
2,447
16,746
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo import time from odoo import fields from odoo.tests import common class TestAngloSaxonCommon(common.TransactionCase): def setUp(self): super(TestAngloSaxonCommon, self).setUp() self.PosMakePayment = self.env['pos.make.payment'] self.PosOrder = self.env['pos.order'] self.Statement = self.env['account.bank.statement'] self.company = self.env.ref('base.main_company') self.warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1) self.partner = self.env['res.partner'].create({'name': 'Partner 1'}) self.category = self.env.ref('product.product_category_all') self.category = self.category.copy({'name': 'New category','property_valuation': 'real_time'}) account_type_rcv = self.env.ref('account.data_account_type_receivable') account_type_inc = self.env.ref('account.data_account_type_revenue') account_type_exp = self.env.ref('account.data_account_type_expenses') self.account = self.env['account.account'].create({'name': 'Receivable', 'code': 'RCV00' , 'user_type_id': account_type_rcv.id, 'reconcile': True}) account_expense = self.env['account.account'].create({'name': 'Expense', 'code': 'EXP00' , 'user_type_id': account_type_exp.id, 'reconcile': True}) account_income = self.env['account.account'].create({'name': 'Income', 'code': 'INC00' , 'user_type_id': account_type_inc.id, 'reconcile': True}) account_output = self.env['account.account'].create({'name': 'Output', 'code': 'OUT00' , 'user_type_id': account_type_exp.id, 'reconcile': True}) account_valuation = self.env['account.account'].create({'name': 'Valuation', 'code': 'STV00', 'user_type_id': account_type_exp.id, 'reconcile': True}) self.partner.property_account_receivable_id = self.account self.category.property_account_income_categ_id = account_income self.category.property_account_expense_categ_id = account_expense self.category.property_stock_account_input_categ_id = self.account self.category.property_stock_account_output_categ_id = account_output self.category.property_stock_valuation_account_id = account_valuation self.category.property_stock_journal = self.env['account.journal'].create({'name': 'Stock journal', 'type': 'sale', 'code': 'STK00'}) self.pos_config = self.env.ref('point_of_sale.pos_config_main') self.pos_config = self.pos_config.copy({'name': 'New POS config'}) self.product = self.env['product.product'].create({ 'name': 'New product', 'standard_price': 100, 'available_in_pos': True, 'type': 'product', }) self.company.anglo_saxon_accounting = True self.company.point_of_sale_update_stock_quantities = 'real' self.product.categ_id = self.category self.product.property_account_expense_id = account_expense self.product.property_account_income_id = account_income sale_journal = self.env['account.journal'].create({'name': 'POS journal', 'type': 'sale', 'code': 'POS00'}) self.pos_config.journal_id = sale_journal self.cash_journal = self.env['account.journal'].create({'name': 'CASH journal', 'type': 'cash', 'code': 'CSH00'}) self.sale_journal = self.env['account.journal'].create({'name': 'SALE journal', 'type': 'sale', 'code': 'INV00'}) self.pos_config.invoice_journal_id = self.sale_journal self.cash_payment_method = self.env['pos.payment.method'].create({ 'name': 'Cash Test', 'journal_id': self.cash_journal.id, 'receivable_account_id': self.account.id, }) self.pos_config.write({'payment_method_ids': [(6, 0, self.cash_payment_method.ids)]}) @odoo.tests.tagged('post_install', '-at_install') class TestAngloSaxonFlow(TestAngloSaxonCommon): def test_create_account_move_line(self): # This test will check that the correct journal entries are created when a product in real time valuation # is sold in a company using anglo-saxon self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id self.cash_journal.loss_account_id = self.account current_session.set_cashbox_pos(0, None) # I create a PoS order with 1 unit of New product at 450 EUR self.pos_order_pos0 = self.PosOrder.create({ 'company_id': self.company.id, 'partner_id': self.partner.id, 'pricelist_id': self.company.partner_id.property_product_pricelist.id, 'session_id': self.pos_config.current_session_id.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product.id, 'price_unit': 450, 'discount': 0.0, 'qty': 1.0, 'price_subtotal': 450, 'price_subtotal_incl': 450, })], 'amount_total': 450, 'amount_tax': 0, 'amount_paid': 0, 'amount_return': 0, }) # I make a payment to fully pay the order context_make_payment = {"active_ids": [self.pos_order_pos0.id], "active_id": self.pos_order_pos0.id} self.pos_make_payment_0 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 450.0, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos0.id} self.pos_make_payment_0.with_context(context_payment).check() # I check that the order is marked as paid self.assertEqual(self.pos_order_pos0.state, 'paid', 'Order should be in paid state.') self.assertEqual(self.pos_order_pos0.amount_paid, 450, 'Amount paid for the order should be updated.') # I close the current session to generate the journal entries current_session_id = self.pos_config.current_session_id current_session_id._check_pos_session_balance() current_session_id.post_closing_cash_details(450.0) current_session_id.close_session_from_ui() self.assertEqual(current_session_id.state, 'closed', 'Check that session is closed') # Check if there is account_move in the order. # There shouldn't be because the order is not invoiced. self.assertFalse(self.pos_order_pos0.account_move, 'There should be no invoice in the order.') # I test that the generated journal entries are correct. account_output = self.category.property_stock_account_output_categ_id expense_account = self.category.property_account_expense_categ_id aml = current_session.move_id.line_ids aml_output = aml.filtered(lambda l: l.account_id.id == account_output.id) aml_expense = aml.filtered(lambda l: l.account_id.id == expense_account.id) self.assertEqual(aml_output.credit, self.product.standard_price, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_expense.debit, self.product.standard_price, "Cost of Good Sold entry missing or mismatching") def _prepare_pos_order(self): """ Set the cost method of `self.product` as FIFO. Receive 5@5 and 5@1 and create a `pos.order` record selling 7 units @ 450. """ # check fifo Costing Method of product.category self.product.categ_id.property_cost_method = 'fifo' self.product.standard_price = 5.0 self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product.id, 'inventory_quantity': 5.0, 'location_id': self.warehouse.lot_stock_id.id, }).action_apply_inventory() self.product.standard_price = 1.0 self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product.id, 'inventory_quantity': 10.0, 'location_id': self.warehouse.lot_stock_id.id, }).action_apply_inventory() self.assertEqual(self.product.value_svl, 30, "Value should be (5*5 + 5*1) = 30") self.assertEqual(self.product.quantity_svl, 10) self.pos_config.module_account = True self.pos_config.open_session_cb(check_coa=False) pos_session = self.pos_config.current_session_id pos_session.set_cashbox_pos(0, None) pos_order_values = { 'company_id': self.company.id, 'partner_id': self.partner.id, 'pricelist_id': self.company.partner_id.property_product_pricelist.id, 'session_id': self.pos_config.current_session_id.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product.id, 'price_unit': 450, 'discount': 0.0, 'qty': 7.0, 'price_subtotal': 7 * 450, 'price_subtotal_incl': 7 * 450, })], 'amount_total': 7 * 450, 'amount_tax': 0, 'amount_paid': 0, 'amount_return': 0, } return self.PosOrder.create(pos_order_values) def test_fifo_valuation_no_invoice(self): """Register a payment and validate a session after selling a fifo product without making an invoice for the customer""" pos_order_pos0 = self._prepare_pos_order() context_make_payment = {"active_ids": [pos_order_pos0.id], "active_id": pos_order_pos0.id} self.pos_make_payment_0 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 7 * 450.0, 'payment_method_id': self.cash_payment_method.id, }) # register the payment context_payment = {'active_id': pos_order_pos0.id} self.pos_make_payment_0.with_context(context_payment).check() # validate the session current_session_id = self.pos_config.current_session_id current_session_id.post_closing_cash_details(7 * 450.0) current_session_id.close_session_from_ui() # check the anglo saxon move lines # with uninvoiced orders, the account_move field of pos.order is empty. # the accounting lines are in move_id of pos.session. session_move = pos_order_pos0.session_id.move_id line = session_move.line_ids.filtered(lambda l: l.debit and l.account_id == self.category.property_account_expense_categ_id) self.assertEqual(session_move.journal_id, self.pos_config.journal_id) self.assertEqual(line.debit, 27, 'As it is a fifo product, the move\'s value should be 5*5 + 2*1') def test_fifo_valuation_with_invoice(self): """Register a payment and validate a session after selling a fifo product and make an invoice for the customer""" pos_order_pos0 = self._prepare_pos_order() context_make_payment = {"active_ids": [pos_order_pos0.id], "active_id": pos_order_pos0.id} self.pos_make_payment_0 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 7 * 450.0, 'payment_method_id': self.cash_payment_method.id, }) # register the payment context_payment = {'active_id': pos_order_pos0.id} self.pos_make_payment_0.with_context(context_payment).check() # Create the customer invoice pos_order_pos0.action_pos_order_invoice() # check the anglo saxon move lines line = pos_order_pos0.account_move.line_ids.filtered(lambda l: l.debit and l.account_id == self.category.property_account_expense_categ_id) self.assertEqual(pos_order_pos0.account_move.journal_id, self.pos_config.invoice_journal_id) self.assertEqual(line.debit, 27, 'As it is a fifo product, the move\'s value should be 5*5 + 2*1') def test_cogs_with_ship_later_no_invoicing(self): # This test will check that the correct journal entries are created when a product in real time valuation # is sold using the ship later option and no invoice is created in a company using anglo-saxon self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id self.cash_journal.loss_account_id = self.account current_session.set_cashbox_pos(0, None) # 2 step delivery method self.warehouse.delivery_steps = 'pick_ship' # I create a PoS order with 1 unit of New product at 450 EUR self.pos_order_pos0 = self.PosOrder.create({ 'company_id': self.company.id, 'partner_id': self.partner.id, 'pricelist_id': self.company.partner_id.property_product_pricelist.id, 'session_id': self.pos_config.current_session_id.id, 'to_invoice': False, 'to_ship': True, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product.id, 'price_unit': 450, 'discount': 0.0, 'qty': 1.0, 'price_subtotal': 450, 'price_subtotal_incl': 450, })], 'amount_total': 450, 'amount_tax': 0, 'amount_paid': 0, 'amount_return': 0, }) # I make a payment to fully pay the order context_make_payment = {"active_ids": [self.pos_order_pos0.id], "active_id": self.pos_order_pos0.id} self.pos_make_payment_0 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 450.0, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos0.id} self.pos_make_payment_0.with_context(context_payment).check() # I close the current session to generate the journal entries current_session_id = self.pos_config.current_session_id current_session_id._check_pos_session_balance() current_session_id.post_closing_cash_details(450.0) current_session_id.close_session_from_ui() self.assertEqual(current_session_id.state, 'closed', 'Check that session is closed') self.assertEqual(len(current_session.picking_ids), 2, "There should be 2 pickings") current_session.picking_ids.move_ids_without_package.quantity_done = 1 current_session.picking_ids.button_validate() # I test that the generated journal entries are correct. account_output = self.category.property_stock_account_output_categ_id expense_account = self.category.property_account_expense_categ_id aml = current_session._get_related_account_moves().line_ids aml_output = aml.filtered(lambda l: l.account_id.id == account_output.id) aml_expense = aml.filtered(lambda l: l.account_id.id == expense_account.id) self.assertEqual(len(aml_output), 3, "There should be 3 output account move lines") # 2 moves in POS journal (Pos order + manual entry at delivery) self.assertEqual(aml_output[:2].move_id.journal_id, self.pos_config.journal_id) # 1 move in stock journal (delivery from stock layers) self.assertEqual(aml_output[2].move_id.journal_id, self.category.property_stock_journal) #Check the lines created after the picking validation self.assertEqual(aml_output[0].credit, self.product.standard_price, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_output[0].debit, 0.0, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_output[2].debit, self.product.standard_price, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_output[2].credit, 0.0, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_expense[0].debit, self.product.standard_price, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_expense[0].credit, 0.0, "Cost of Good Sold entry missing or mismatching") #Check the lines created by the PoS session self.assertEqual(aml_output[1].debit, 0.0, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_output[1].credit, 0.0, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_expense[1].credit, 0.0, "Cost of Good Sold entry missing or mismatching") self.assertEqual(aml_expense[1].debit, 0.0, "Cost of Good Sold entry missing or mismatching")
54.72549
16,746
515
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import HttpCase, tagged from odoo import tools @tagged('post_install', '-at_install') class TestUi(HttpCase): # Avoid "A Chart of Accounts is not yet installed in your current company." # Everything is set up correctly even without installed CoA @tools.mute_logger('odoo.http') def test_01_point_of_sale_tour(self): self.start_tour("/web", 'point_of_sale_tour', login="admin")
32.1875
515
882
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.addons.web.tests.test_js import odoo.tests @odoo.tests.tagged("post_install", "-at_install") class WebSuite(odoo.tests.HttpCase): def setUp(self): super().setUp() env = self.env(user=self.env.ref('base.user_admin')) self.main_pos_config = self.main_pos_config = env['pos.config'].create({ 'name': 'Shop', 'barcode_nomenclature_id': env.ref('barcodes.default_barcode_nomenclature').id, }) def test_pos_js(self): # open a session, the /pos/ui controller will redirect to it self.main_pos_config.open_session_cb(check_coa=False) # point_of_sale desktop test suite self.browser_js( "/pos/ui/tests?mod=web&failfast", "", "", login="admin", timeout=1800 )
35.28
882
47,378
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo import tools from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSBasicConfig(TestPoSCommon): """ Test PoS with basic configuration The tests contain base scenarios in using pos. More specialized cases are tested in other tests. """ def setUp(self): super(TestPoSBasicConfig, self).setUp() self.config = self.basic_config self.product0 = self.create_product('Product 0', self.categ_basic, 0.0, 0.0) self.product1 = self.create_product('Product 1', self.categ_basic, 10.0, 5) self.product2 = self.create_product('Product 2', self.categ_basic, 20.0, 10) self.product3 = self.create_product('Product 3', self.categ_basic, 30.0, 15) self.product4 = self.create_product('Product_4', self.categ_basic, 9.96, 4.98) self.product99 = self.create_product('Product_99', self.categ_basic, 99, 50) self.adjust_inventory([self.product1, self.product2, self.product3], [100, 50, 50]) def test_orders_no_invoiced(self): """ Test for orders without invoice 3 orders - first 2 orders with cash payment - last order with bank payment Orders ====== +---------+----------+-----------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +---------+----------+-----------+----------+-----+-------+ | order 1 | cash | no | product1 | 10 | 100 | | | | | product2 | 5 | 100 | +---------+----------+-----------+----------+-----+-------+ | order 2 | cash | no | product2 | 7 | 140 | | | | | product3 | 1 | 30 | +---------+----------+-----------+----------+-----+-------+ | order 3 | bank | no | product1 | 1 | 10 | | | | | product2 | 3 | 60 | | | | | product3 | 5 | 150 | +---------+----------+-----------+----------+-----+-------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale | -590 | | pos receivable cash | 370 | | pos receivable bank | 220 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ start_qty_available = { self.product1: self.product1.qty_available, self.product2: self.product2.qty_available, self.product3: self.product3.qty_available, } def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # check product qty_available after syncing the order self.assertEqual( self.product1.qty_available + 11, start_qty_available[self.product1], ) self.assertEqual( self.product2.qty_available + 15, start_qty_available[self.product2], ) self.assertEqual( self.product3.qty_available + 6, start_qty_available[self.product3], ) # picking and stock moves should be in done state for order in self.pos_session.order_ids: self.assertEqual( order.picking_ids[0].state, 'done', 'Picking should be in done state.' ) move_lines = order.picking_ids[0].move_lines self.assertEqual( move_lines.mapped('state'), ['done'] * len(move_lines), 'Move Lines should be in done state.' ) self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 5)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 7), (self.product3, 1)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 1), (self.product3, 5), (self.product2, 3)], 'payments': [(self.bank_pm1, 220)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 590, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 220, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 370, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((370, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 370, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 370, 'reconciled': True}, ] }), ], 'bank_payments': [ ((220, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 220, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 220, 'reconciled': True}, ] }), ], }, }) def test_orders_with_invoiced(self): """ Test for orders: one with invoice 3 orders - order 1, paid by cash - order 2, paid by bank - order 3, paid by bank, invoiced Orders ====== +---------+----------+---------------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +---------+----------+---------------+----------+-----+-------+ | order 1 | cash | no | product1 | 6 | 60 | | | | | product2 | 3 | 60 | | | | | product3 | 1 | 30 | +---------+----------+---------------+----------+-----+-------+ | order 2 | bank | no | product1 | 1 | 10 | | | | | product2 | 20 | 400 | +---------+----------+---------------+----------+-----+-------+ | order 3 | bank | yes, customer | product1 | 10 | 100 | | | | | product3 | 1 | 30 | +---------+----------+---------------+----------+-----+-------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale | -560 | | pos receivable cash | 150 | | pos receivable bank | 540 | | receivable | -130 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ start_qty_available = { self.product1: self.product1.qty_available, self.product2: self.product2.qty_available, self.product3: self.product3.qty_available, } def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # check product qty_available after syncing the order self.assertEqual( self.product1.qty_available + 17, start_qty_available[self.product1], ) self.assertEqual( self.product2.qty_available + 23, start_qty_available[self.product2], ) self.assertEqual( self.product3.qty_available + 2, start_qty_available[self.product3], ) # picking and stock moves should be in done state # no exception for invoiced orders for order in self.pos_session.order_ids: self.assertEqual( order.picking_ids[0].state, 'done', 'Picking should be in done state.' ) move_lines = order.picking_ids[0].move_lines self.assertEqual( move_lines.mapped('state'), ['done'] * len(move_lines), 'Move Lines should be in done state.' ) # check account move in the invoiced order invoiced_order = self.pos_session.order_ids.filtered(lambda order: order.account_move) self.assertEqual(1, len(invoiced_order), 'Only one order is invoiced in this test.') # check state of orders before validating the session. self.assertEqual('invoiced', invoiced_order.state, msg="state should be 'invoiced' for invoiced orders.") uninvoiced_orders = self.pos_session.order_ids - invoiced_order self.assertTrue( all([order.state == 'paid' for order in uninvoiced_orders]), msg="state should be 'paid' for uninvoiced orders before validating the session." ) def _after_closing_cb(): # check state of orders after validating the session. uninvoiced_orders = self.pos_session.order_ids.filtered(lambda order: not order.is_invoiced) self.assertTrue( all([order.state == 'done' for order in uninvoiced_orders]), msg="State should be 'done' for uninvoiced orders after validating the session." ) self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 6), (self.product2, 3), (self.product3, 1), ], 'payments': [(self.cash_pm1, 150)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 1), (self.product2, 20), ], 'payments': [(self.bank_pm1, 410)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 10), (self.product3, 1), ], 'payments': [(self.bank_pm1, 130)], 'is_invoiced': True, 'customer': self.customer, 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '00100-010-0003': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 30, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 130, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 130), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 130, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 130, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'after_closing_cb': _after_closing_cb, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 560, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 540, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 150, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 130, 'reconciled': True}, ], }, 'cash_statement': [ ((150, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 150, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 150, 'reconciled': True}, ] }), ], 'bank_payments': [ ((540, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 540, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 540, 'reconciled': True}, ] }), ], }, }) def test_orders_with_zero_valued_invoiced(self): """One invoiced order but with zero receivable line balance.""" self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product0, 1)], 'payments': [(self.bank_pm1, 0)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 0, 'reconciled': False}, ] }, 'payments': [ ((self.bank_pm1, 0), False), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': False, 'cash_statement': [], 'bank_payments': [], }, }) def test_return_order_invoiced(self): def _before_closing_cb(): order = self.pos_session.order_ids.filtered(lambda order: '666-666-666' in order.pos_reference) # refund order.refund() refund_order = self.pos_session.order_ids.filtered(lambda order: order.state == 'draft') # pay the refund context_make_payment = {"active_ids": [refund_order.id], "active_id": refund_order.id} make_payment = self.env['pos.make.payment'].with_context(context_make_payment).create({ 'payment_method_id': self.cash_pm1.id, 'amount': -100, }) make_payment.check() # invoice refund refund_order.action_pos_order_invoice() self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments': [(self.cash_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '666-666-666'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '666-666-666': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [], }, }) def test_return_order(self): """ Test return order 2 orders - 2nd order is returned Orders ====== +------------------+----------+-----------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +------------------+----------+-----------+----------+-----+-------+ | order 1 | bank | no | product1 | 1 | 10 | | | | | product2 | 5 | 100 | +------------------+----------+-----------+----------+-----+-------+ | order 2 | cash | no | product1 | 3 | 30 | | | | | product2 | 2 | 40 | | | | | product3 | 1 | 30 | +------------------+----------+-----------+----------+-----+-------+ | order 3 (return) | cash | no | product1 | -3 | -30 | | | | | product2 | -2 | -40 | | | | | product3 | -1 | -30 | +------------------+----------+-----------+----------+-----+-------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale (sales) | -210 | | sale (refund) | 100 | | pos receivable bank | 110 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ start_qty_available = { self.product1: self.product1.qty_available, self.product2: self.product2.qty_available, self.product3: self.product3.qty_available, } def _before_closing_cb(): # check values before closing the session self.assertEqual(2, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # return order order_to_return = self.pos_session.order_ids.filtered(lambda order: '12345-123-1234' in order.pos_reference) order_to_return.refund() refund_order = self.pos_session.order_ids.filtered(lambda order: order.state == 'draft') # check if amount to pay self.assertAlmostEqual(refund_order.amount_total - refund_order.amount_paid, -100) # pay the refund context_make_payment = {"active_ids": [refund_order.id], "active_id": refund_order.id} make_payment = self.env['pos.make.payment'].with_context(context_make_payment).create({ 'payment_method_id': self.cash_pm1.id, 'amount': -100, }) make_payment.check() self.assertEqual(refund_order.state, 'paid', 'Payment is registered, order should be paid.') self.assertAlmostEqual(refund_order.amount_paid, -100.0, msg='Amount paid for return order should be negative.') # check product qty_available after syncing the order self.assertEqual( self.product1.qty_available + 1, start_qty_available[self.product1], ) self.assertEqual( self.product2.qty_available + 5, start_qty_available[self.product2], ) self.assertEqual( self.product3.qty_available, start_qty_available[self.product3], ) # picking and stock moves should be in done state # no exception of return orders for order in self.pos_session.order_ids: self.assertEqual( order.picking_ids[0].state, 'done', 'Picking should be in done state.' ) move_lines = order.picking_ids[0].move_lines self.assertEqual( move_lines.mapped('state'), ['done'] * len(move_lines), 'Move Lines should be in done state.' ) self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 1), (self.product2, 5)], 'payments': [(self.bank_pm1, 110)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 3), (self.product2, 2), (self.product3, 1)], 'payments': [(self.cash_pm1, 100)], 'uid': '12345-123-1234'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 210, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 110, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((110, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 110, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 110, 'reconciled': True}, ] }), ], }, }) def test_split_cash_payments(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 5)], 'payments': [(self.cash_split_pm1, 100), (self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 7), (self.product3, 1)], 'payments': [(self.cash_split_pm1, 70), (self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 1), (self.product3, 5), (self.product2, 3)], 'payments': [(self.cash_split_pm1, 120), (self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0003'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 590, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 300, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 70, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 120, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }), ((70, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 70, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 70, 'reconciled': True}, ] }), ((120, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 120, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 120, 'reconciled': True}, ] }), ], 'bank_payments': [ ((300, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 300, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 300, 'reconciled': True}, ] }) ], }, }) def test_rounding_method(self): # set the cash rounding method self.config.cash_rounding = True self.config.rounding_method = self.env['account.cash.rounding'].create({ 'name': 'add_invoice_line', 'rounding': 0.05, 'strategy': 'add_invoice_line', 'profit_account_id': self.company['default_cash_difference_income_account_id'].copy().id, 'loss_account_id': self.company['default_cash_difference_expense_account_id'].copy().id, 'rounding_method': 'HALF-UP', }) self.open_new_session() """ Test for orders: one with invoice 3 orders - order 1, paid by cash - order 2, paid by bank - order 3, paid by bank, invoiced Orders ====== +---------+----------+---------------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +---------+----------+---------------+----------+-----+-------+ | order 1 | bank | no | product1 | 6 | 60 | | | | | product4 | 4 | 39.84 | +---------+----------+---------------+----------+-----+-------+ | order 2 | bank | yes | product4 | 3 | 29.88 | | | | | product2 | 20 | 400 | +---------+----------+---------------+----------+-----+-------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale | -596,56 | | pos receivable bank | 516,64 | | Rounding applied | -0,01 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ # create orders orders = [] # create orders orders = [] orders.append(self.create_ui_order_data( [(self.product4, 3), (self.product2, 20)], payments=[(self.bank_pm1, 429.90)] )) orders.append(self.create_ui_order_data( [(self.product1, 6), (self.product4, 4)], payments=[(self.bank_pm1, 99.85)] )) # sync orders order = self.env['pos.order'].create_from_ui(orders) self.assertEqual(orders[0]['data']['amount_return'], 0, msg='The amount return should be 0') self.assertEqual(orders[1]['data']['amount_return'], 0, msg='The amount return should be 0') # close the session self.pos_session.action_pos_session_validate() # check values after the session is closed session_account_move = self.pos_session.move_id rounding_line = session_account_move.line_ids.filtered(lambda line: line.name == 'Rounding line') self.assertAlmostEqual(rounding_line.credit, 0.03, msg='The credit should be equals to 0.03') def test_correct_partner_on_invoice_receivables(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.cash_split_pm1 | self.bank_pm1 | self.bank_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.cash_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.cash_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0003'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0004'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.cash_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0005'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0006'}, {'pos_order_lines_ui_args': [(self.product99, 1)], 'payments':[(self.cash_split_pm1, 99)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0007'}, {'pos_order_lines_ui_args': [(self.product99, 1)], 'payments':[(self.bank_split_pm1, 99)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0008'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_pm1, 100)], 'customer': self.other_customer, 'is_invoiced': True, 'uid': '00100-010-0009'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_pm1, 100)], 'customer': self.other_customer, 'is_invoiced': True, 'uid': '00100-010-0010'}, {'pos_order_lines_ui_args': [(self.product1, 10)], 'payments':[(self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0011'}, ], 'journal_entries_before_closing': { '00100-010-0001': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0002': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0003': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_split_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0004': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_split_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0009': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 100), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0010': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 100), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0011': { 'invoice': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 100), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 398, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 500, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 99, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 99, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 400, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }), ((99, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 99, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 99, 'reconciled': True}, ] }), ((200, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }), ], 'bank_payments': [ ((100, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }), ((99, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 99, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 99, 'reconciled': True}, ] }), ((500, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 500, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 500, 'reconciled': True}, ] }), ], }, }) def test_cash_register_if_no_order(self): # Process one order with product3 self.open_new_session(0) session = self.pos_session order_data = self.create_ui_order_data([(self.product3, 1)]) amount_paid = order_data['data']['amount_paid'] self.env['pos.order'].create_from_ui([order_data]) session.post_closing_cash_details(amount_paid) session.close_session_from_ui() cash_register = session.cash_register_id self.assertEqual(cash_register.balance_start, 0) self.assertEqual(cash_register.balance_end_real, amount_paid) # Open/Close session without any order in cash control self.open_new_session(amount_paid) session = self.pos_session session.post_closing_cash_details(amount_paid) session.close_session_from_ui() cash_register = session.cash_register_id self.assertEqual(cash_register.balance_start, amount_paid) self.assertEqual(cash_register.balance_end_real, amount_paid) self.assertEqual(self.config.last_session_closing_cash, amount_paid) def test_start_balance_with_two_pos(self): """ When having several POS with cash control, this tests ensures that each POS has its correct opening amount """ def open_and_check(pos_data): self.config = pos_data['config'] self.open_new_session() session = self.pos_session session.set_cashbox_pos(pos_data['amount_paid'], False) self.assertEqual(session.cash_register_id.balance_start, pos_data['amount_paid']) pos01_config = self.config pos02_config = pos01_config.copy() pos01_data = {'config': pos01_config, 'p_qty': 1, 'amount_paid': 0} pos02_data = {'config': pos02_config, 'p_qty': 3, 'amount_paid': 0} for pos_data in [pos01_data, pos02_data]: open_and_check(pos_data) session = self.pos_session order_data = self.create_ui_order_data([(self.product3, pos_data['p_qty'])]) pos_data['amount_paid'] += order_data['data']['amount_paid'] self.env['pos.order'].create_from_ui([order_data]) session.post_closing_cash_details(pos_data['amount_paid']) session.close_session_from_ui() open_and_check(pos01_data) open_and_check(pos02_data)
54.835648
47,378
18,286
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo import tools from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSMultipleReceivableAccounts(TestPoSCommon): """ Test for invoiced orders with customers having receivable account different from default Thus, for this test, there are two receivable accounts involved and are set in the customers. self.customer -> self.receivable_account self.other_customer -> self.other_receivable_account ADDITIONALLY, this tests different sales account on the products. NOTE That both receivable accounts above are different from the pos receivable account. """ def setUp(self): super(TestPoSMultipleReceivableAccounts, self).setUp() self.config = self.basic_config self.product1 = self.create_product( 'Product 1', self.categ_basic, lst_price=10.99, standard_price=5.0, tax_ids=self.taxes['tax7'].ids, ) self.product2 = self.create_product( 'Product 2', self.categ_basic, lst_price=19.99, standard_price=10.0, tax_ids=self.taxes['tax10'].ids, sale_account=self.other_sale_account, ) self.product3 = self.create_product( 'Product 3', self.categ_basic, lst_price=30.99, standard_price=15.0, tax_ids=self.taxes['tax_group_7_10'].ids, ) self.adjust_inventory([self.product1, self.product2, self.product3], [100, 50, 50]) def test_01_invoiced_order_from_other_customer(self): """ Orders ====== +---------+----------+-----------+----------+-----+---------+--------------------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+-----------+----------+-----+---------+--------------------------+--------+ | order 1 | cash | no | product1 | 10 | 109.9 | 7.69 [7%] | 117.59 | | | | | product2 | 10 | 181.73 | 18.17 [10%] | 199.9 | | | | | product3 | 10 | 281.73 | 19.72 [7%] + 28.17 [10%] | 329.62 | +---------+----------+-----------+----------+-----+---------+--------------------------+--------+ | order 2 | bank | no | product1 | 5 | 54.95 | 3.85 [7%] | 58.80 | | | | | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | +---------+----------+-----------+----------+-----+---------+--------------------------+--------+ | order 3 | bank | yes | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | | | | | product3 | 5 | 140.86 | 9.86 [7%] + 14.09 [10%] | 164.81 | +---------+----------+-----------+----------+-----+---------+--------------------------+--------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale_account | -164.85 | | sale_account | -281.73 | | other_sale_account | -272.59 | | tax 7% | -31.26 | | tax 10% | -55.43 | | pos receivable cash | 647.11 | | pos receivable bank | 423.51 | | other receivable | -264.76 | +---------------------+---------+ | Total balance | 0.00 | +---------------------+---------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # check if there is one invoiced order self.assertEqual(len(self.pos_session.order_ids.filtered(lambda order: order.state == 'invoiced')), 1, 'There should only be one invoiced order.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'payments': [(self.bank_pm1, 158.75)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm1, 264.76)], 'is_invoiced': True, 'customer': self.other_customer, 'uid': '09876-098-0987'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '09876-098-0987': { 'invoice': { 'line_ids_predicate': lambda line: line.account_id in self.other_sale_account | self.sales_account | self.other_receivable_account, 'line_ids': [ {'account_id': self.other_sale_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 140.86, 'reconciled': False}, {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 264.76, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 264.76), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 264.76, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 264.76, 'credit': 0, 'reconciled': False}, ] }), ], } }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 31.26, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 55.43, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 164.85, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 272.59, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 281.73, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 423.51, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 647.11, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 264.76, 'reconciled': True}, ], }, 'cash_statement': [ ((647.11, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 647.11, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 647.11, 'reconciled': True}, ] }), ], 'bank_payments': [ ((423.51, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 423.51, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 423.51, 'reconciled': True}, ] }), ], }, }) def test_02_all_orders_invoiced_mixed_customers(self): """ Orders ====== +---------+----------+---------------------+----------+-----+---------+--------------------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+---------------------+----------+-----+---------+--------------------------+--------+ | order 1 | cash | yes, other_customer | product1 | 10 | 109.90 | 7.69 [7%] | 117.59 | | | | | product2 | 10 | 181.73 | 18.17 [10%] | 199.90 | | | | | product3 | 10 | 281.73 | 19.72 [7%] + 28.17 [10%] | 329.62 | +---------+----------+---------------------+----------+-----+---------+--------------------------+--------+ | order 2 | bank | yes, customer | product1 | 5 | 54.95 | 3.85 [7%] | 58.80 | | | | | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | +---------+----------+---------------------+----------+-----+---------+--------------------------+--------+ | order 3 | bank | yes, other customer | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | | | | | product3 | 5 | 140.86 | 9.86 [7%] + 14.09 [10%] | 164.81 | +---------+----------+---------------------+----------+-----+---------+--------------------------+--------+ Expected Result =============== +----------------------+---------+ | account | balance | +----------------------+---------+ | pos receivable cash | 647.11 | | pos receivable bank | 423.51 | | received bank | -423.51 | | received cash | -647.11 | +----------------------+---------+ | Total balance | 0.00 | +----------------------+---------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # check if there is one invoiced order self.assertEqual(len(self.pos_session.order_ids.filtered(lambda order: order.state == 'invoiced')), 3, 'All orders should be invoiced.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'is_invoiced': True, 'customer': self.other_customer, 'uid': '09876-098-0987'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'payments': [(self.bank_pm1, 158.75)], 'is_invoiced': True, 'customer': self.customer, 'uid': '09876-098-0988'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm1, 264.76)], 'is_invoiced': True, 'customer': self.other_customer, 'uid': '09876-098-0989'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '09876-098-0987': { 'invoice': { 'line_ids_predicate': lambda line: line.account_id in self.other_sale_account | self.sales_account | self.other_receivable_account, 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 109.90, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 181.73, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 281.73, 'reconciled': False}, {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 647.11, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.cash_pm1, 647.11), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 647.11, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 647.11, 'credit': 0, 'reconciled': False}, ] }), ], }, '09876-098-0988': { 'invoice': { 'line_ids_predicate': lambda line: line.account_id in self.other_sale_account | self.sales_account | self.c1_receivable, 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 54.95, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 158.75, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 158.75), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 158.75, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 158.75, 'credit': 0, 'reconciled': False}, ] }), ], }, '09876-098-0989': { 'invoice': { 'line_ids_predicate': lambda line: line.account_id in self.other_sale_account | self.sales_account | self.other_receivable_account, 'line_ids': [ {'account_id': self.other_sale_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 140.86, 'reconciled': False}, {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 264.76, 'credit': 0, 'reconciled': True}, ] }, 'payments': [ ((self.bank_pm1, 264.76), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 264.76, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 264.76, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 423.51, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 647.11, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 647.11, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 423.51, 'reconciled': True}, ], }, 'cash_statement': [ ((647.11, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 647.11, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 647.11, 'reconciled': True}, ] }), ], 'bank_payments': [ ((423.51, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 423.51, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 423.51, 'reconciled': True}, ] }), ], }, })
63.493056
18,286
3,540
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSSetup(TestPoSCommon): """ This group of tests is for sanity check in setting up global records which will be used in each testing. If a test fails here, then it means there are inconsistencies in what we expect in the setup. """ def setUp(self): super(TestPoSSetup, self).setUp() self.config = self.basic_config self.products = [ self.create_product('Product 1', self.categ_basic, lst_price=10.0, standard_price=5), self.create_product('Product 2', self.categ_basic, lst_price=20.0, standard_price=10), self.create_product('Product 3', self.categ_basic, lst_price=30.0, standard_price=15), ] def test_basic_config_values(self): config = self.basic_config self.assertEqual(config.currency_id, self.company_currency) self.assertEqual(config.pricelist_id.currency_id, self.company_currency) def test_other_currency_config_values(self): config = self.other_currency_config self.assertEqual(config.currency_id, self.other_currency) self.assertEqual(config.pricelist_id.currency_id, self.other_currency) def test_product_categories(self): # check basic product category # it is expected to have standard and manual_periodic valuation self.assertEqual(self.categ_basic.property_cost_method, 'standard') self.assertEqual(self.categ_basic.property_valuation, 'manual_periodic') # check anglo saxon product category # this product categ is expected to have fifo and real_time valuation self.assertEqual(self.categ_anglo.property_cost_method, 'fifo') self.assertEqual(self.categ_anglo.property_valuation, 'real_time') def test_product_price(self): def get_price(pricelist, product): return pricelist.get_product_price(product, 1, self.customer) # check usd pricelist pricelist = self.basic_config.pricelist_id for product in self.products: self.assertAlmostEqual(get_price(pricelist, product), product.lst_price) # check eur pricelist # exchange rate to the other currency is set to 0.5, thus, lst_price # is expected to have half its original value. pricelist = self.other_currency_config.pricelist_id for product in self.products: self.assertAlmostEqual(get_price(pricelist, product), product.lst_price * 0.5) def test_taxes(self): tax7 = self.taxes['tax7'] self.assertEqual(tax7.name, 'Tax 7%') self.assertAlmostEqual(tax7.amount, 7) self.assertEqual(tax7.invoice_repartition_line_ids.mapped('account_id').id, self.tax_received_account.id) tax10 = self.taxes['tax10'] self.assertEqual(tax10.name, 'Tax 10%') self.assertAlmostEqual(tax10.amount, 10) self.assertEqual(tax10.price_include, True) self.assertEqual(tax10.invoice_repartition_line_ids.mapped('account_id').id, self.tax_received_account.id) tax_group_7_10 = self.taxes['tax_group_7_10'] self.assertEqual(tax_group_7_10.name, 'Tax 7+10%') self.assertEqual(tax_group_7_10.amount_type, 'group') self.assertEqual(sorted(tax_group_7_10.children_tax_ids.ids), sorted((tax7 | tax10).ids))
46.578947
3,540
33,500
py
PYTHON
15.0
# -*- coding: utf-8 -*- from random import randint from datetime import datetime from odoo import fields, tools from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon from odoo.tests.common import Form from odoo.tests import tagged import logging _logger = logging.getLogger(__name__) @tagged('post_install', '-at_install') class TestPointOfSaleCommon(ValuationReconciliationTestCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company_data['company'].write({ 'point_of_sale_update_stock_quantities': 'real', }) cls.AccountBankStatement = cls.env['account.bank.statement'] cls.AccountBankStatementLine = cls.env['account.bank.statement.line'] cls.PosMakePayment = cls.env['pos.make.payment'] cls.PosOrder = cls.env['pos.order'] cls.PosSession = cls.env['pos.session'] cls.company = cls.company_data['company'] cls.product3 = cls.env['product.product'].create({ 'name': 'Product 3', 'list_price': 450, }) cls.product4 = cls.env['product.product'].create({ 'name': 'Product 4', 'list_price': 750, }) cls.partner1 = cls.env['res.partner'].create({'name': 'Partner 1'}) cls.partner4 = cls.env['res.partner'].create({'name': 'Partner 4'}) cls.pos_config = cls.env['pos.config'].create({ 'name': 'Main', 'journal_id': cls.company_data['default_journal_sale'].id, 'invoice_journal_id': cls.company_data['default_journal_sale'].id, }) cls.led_lamp = cls.env['product.product'].create({ 'name': 'LED Lamp', 'available_in_pos': True, 'list_price': 0.90, }) cls.whiteboard_pen = cls.env['product.product'].create({ 'name': 'Whiteboard Pen', 'available_in_pos': True, 'list_price': 1.20, }) cls.newspaper_rack = cls.env['product.product'].create({ 'name': 'Newspaper Rack', 'available_in_pos': True, 'list_price': 1.28, }) cls.cash_payment_method = cls.env['pos.payment.method'].create({ 'name': 'Cash', 'receivable_account_id': cls.company_data['default_account_receivable'].id, 'journal_id': cls.company_data['default_journal_cash'].id, 'company_id': cls.env.company.id, }) cls.bank_payment_method = cls.env['pos.payment.method'].create({ 'name': 'Bank', 'journal_id': cls.company_data['default_journal_bank'].id, 'receivable_account_id': cls.company_data['default_account_receivable'].id, 'company_id': cls.env.company.id, }) cls.credit_payment_method = cls.env['pos.payment.method'].create({ 'name': 'Credit', 'receivable_account_id': cls.company_data['default_account_receivable'].id, 'split_transactions': True, 'company_id': cls.env.company.id, }) cls.pos_config.write({'payment_method_ids': [(4, cls.credit_payment_method.id), (4, cls.bank_payment_method.id), (4, cls.cash_payment_method.id)]}) # Create POS journal cls.pos_config.journal_id = cls.env['account.journal'].create({ 'type': 'general', 'name': 'Point of Sale - Test', 'code': 'POSS - Test', 'company_id': cls.env.company.id, 'sequence': 20 }) # create a VAT tax of 10%, included in the public price Tax = cls.env['account.tax'] account_tax_10_incl = Tax.create({ 'name': 'VAT 10 perc Incl', 'amount_type': 'percent', 'amount': 10.0, 'price_include': True, }) # assign this 10 percent tax on the [PCSC234] PC Assemble SC234 product # as a sale tax cls.product3.taxes_id = [(6, 0, [account_tax_10_incl.id])] # create a VAT tax of 5%, which is added to the public price account_tax_05_incl = Tax.create({ 'name': 'VAT 5 perc Incl', 'amount_type': 'percent', 'amount': 5.0, 'price_include': False, }) # create a second VAT tax of 5% but this time for a child company, to # ensure that only product taxes of the current session's company are considered #(this tax should be ignore when computing order's taxes in following tests) account_tax_05_incl_chicago = Tax.create({ 'name': 'VAT 05 perc Excl (US)', 'amount_type': 'percent', 'amount': 5.0, 'price_include': False, 'company_id': cls.company_data_2['company'].id, }) cls.product4.company_id = False # I assign those 5 percent taxes on the PCSC349 product as a sale taxes cls.product4.write( {'taxes_id': [(6, 0, [account_tax_05_incl.id, account_tax_05_incl_chicago.id])]}) # Set account_id in the generated repartition lines. Automatically, nothing is set. invoice_rep_lines = (account_tax_05_incl | account_tax_10_incl).mapped('invoice_repartition_line_ids') refund_rep_lines = (account_tax_05_incl | account_tax_10_incl).mapped('refund_repartition_line_ids') # Expense account, should just be something else than receivable/payable (invoice_rep_lines | refund_rep_lines).write({'account_id': cls.company_data['default_account_tax_sale'].id}) @tagged('post_install', '-at_install') class TestPoSCommon(ValuationReconciliationTestCommon): """ Set common values for different special test cases. The idea is to set up common values here for the tests and implement different special scenarios by inheriting this class. """ @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company_data['company'].write({ 'point_of_sale_update_stock_quantities': 'real', 'country_id': cls.env['res.country'].create({ 'name': 'PoS Land', 'code': 'WOW', }), }) # Set basic defaults cls.company = cls.company_data['company'] cls.pos_sale_journal = cls.env['account.journal'].create({ 'type': 'general', 'name': 'Point of Sale Test', 'code': 'POSS', 'company_id': cls.company.id, 'sequence': 20 }) cls.sales_account = cls.company_data['default_account_revenue'] cls.invoice_journal = cls.company_data['default_journal_sale'] cls.receivable_account = cls.company_data['default_account_receivable'] cls.tax_received_account = cls.company_data['default_account_tax_sale'] cls.company.account_default_pos_receivable_account_id = cls.env['account.account'].create({ 'code': 'X1012 - POS', 'name': 'Debtors - (POS)', 'reconcile': True, 'user_type_id': cls.env.ref('account.data_account_type_receivable').id, }) cls.pos_receivable_account = cls.company.account_default_pos_receivable_account_id cls.pos_receivable_cash = cls.copy_account(cls.company.account_default_pos_receivable_account_id, {'name': 'POS Receivable Cash'}) cls.pos_receivable_bank = cls.copy_account(cls.company.account_default_pos_receivable_account_id, {'name': 'POS Receivable Bank'}) cls.outstanding_bank = cls.copy_account(cls.company.account_journal_payment_debit_account_id, {'name': 'Outstanding Bank'}) cls.c1_receivable = cls.copy_account(cls.receivable_account, {'name': 'Customer 1 Receivable'}) cls.other_receivable_account = cls.env['account.account'].create({ 'name': 'Other Receivable', 'code': 'RCV00' , 'user_type_id': cls.env['account.account.type'].create({'name': 'RCV type', 'type': 'receivable', 'internal_group': 'asset'}).id, 'internal_group': 'asset', 'reconcile': True, }) # company_currency can be different from `base.USD` depending on the localization installed cls.company_currency = cls.company.currency_id # other_currency is a currency different from the company_currency # sometimes company_currency is different from USD, so handle appropriately. cls.other_currency = cls.currency_data['currency'] cls.currency_pricelist = cls.env['product.pricelist'].create({ 'name': 'Public Pricelist', 'currency_id': cls.company_currency.id, }) # Set Point of Sale configurations # basic_config # - derived from 'point_of_sale.pos_config_main' with added invoice_journal_id and credit payment method. # other_currency_config # - pos.config set to have currency different from company currency. cls.basic_config = cls._create_basic_config() cls.other_currency_config = cls._create_other_currency_config() # Set product categories # categ_basic # - just the plain 'product.product_category_all' # categ_anglo # - product category with fifo and real_time valuations # - used for checking anglo saxon accounting behavior cls.categ_basic = cls.env.ref('product.product_category_all') cls.env.company.anglo_saxon_accounting = True cls.categ_anglo = cls._create_categ_anglo() # other basics cls.sale_account = cls.categ_basic.property_account_income_categ_id cls.other_sale_account = cls.env['account.account'].search([ ('company_id', '=', cls.company.id), ('user_type_id', '=', cls.env.ref('account.data_account_type_revenue').id), ('id', '!=', cls.sale_account.id) ], limit=1) # Set customers cls.customer = cls.env['res.partner'].create({'name': 'Customer 1', 'property_account_receivable_id': cls.c1_receivable.id}) cls.other_customer = cls.env['res.partner'].create({'name': 'Other Customer', 'property_account_receivable_id': cls.other_receivable_account.id}) # Set taxes # cls.taxes => dict # keys: 'tax7', 'tax10'(price_include=True), 'tax_group_7_10' cls.taxes = cls._create_taxes() cls.stock_location_components = cls.env["stock.location"].create({ 'name': 'Shelf 1', 'location_id': cls.company_data['default_warehouse'].lot_stock_id.id, }) ##################### ## private methods ## ##################### @classmethod def _create_basic_config(cls): new_config = Form(cls.env['pos.config']) new_config.name = 'PoS Shop Test' new_config.module_account = True new_config.invoice_journal_id = cls.invoice_journal new_config.journal_id = cls.pos_sale_journal new_config.available_pricelist_ids.clear() new_config.available_pricelist_ids.add(cls.currency_pricelist) new_config.pricelist_id = cls.currency_pricelist config = new_config.save() cls.cash_pm1 = cls.env['pos.payment.method'].create({ 'name': 'Cash', 'journal_id': cls.company_data['default_journal_cash'].id, 'receivable_account_id': cls.pos_receivable_cash.id, 'company_id': cls.env.company.id, }) cls.bank_pm1 = cls.env['pos.payment.method'].create({ 'name': 'Bank', 'journal_id': cls.company_data['default_journal_bank'].id, 'receivable_account_id': cls.pos_receivable_bank.id, 'outstanding_account_id': cls.outstanding_bank.id, 'company_id': cls.env.company.id, }) cls.cash_split_pm1 = cls.cash_pm1.copy(default={ 'name': 'Split (Cash) PM', 'split_transactions': True, }) cls.bank_split_pm1 = cls.bank_pm1.copy(default={ 'name': 'Split (Bank) PM', 'split_transactions': True, }) cls.pay_later_pm = cls.env['pos.payment.method'].create({'name': 'Pay Later', 'split_transactions': True}) config.write({'payment_method_ids': [(4, cls.cash_split_pm1.id), (4, cls.bank_split_pm1.id), (4, cls.cash_pm1.id), (4, cls.bank_pm1.id), (4, cls.pay_later_pm.id)]}) return config @classmethod def _create_other_currency_config(cls): (cls.other_currency.rate_ids | cls.company_currency.rate_ids).unlink() cls.env['res.currency.rate'].create({ 'rate': 0.5, 'currency_id': cls.other_currency.id, 'name': datetime.today().date(), }) other_cash_journal = cls.env['account.journal'].create({ 'name': 'Cash Other', 'type': 'cash', 'company_id': cls.company.id, 'code': 'CSHO', 'sequence': 10, 'currency_id': cls.other_currency.id }) other_invoice_journal = cls.env['account.journal'].create({ 'name': 'Customer Invoice Other', 'type': 'sale', 'company_id': cls.company.id, 'code': 'INVO', 'sequence': 11, 'currency_id': cls.other_currency.id }) other_sales_journal = cls.env['account.journal'].create({ 'name':'PoS Sale Other', 'type': 'sale', 'code': 'POSO', 'company_id': cls.company.id, 'sequence': 12, 'currency_id': cls.other_currency.id }) other_bank_journal = cls.env['account.journal'].create({ 'name': 'Bank Other', 'type': 'bank', 'company_id': cls.company.id, 'code': 'BNKO', 'sequence': 13, 'currency_id': cls.other_currency.id }) other_pricelist = cls.env['product.pricelist'].create({ 'name': 'Public Pricelist Other', 'currency_id': cls.other_currency.id, }) cls.cash_pm2 = cls.env['pos.payment.method'].create({ 'name': 'Cash Other', 'journal_id': other_cash_journal.id, 'receivable_account_id': cls.pos_receivable_cash.id, }) cls.bank_pm2 = cls.env['pos.payment.method'].create({ 'name': 'Bank Other', 'journal_id': other_bank_journal.id, 'receivable_account_id': cls.pos_receivable_bank.id, 'outstanding_account_id': cls.outstanding_bank.id, }) new_config = Form(cls.env['pos.config']) new_config.name = 'Shop Other' new_config.invoice_journal_id = other_invoice_journal new_config.journal_id = other_sales_journal new_config.use_pricelist = True new_config.available_pricelist_ids.clear() new_config.available_pricelist_ids.add(other_pricelist) new_config.pricelist_id = other_pricelist new_config.payment_method_ids.clear() new_config.payment_method_ids.add(cls.cash_pm2) new_config.payment_method_ids.add(cls.bank_pm2) config = new_config.save() return config @classmethod def _create_categ_anglo(cls): return cls.env['product.category'].create({ 'name': 'Anglo', 'parent_id': False, 'property_cost_method': 'fifo', 'property_valuation': 'real_time', 'property_stock_account_input_categ_id': cls.company_data['default_account_stock_in'].id, 'property_stock_account_output_categ_id': cls.company_data['default_account_stock_out'].id, }) @classmethod def _create_taxes(cls): """ Create taxes tax7: 7%, excluded in product price tax10: 10%, included in product price tax21: 21%, included in product price """ def create_tag(name): return cls.env['account.account.tag'].create({ 'name': name, 'applicability': 'taxes', 'country_id': cls.env.company.country_id.id }) cls.tax_tag_invoice_base = create_tag('Invoice Base tag') cls.tax_tag_invoice_tax = create_tag('Invoice Tax tag') cls.tax_tag_refund_base = create_tag('Refund Base tag') cls.tax_tag_refund_tax = create_tag('Refund Tax tag') def create_tax(percentage, price_include=False): return cls.env['account.tax'].create({ 'name': f'Tax {percentage}%', 'amount': percentage, 'price_include': price_include, 'amount_type': 'percent', 'include_base_amount': False, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tag_invoice_base.ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_received_account.id, 'tag_ids': [(6, 0, cls.tax_tag_invoice_tax.ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tag_refund_base.ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_received_account.id, 'tag_ids': [(6, 0, cls.tax_tag_refund_tax.ids)], }), ], }) def create_tax_fixed(amount, price_include=False): return cls.env['account.tax'].create({ 'name': f'Tax fixed amount {amount}', 'amount': amount, 'price_include': price_include, 'include_base_amount': price_include, 'amount_type': 'fixed', 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tag_invoice_base.ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_received_account.id, 'tag_ids': [(6, 0, cls.tax_tag_invoice_tax.ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tag_refund_base.ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_received_account.id, 'tag_ids': [(6, 0, cls.tax_tag_refund_tax.ids)], }), ], }) tax_fixed006 = create_tax_fixed(0.06, price_include=True) tax_fixed012 = create_tax_fixed(0.12, price_include=True) tax7 = create_tax(7, price_include=False) tax10 = create_tax(10, price_include=True) tax21 = create_tax(21, price_include=True) tax_group_7_10 = tax7.copy() with Form(tax_group_7_10) as tax: tax.name = 'Tax 7+10%' tax.amount_type = 'group' tax.children_tax_ids.add(tax7) tax.children_tax_ids.add(tax10) return { 'tax7': tax7, 'tax10': tax10, 'tax21': tax21, 'tax_fixed006': tax_fixed006, 'tax_fixed012': tax_fixed012, 'tax_group_7_10': tax_group_7_10 } #################### ## public methods ## #################### def create_random_uid(self): return ('%05d-%03d-%04d' % (randint(1, 99999), randint(1, 999), randint(1, 9999))) def create_ui_order_data(self, pos_order_lines_ui_args, customer=False, is_invoiced=False, payments=None, uid=None): """ Mocks the order_data generated by the pos ui. This is useful in making orders in an open pos session without making tours. Its functionality is tested in test_pos_create_ui_order_data.py. Before use, make sure that self is set with: 1. pricelist -> the pricelist of the current session 2. currency -> currency of the current session 3. pos_session -> the current session, equivalent to config.current_session_id 4. cash_pm -> first cash payment method in the current session 5. config -> the active pos.config The above values should be set when `self.open_new_session` is called. :param list(tuple) pos_order_lines_ui_args: pairs of `ordered product` and `quantity` or triplet of `ordered product`, `quantity` and discount :param list(tuple) payments: pair of `payment_method` and `amount` """ default_fiscal_position = self.config.default_fiscal_position_id fiscal_position = customer.property_account_position_id if customer else default_fiscal_position def create_order_line(product, quantity, discount=0.0): price_unit = self.pricelist.get_product_price(product, quantity, False) tax_ids = fiscal_position.map_tax(product.taxes_id) price_unit_after_discount = price_unit * (1 - discount / 100.0) tax_values = ( tax_ids.compute_all(price_unit_after_discount, self.currency, quantity) if tax_ids else { 'total_excluded': price_unit * quantity, 'total_included': price_unit * quantity, } ) return (0, 0, { 'discount': discount, 'id': randint(1, 1000000), 'pack_lot_ids': [], 'price_unit': price_unit, 'product_id': product.id, 'price_subtotal': tax_values['total_excluded'], 'price_subtotal_incl': tax_values['total_included'], 'qty': quantity, 'tax_ids': [(6, 0, tax_ids.ids)] }) def create_payment(payment_method, amount): return (0, 0, { 'amount': amount, 'name': fields.Datetime.now(), 'payment_method_id': payment_method.id, }) uid = uid or self.create_random_uid() # 1. generate the order lines order_lines = [ create_order_line(product, quantity, discount and discount[0] or 0.0) for product, quantity, *discount in pos_order_lines_ui_args ] # 2. generate the payments total_amount_incl = sum(line[2]['price_subtotal_incl'] for line in order_lines) if payments is None: default_cash_pm = self.config.payment_method_ids.filtered(lambda pm: pm.is_cash_count)[:1] if not default_cash_pm: raise Exception('There should be a cash payment method set in the pos.config.') payments = [create_payment(default_cash_pm, total_amount_incl)] else: payments = [ create_payment(pm, amount) for pm, amount in payments ] # 3. complete the fields of the order_data total_amount_base = sum(line[2]['price_subtotal'] for line in order_lines) return { 'data': { 'amount_paid': sum(payment[2]['amount'] for payment in payments), 'amount_return': 0, 'amount_tax': total_amount_incl - total_amount_base, 'amount_total': total_amount_incl, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': fiscal_position.id, 'pricelist_id': self.config.pricelist_id.id, 'lines': order_lines, 'name': 'Order %s' % uid, 'partner_id': customer and customer.id, 'pos_session_id': self.pos_session.id, 'sequence_number': 2, 'statement_ids': payments, 'uid': uid, 'user_id': self.env.user.id, 'to_invoice': is_invoiced, }, 'id': uid, 'to_invoice': is_invoiced, } @classmethod def create_product(cls, name, category, lst_price, standard_price=None, tax_ids=None, sale_account=None): product = cls.env['product.product'].create({ 'type': 'product', 'available_in_pos': True, 'taxes_id': [(5, 0, 0)] if not tax_ids else [(6, 0, tax_ids)], 'name': name, 'categ_id': category.id, 'lst_price': lst_price, 'standard_price': standard_price if standard_price else 0.0, }) if sale_account: product.property_account_income_id = sale_account return product @classmethod def adjust_inventory(cls, products, quantities): """ Adjust inventory of the given products """ for product, qty in zip(products, quantities): cls.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': product.id, 'inventory_quantity': qty, 'location_id': cls.stock_location_components.id, }).action_apply_inventory() def open_new_session(self, opening_cash=0): """ Used to open new pos session in each configuration. - The idea is to properly set values that are constant and commonly used in an open pos session. - Calling this method is also a prerequisite for using `self.create_ui_order_data` function. Fields: * config : the pos.config currently being used. Its value is set at `self.setUp` of the inheriting test class. * pos_session : the current_session_id of config * currency : currency of the current pos.session * pricelist : the default pricelist of the session """ self.config.open_session_cb(check_coa=False) self.pos_session = self.config.current_session_id self.currency = self.pos_session.currency_id self.pricelist = self.pos_session.config_id.pricelist_id self.pos_session.set_cashbox_pos(opening_cash, None) return self.pos_session def _run_test(self, args): pos_session = self._start_pos_session(args['payment_methods'], args.get('opening_cash', 0)) _logger.info('DONE: Start session.') orders_map = self._create_orders(args['orders']) _logger.info('DONE: Orders created.') before_closing_cb = args.get('before_closing_cb') if before_closing_cb: before_closing_cb() _logger.info('DONE: Call of before_closing_cb.') self._check_invoice_journal_entries(pos_session, orders_map, expected_values=args['journal_entries_before_closing']) _logger.info('DONE: Checks for journal entries before closing the session.') total_cash_payment = sum(pos_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) pos_session.post_closing_cash_details(total_cash_payment) pos_session.close_session_from_ui() after_closing_cb = args.get('after_closing_cb') if after_closing_cb: after_closing_cb() _logger.info('DONE: Call of after_closing_cb.') self._check_session_journal_entries(pos_session, expected_values=args['journal_entries_after_closing']) _logger.info('DONE: Checks for journal entries after closing the session.') def _start_pos_session(self, payment_methods, opening_cash): self.config.write({'payment_method_ids': [(6, 0, payment_methods.ids)]}) pos_session = self.open_new_session(opening_cash) self.assertEqual(self.config.payment_method_ids.ids, pos_session.payment_method_ids.ids, msg='Payment methods in the config should be the same as the session.') return pos_session def _create_orders(self, order_data_params): '''Returns a dict mapping uid to its created pos.order record.''' result = {} for params in order_data_params: order_data = self.create_ui_order_data(**params) result[params['uid']] = self.env['pos.order'].browse([order['id'] for order in self.env['pos.order'].create_from_ui([order_data])]) return result def _check_invoice_journal_entries(self, pos_session, orders_map, expected_values): '''Checks the invoice, together with the payments, from each invoiced order.''' currency_rounding = pos_session.currency_id.rounding for uid in orders_map: order = orders_map[uid] if not order.is_invoiced: continue invoice = order.account_move # allow not checking the invoice since pos is not creating the invoices if expected_values[uid].get('invoice'): self._assert_account_move(invoice, expected_values[uid]['invoice']) _logger.info('DONE: Check of invoice for order %s.', uid) for pos_payment in order.payment_ids: if pos_payment.payment_method_id == self.pay_later_pm: # Skip the pay later payments since there are no journal entries # for them when invoicing. continue # This predicate is used to match the pos_payment's journal entry to the # list of payments specified in the 'payments' field of the `_run_test` # args. def predicate(args): payment_method, amount = args first = payment_method == pos_payment.payment_method_id second = tools.float_is_zero(pos_payment.amount - amount, precision_rounding=currency_rounding) return first and second self._find_then_assert_values(pos_payment.account_move_id, expected_values[uid]['payments'], predicate) _logger.info('DONE: Check of invoice payment (%s, %s) for order %s.', pos_payment.payment_method_id.name, pos_payment.amount, uid) def _check_session_journal_entries(self, pos_session, expected_values): '''Checks the journal entries after closing the session excluding entries checked in `_check_invoice_journal_entries`.''' currency_rounding = pos_session.currency_id.rounding # check expected session journal entry self._assert_account_move(pos_session.move_id, expected_values['session_journal_entry']) _logger.info("DONE: Check of the session's account move.") # check expected cash journal entries for statement_line in pos_session.cash_register_id.line_ids: def statement_line_predicate(args): return tools.float_is_zero(statement_line.amount - args[0], precision_rounding=currency_rounding) self._find_then_assert_values(statement_line.move_id, expected_values['cash_statement'], statement_line_predicate) _logger.info("DONE: Check of cash statement lines.") # check expected bank payments for bank_payment in pos_session.bank_payment_ids: def bank_payment_predicate(args): return tools.float_is_zero(bank_payment.amount - args[0], precision_rounding=currency_rounding) self._find_then_assert_values(bank_payment.move_id, expected_values['bank_payments'], bank_payment_predicate) _logger.info("DONE: Check of bank account payments.") def _find_then_assert_values(self, account_move, source_of_expected_vals, predicate): expected_move_vals = next(move_vals for args, move_vals in source_of_expected_vals if predicate(args)) self._assert_account_move(account_move, expected_move_vals) def _assert_account_move(self, account_move, expected_account_move_vals): if expected_account_move_vals: # We allow partial checks of the lines of the account move if `line_ids_predicate` is specified. # This means that only those that satisfy the predicate are compared to the expected account move line_ids. line_ids_predicate = expected_account_move_vals.pop('line_ids_predicate', lambda _: True) self.assertRecordValues(account_move.line_ids.filtered(line_ids_predicate), expected_account_move_vals.pop('line_ids')) self.assertRecordValues(account_move, [expected_account_move_vals]) else: # if the expected_account_move_vals is falsy, the account_move should be falsy. self.assertFalse(account_move)
45.890411
33,500
65,758
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time import odoo from odoo import fields, tools from odoo.tools import float_compare, mute_logger, test_reports from odoo.tests.common import Form from odoo.addons.point_of_sale.tests.common import TestPointOfSaleCommon @odoo.tests.tagged('post_install', '-at_install') class TestPointOfSaleFlow(TestPointOfSaleCommon): def compute_tax(self, product, price, qty=1, taxes=None): if not taxes: taxes = product.taxes_id.filtered(lambda t: t.company_id.id == self.env.company.id) currency = self.pos_config.pricelist_id.currency_id res = taxes.compute_all(price, currency, qty, product=product) untax = res['total_excluded'] return untax, sum(tax.get('amount', 0.0) for tax in res['taxes']) def test_order_refund(self): self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id # I create a new PoS order with 2 lines order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 5.0, 'qty': 2.0, 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': 450 * (1 - 5/100.0) * 2, 'price_subtotal_incl': 450 * (1 - 5/100.0) * 2, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 5.0, 'qty': 3.0, 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': 300 * (1 - 5/100.0) * 3, 'price_subtotal_incl': 300 * (1 - 5/100.0) * 3, })], 'amount_total': 1710.0, 'amount_tax': 0.0, 'amount_paid': 0.0, 'amount_return': 0.0, }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() self.assertAlmostEqual(order.amount_total, order.amount_paid, msg='Order should be fully paid.') # I create a refund refund_action = order.refund() refund = self.PosOrder.browse(refund_action['res_id']) self.assertEqual(order.amount_total, -1*refund.amount_total, "The refund does not cancel the order (%s and %s)" % (order.amount_total, refund.amount_total)) payment_context = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. refund_payment.with_context(**payment_context).check() self.assertEqual(refund.state, 'paid', "The refund is not marked as paid") self.assertTrue(refund.payment_ids.payment_method_id.is_cash_count, msg='There should only be one payment and paid in cash.') total_cash_payment = sum(current_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) current_session.post_closing_cash_details(total_cash_payment) current_session.close_session_from_ui() self.assertEqual(current_session.state, 'closed', msg='State of current session should be closed.') def test_order_refund_lots(self): # open pos session self.pos_config.open_session_cb() current_session = self.pos_config.current_session_id # set up product iwith SN tracing and create two lots (1001, 1002) self.stock_location = self.company_data['default_warehouse'].lot_stock_id self.product2 = self.env['product.product'].create({ 'name': 'Product A', 'type': 'product', 'tracking': 'serial', 'categ_id': self.env.ref('product.product_category_all').id, }) lot1 = self.env['stock.production.lot'].create({ 'name': '1001', 'product_id': self.product2.id, 'company_id': self.env.company.id, }) lot2 = self.env['stock.production.lot'].create({ 'name': '1002', 'product_id': self.product2.id, 'company_id': self.env.company.id, }) self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product2.id, 'inventory_quantity': 1, 'location_id': self.stock_location.id, 'lot_id': lot1.id }).action_apply_inventory() self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product2.id, 'inventory_quantity': 1, 'location_id': self.stock_location.id, 'lot_id': lot2.id }).action_apply_inventory() # create pos order with the two SN created before order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product2.id, 'price_unit': 6, 'discount': 0, 'qty': 2, 'tax_ids': [[6, False, []]], 'price_subtotal': 12, 'price_subtotal_incl': 12, 'pack_lot_ids': [ [0, 0, {'lot_name': '1001'}], [0, 0, {'lot_name': '1002'}], ] })], 'pricelist_id': 1, 'amount_paid': 12.0, 'amount_total': 12.0, 'amount_tax': 0.0, 'amount_return': 0.0, 'to_invoice': False, }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() # I create a refund refund_action = order.refund() refund = self.PosOrder.browse(refund_action['res_id']) order_lot_id = [lot_id.lot_name for lot_id in order.lines.pack_lot_ids] refund_lot_id = [lot_id.lot_name for lot_id in refund.lines.pack_lot_ids] self.assertEqual( order_lot_id, refund_lot_id, "In the refund we should find the same lot as in the original order") payment_context = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. refund_payment.with_context(**payment_context).check() self.assertEqual(refund.state, 'paid', "The refund is not marked as paid") current_session.action_pos_session_closing_control() def test_ship_later_picking(self): """ In order to test the picking's generated from the point of sale using the ship later """ # I click on create a new session button self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id # I create a PoS order with 1 units of PCSC234 at 450 EUR # and 1 units of PCSC349 at 300 EUR. untax1, atax1 = self.compute_tax(self.product3, 450, 1) untax2, atax2 = self.compute_tax(self.product4, 300, 1) self.pos_order_pos1 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'to_ship': True, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': 1.0, 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': 1.0, 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [self.pos_order_pos1.id], "active_id": self.pos_order_pos1.id } self.pos_make_payment_1 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2 }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos1.id} self.pos_make_payment_1.with_context(context_payment).check() # I create a second order untax1, atax1 = self.compute_tax(self.product3, 450, 1) untax2, atax2 = self.compute_tax(self.product4, 300, 1) self.pos_order_pos2 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'to_ship': True, 'lines': [(0, 0, { 'name': "OL/0003", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': 1, 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0004", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': 1, 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [self.pos_order_pos2.id], "active_id": self.pos_order_pos2.id } self.pos_make_payment_2 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2 }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos2.id} self.pos_make_payment_2.with_context(context_payment).check() current_session.picking_ids.move_ids_without_package.quantity_done = 1 current_session.picking_ids.button_validate() # I test that the pickings are created as expected during payment # One picking attached and having all the positive move lines in the correct state self.assertEqual( self.pos_order_pos1.picking_ids[0].state, 'done', 'Picking should be in done state.' ) self.assertEqual( self.pos_order_pos1.picking_ids[0].move_lines.mapped('state'), ['done', 'done'], 'Move Lines should be in done state.' ) self.assertEqual( self.pos_order_pos2.picking_ids[0].state, 'done', 'Picking should be in done state.' ) self.assertEqual( self.pos_order_pos2.picking_ids[0].move_lines.mapped('state'), ['done', 'done'], 'Move Lines should be in done state.' ) # I close the session to generate the journal entries self.pos_config.current_session_id.action_pos_session_closing_control() def test_order_to_picking(self): """ In order to test the Point of Sale in module, I will do three orders from the sale to the payment, invoicing + picking, but will only check the picking consistency in the end. TODO: Check the negative picking after changing the picking relation to One2many (also for a mixed use case), check the quantity, the locations and return picking logic """ # I click on create a new session button self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id # I create a PoS order with 2 units of PCSC234 at 450 EUR # and 3 units of PCSC349 at 300 EUR. untax1, atax1 = self.compute_tax(self.product3, 450, 2) untax2, atax2 = self.compute_tax(self.product4, 300, 3) self.pos_order_pos1 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': 2.0, 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': 3.0, 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [self.pos_order_pos1.id], "active_id": self.pos_order_pos1.id } self.pos_make_payment_2 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2 }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos1.id} self.pos_make_payment_2.with_context(context_payment).check() # I check that the order is marked as paid self.assertEqual( self.pos_order_pos1.state, 'paid', 'Order should be in paid state.' ) # I test that the pickings are created as expected during payment # One picking attached and having all the positive move lines in the correct state self.assertEqual( self.pos_order_pos1.picking_ids[0].state, 'done', 'Picking should be in done state.' ) self.assertEqual( self.pos_order_pos1.picking_ids[0].move_lines.mapped('state'), ['done', 'done'], 'Move Lines should be in done state.' ) # I create a second order untax1, atax1 = self.compute_tax(self.product3, 450, -2) untax2, atax2 = self.compute_tax(self.product4, 300, -3) self.pos_order_pos2 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0003", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': (-2.0), 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0004", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': (-3.0), 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [self.pos_order_pos2.id], "active_id": self.pos_order_pos2.id } self.pos_make_payment_3 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2 }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos2.id} self.pos_make_payment_3.with_context(context_payment).check() # I check that the order is marked as paid self.assertEqual( self.pos_order_pos2.state, 'paid', 'Order should be in paid state.' ) # I test that the pickings are created as expected # One picking attached and having all the positive move lines in the correct state self.assertEqual( self.pos_order_pos2.picking_ids[0].state, 'done', 'Picking should be in done state.' ) self.assertEqual( self.pos_order_pos2.picking_ids[0].move_lines.mapped('state'), ['done', 'done'], 'Move Lines should be in done state.' ) untax1, atax1 = self.compute_tax(self.product3, 450, -2) untax2, atax2 = self.compute_tax(self.product4, 300, 3) self.pos_order_pos3 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0005", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': (-2.0), 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0006", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': 3.0, 'tax_ids': [(6, 0, self.product4.taxes_id.ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [self.pos_order_pos3.id], "active_id": self.pos_order_pos3.id } self.pos_make_payment_4 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos3.id} self.pos_make_payment_4.with_context(context_payment).check() # I check that the order is marked as paid self.assertEqual( self.pos_order_pos3.state, 'paid', 'Order should be in paid state.' ) # I test that the pickings are created as expected # One picking attached and having all the positive move lines in the correct state self.assertEqual( self.pos_order_pos3.picking_ids[0].state, 'done', 'Picking should be in done state.' ) self.assertEqual( self.pos_order_pos3.picking_ids[0].move_lines.mapped('state'), ['done'], 'Move Lines should be in done state.' ) # I close the session to generate the journal entries self.pos_config.current_session_id.action_pos_session_closing_control() def test_order_to_picking02(self): """ This test is similar to test_order_to_picking except that this time, there are two products: - One tracked by lot - One untracked - Both are in a sublocation of the main warehouse """ tracked_product, untracked_product = self.env['product.product'].create([{ 'name': 'SuperProduct Tracked', 'type': 'product', 'tracking': 'lot', 'available_in_pos': True, }, { 'name': 'SuperProduct Untracked', 'type': 'product', 'available_in_pos': True, }]) wh_location = self.company_data['default_warehouse'].lot_stock_id shelf1_location = self.env['stock.location'].create({ 'name': 'shelf1', 'usage': 'internal', 'location_id': wh_location.id, }) lot = self.env['stock.production.lot'].create({ 'name': 'SuperLot', 'product_id': tracked_product.id, 'company_id': self.env.company.id, }) qty = 2 self.env['stock.quant']._update_available_quantity(tracked_product, shelf1_location, qty, lot_id=lot) self.env['stock.quant']._update_available_quantity(untracked_product, shelf1_location, qty) self.pos_config.open_session_cb() self.pos_config.current_session_id.update_stock_at_closing = False untax, atax = self.compute_tax(tracked_product, 1.15, 1) for dummy in range(qty): pos_order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': self.pos_config.current_session_id.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': tracked_product.id, 'price_unit': 1.15, 'discount': 0.0, 'qty': 1.0, 'tax_ids': [(6, 0, tracked_product.taxes_id.ids)], 'price_subtotal': untax, 'price_subtotal_incl': untax + atax, 'pack_lot_ids': [[0, 0, {'lot_name': lot.name}]], }), (0, 0, { 'name': "OL/0002", 'product_id': untracked_product.id, 'price_unit': 1.15, 'discount': 0.0, 'qty': 1.0, 'tax_ids': [(6, 0, untracked_product.taxes_id.ids)], 'price_subtotal': untax, 'price_subtotal_incl': untax + atax, })], 'amount_tax': 2 * atax, 'amount_total': 2 * (untax + atax), 'amount_paid': 0, 'amount_return': 0, }) context_make_payment = { "active_ids": [pos_order.id], "active_id": pos_order.id, } pos_make_payment = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 2 * (untax + atax), }) context_payment = {'active_id': pos_order.id} pos_make_payment.with_context(context_payment).check() self.assertEqual(pos_order.state, 'paid') tracked_line = pos_order.picking_ids.move_line_ids.filtered(lambda ml: ml.product_id.id == tracked_product.id) untracked_line = pos_order.picking_ids.move_line_ids - tracked_line self.assertEqual(tracked_line.lot_id, lot) self.assertFalse(untracked_line.lot_id) self.assertEqual(tracked_line.location_id, shelf1_location) self.assertEqual(untracked_line.location_id, shelf1_location) self.pos_config.current_session_id.action_pos_session_closing_control() def test_order_to_invoice(self): self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id untax1, atax1 = self.compute_tax(self.product3, 450*0.95, 2) untax2, atax2 = self.compute_tax(self.product4, 300*0.95, 3) # I create a new PoS order with 2 units of PC1 at 450 EUR (Tax Incl) and 3 units of PCSC349 at 300 EUR. (Tax Excl) self.pos_order_pos1 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 5.0, 'qty': 2.0, 'tax_ids': [(6, 0, self.product3.taxes_id.filtered(lambda t: t.company_id.id == self.env.company.id).ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 5.0, 'qty': 3.0, 'tax_ids': [(6, 0, self.product4.taxes_id.filtered(lambda t: t.company_id.id == self.env.company.id).ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0.0, 'amount_return': 0.0, }) # I click on the "Make Payment" wizard to pay the PoS order context_make_payment = {"active_ids": [self.pos_order_pos1.id], "active_id": self.pos_order_pos1.id} self.pos_make_payment = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': untax1 + untax2 + atax1 + atax2, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos1.id} self.pos_make_payment.with_context(context_payment).check() # I check that the order is marked as paid and there is no invoice # attached to it self.assertEqual(self.pos_order_pos1.state, 'paid', "Order should be in paid state.") self.assertFalse(self.pos_order_pos1.account_move, 'Invoice should not be attached to order.') # I generate an invoice from the order res = self.pos_order_pos1.action_pos_order_invoice() self.assertIn('res_id', res, "Invoice should be created") # I test that the total of the attached invoice is correct invoice = self.env['account.move'].browse(res['res_id']) if invoice.state != 'posted': invoice.action_post() self.assertAlmostEqual( invoice.amount_total, self.pos_order_pos1.amount_total, places=2, msg="Invoice not correct") # I close the session to generate the journal entries current_session.action_pos_session_closing_control() """In order to test the reports on Bank Statement defined in point_of_sale module, I create a bank statement line, confirm it and print the reports""" # I select the period and journal for the bank statement context_journal = {'journal_type': 'bank'} self.assertTrue(self.AccountBankStatement.with_context( context_journal)._default_journal(), 'Journal has not been selected') journal = self.env['account.journal'].create({ 'name': 'Bank Test', 'code': 'BNKT', 'type': 'bank', 'company_id': self.env.company.id, }) # I create a bank statement with Opening and Closing balance 0. account_statement = self.AccountBankStatement.create({ 'balance_start': 0.0, 'balance_end_real': 0.0, 'date': time.strftime('%Y-%m-%d'), 'journal_id': journal.id, 'company_id': self.env.company.id, 'name': 'pos session test', }) # I create bank statement line account_statement_line = self.AccountBankStatementLine.create({ 'amount': 1000, 'partner_id': self.partner4.id, 'statement_id': account_statement.id, 'payment_ref': 'EXT001' }) # I modify the bank statement and set the Closing Balance. account_statement.write({ 'balance_end_real': 1000.0, }) # I reconcile the bank statement. new_aml_dicts = [{ 'account_id': self.partner4.property_account_receivable_id.id, 'name': "EXT001", 'credit': 1000.0, 'debit': 0.0, }] # I confirm the bank statement using Confirm button self.AccountBankStatement.button_validate() def test_create_from_ui(self): """ Simulation of sales coming from the interface, even after closing the session """ # I click on create a new session button self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id num_starting_orders = len(current_session.order_ids) current_session.set_cashbox_pos(0, None) untax, atax = self.compute_tax(self.led_lamp, 0.9) carrot_order = {'data': {'amount_paid': untax + atax, 'amount_return': 0, 'amount_tax': atax, 'amount_total': untax + atax, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, {'discount': 0, 'pack_lot_ids': [], 'price_unit': 0.9, 'product_id': self.led_lamp.id, 'price_subtotal': 0.9, 'price_subtotal_incl': 1.04, 'qty': 1, 'tax_ids': [(6, 0, self.led_lamp.taxes_id.ids)]}]], 'name': 'Order 00042-003-0014', 'partner_id': False, 'pos_session_id': current_session.id, 'sequence_number': 2, 'statement_ids': [[0, 0, {'amount': untax + atax, 'name': fields.Datetime.now(), 'payment_method_id': self.cash_payment_method.id}]], 'uid': '00042-003-0014', 'user_id': self.env.uid}, 'to_invoice': False} untax, atax = self.compute_tax(self.whiteboard_pen, 1.2) zucchini_order = {'data': {'amount_paid': untax + atax, 'amount_return': 0, 'amount_tax': atax, 'amount_total': untax + atax, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, {'discount': 0, 'pack_lot_ids': [], 'price_unit': 1.2, 'product_id': self.whiteboard_pen.id, 'price_subtotal': 1.2, 'price_subtotal_incl': 1.38, 'qty': 1, 'tax_ids': [(6, 0, self.whiteboard_pen.taxes_id.ids)]}]], 'name': 'Order 00043-003-0014', 'partner_id': self.partner1.id, 'pos_session_id': current_session.id, 'sequence_number': self.pos_config.journal_id.id, 'statement_ids': [[0, 0, {'amount': untax + atax, 'name': fields.Datetime.now(), 'payment_method_id': self.credit_payment_method.id}]], 'uid': '00043-003-0014', 'user_id': self.env.uid}, 'to_invoice': False} untax, atax = self.compute_tax(self.newspaper_rack, 1.28) newspaper_rack_order = {'data': {'amount_paid': untax + atax, 'amount_return': 0, 'amount_tax': atax, 'amount_total': untax + atax, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, {'discount': 0, 'pack_lot_ids': [], 'price_unit': 1.28, 'product_id': self.newspaper_rack.id, 'price_subtotal': 1.28, 'price_subtotal_incl': 1.47, 'qty': 1, 'tax_ids': [[6, False, self.newspaper_rack.taxes_id.ids]]}]], 'name': 'Order 00044-003-0014', 'partner_id': False, 'pos_session_id': current_session.id, 'sequence_number': self.pos_config.journal_id.id, 'statement_ids': [[0, 0, {'amount': untax + atax, 'name': fields.Datetime.now(), 'payment_method_id': self.bank_payment_method.id}]], 'uid': '00044-003-0014', 'user_id': self.env.uid}, 'to_invoice': False} # I create an order on an open session self.PosOrder.create_from_ui([carrot_order]) self.assertEqual(num_starting_orders + 1, len(current_session.order_ids), "Submitted order not encoded") # I close the session total_cash_payment = sum(current_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) current_session.post_closing_cash_details(total_cash_payment) current_session.close_session_from_ui() self.assertEqual(current_session.state, 'closed', "Session was not properly closed") self.assertFalse(self.pos_config.current_session_id, "Current session not properly recomputed") # I keep selling after the session is closed with mute_logger('odoo.addons.point_of_sale.models.pos_order'): self.PosOrder.create_from_ui([zucchini_order, newspaper_rack_order]) rescue_session = self.PosSession.search([ ('config_id', '=', self.pos_config.id), ('state', '=', 'opened'), ('rescue', '=', True) ]) self.assertEqual(len(rescue_session), 1, "One (and only one) rescue session should be created for orphan orders") self.assertIn("(RESCUE FOR %s)" % current_session.name, rescue_session.name, "Rescue session is not linked to the previous one") self.assertEqual(len(rescue_session.order_ids), 2, "Rescue session does not contain both orders") # I close the rescue session total_cash_payment = sum(rescue_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) rescue_session.post_closing_cash_details(total_cash_payment) rescue_session.close_session_from_ui() self.assertEqual(rescue_session.state, 'closed', "Rescue session was not properly closed") def test_order_to_payment_currency(self): """ In order to test the Point of Sale in module, I will do a full flow from the sale to the payment and invoicing. I will use two products, one with price including a 10% tax, the other one with 5% tax excluded from the price. The order will be in a different currency than the company currency. """ # Make sure the company is in USD self.env.ref('base.USD').active = True self.env.ref('base.EUR').active = True self.env.cr.execute( "UPDATE res_company SET currency_id = %s WHERE id = %s", [self.env.ref('base.USD').id, self.env.company.id]) # Demo data are crappy, clean-up the rates self.env['res.currency.rate'].search([]).unlink() self.env['res.currency.rate'].create({ 'name': '2010-01-01', 'rate': 2.0, 'currency_id': self.env.ref('base.EUR').id, }) # make a config that has currency different from the company eur_pricelist = self.partner1.property_product_pricelist.copy(default={'currency_id': self.env.ref('base.EUR').id}) sale_journal = self.env['account.journal'].create({ 'name': 'PoS Sale EUR', 'type': 'sale', 'code': 'POSE', 'company_id': self.company.id, 'sequence': 12, 'currency_id': self.env.ref('base.EUR').id }) eur_config = self.pos_config.create({ 'name': 'Shop EUR Test', 'module_account': False, 'journal_id': sale_journal.id, 'use_pricelist': True, 'available_pricelist_ids': [(6, 0, eur_pricelist.ids)], 'pricelist_id': eur_pricelist.id, 'payment_method_ids': [(6, 0, self.bank_payment_method.ids)] }) # I click on create a new session button eur_config.open_session_cb(check_coa=False) current_session = eur_config.current_session_id # I create a PoS order with 2 units of PCSC234 at 450 EUR (Tax Incl) # and 3 units of PCSC349 at 300 EUR. (Tax Excl) untax1, atax1 = self.compute_tax(self.product3, 450, 2) untax2, atax2 = self.compute_tax(self.product4, 300, 3) self.pos_order_pos0 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'pricelist_id': eur_pricelist.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 0.0, 'qty': 2.0, 'tax_ids': [(6, 0, self.product3.taxes_id.filtered(lambda t: t.company_id == self.env.company).ids)], 'price_subtotal': untax1, 'price_subtotal_incl': untax1 + atax1, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 0.0, 'qty': 3.0, 'tax_ids': [(6, 0, self.product4.taxes_id.filtered(lambda t: t.company_id == self.env.company).ids)], 'price_subtotal': untax2, 'price_subtotal_incl': untax2 + atax2, })], 'amount_tax': atax1 + atax2, 'amount_total': untax1 + untax2 + atax1 + atax2, 'amount_paid': 0.0, 'amount_return': 0.0, }) # I check that the total of the order is now equal to (450*2 + # 300*3*1.05)*0.95 self.assertLess( abs(self.pos_order_pos0.amount_total - (450 * 2 + 300 * 3 * 1.05)), 0.01, 'The order has a wrong total including tax and discounts') # I click on the "Make Payment" wizard to pay the PoS order with a # partial amount of 100.0 EUR context_make_payment = {"active_ids": [self.pos_order_pos0.id], "active_id": self.pos_order_pos0.id} self.pos_make_payment_0 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 100.0, 'payment_method_id': self.bank_payment_method.id, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos0.id} self.pos_make_payment_0.with_context(context_payment).check() # I check that the order is not marked as paid yet self.assertEqual(self.pos_order_pos0.state, 'draft', 'Order should be in draft state.') # On the second payment proposition, I check that it proposes me the # remaining balance which is 1790.0 EUR defs = self.pos_make_payment_0.with_context({'active_id': self.pos_order_pos0.id}).default_get(['amount']) self.assertLess( abs(defs['amount'] - ((450 * 2 + 300 * 3 * 1.05) - 100.0)), 0.01, "The remaining balance is incorrect.") #'I pay the remaining balance. context_make_payment = { "active_ids": [self.pos_order_pos0.id], "active_id": self.pos_order_pos0.id} self.pos_make_payment_1 = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': (450 * 2 + 300 * 3 * 1.05) - 100.0, 'payment_method_id': self.bank_payment_method.id, }) # I click on the validate button to register the payment. self.pos_make_payment_1.with_context(context_make_payment).check() # I check that the order is marked as paid self.assertEqual(self.pos_order_pos0.state, 'paid', 'Order should be in paid state.') # I generate the journal entries current_session.action_pos_session_validate() # I test that the generated journal entry is attached to the PoS order self.assertTrue(current_session.move_id, "Journal entry should have been attached to the session.") # Check the amounts debit_lines = current_session.move_id.mapped('line_ids.debit') credit_lines = current_session.move_id.mapped('line_ids.credit') amount_currency_lines = current_session.move_id.mapped('line_ids.amount_currency') for a, b in zip(sorted(debit_lines), [0.0, 0.0, 0.0, 0.0, 922.5]): self.assertAlmostEqual(a, b) for a, b in zip(sorted(credit_lines), [0.0, 22.5, 40.91, 409.09, 450]): self.assertAlmostEqual(a, b) for a, b in zip(sorted(amount_currency_lines), [-900, -818.18, -81.82, -45, 1845]): self.assertAlmostEqual(a, b) def test_order_to_invoice_no_tax(self): self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id # I create a new PoS order with 2 units of PC1 at 450 EUR (Tax Incl) and 3 units of PCSC349 at 300 EUR. (Tax Excl) self.pos_order_pos1 = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 5.0, 'qty': 2.0, 'price_subtotal': 855, 'price_subtotal_incl': 855, }), (0, 0, { 'name': "OL/0002", 'product_id': self.product4.id, 'price_unit': 300, 'discount': 5.0, 'qty': 3.0, 'price_subtotal': 855, 'price_subtotal_incl': 855, })], 'amount_tax': 855 * 2, 'amount_total': 855 * 2, 'amount_paid': 0.0, 'amount_return': 0.0, }) # I click on the "Make Payment" wizard to pay the PoS order context_make_payment = {"active_ids": [self.pos_order_pos1.id], "active_id": self.pos_order_pos1.id} self.pos_make_payment = self.PosMakePayment.with_context(context_make_payment).create({ 'amount': 855 * 2, }) # I click on the validate button to register the payment. context_payment = {'active_id': self.pos_order_pos1.id} self.pos_make_payment.with_context(context_payment).check() # I check that the order is marked as paid and there is no invoice # attached to it self.assertEqual(self.pos_order_pos1.state, 'paid', "Order should be in paid state.") self.assertFalse(self.pos_order_pos1.account_move, 'Invoice should not be attached to order yet.') # I generate an invoice from the order res = self.pos_order_pos1.action_pos_order_invoice() self.assertIn('res_id', res, "No invoice created") # I test that the total of the attached invoice is correct invoice = self.env['account.move'].browse(res['res_id']) if invoice.state != 'posted': invoice.action_post() self.assertAlmostEqual( invoice.amount_total, self.pos_order_pos1.amount_total, places=2, msg="Invoice not correct") for iline in invoice.invoice_line_ids: self.assertFalse(iline.tax_ids) self.pos_config.current_session_id.action_pos_session_closing_control() def test_order_with_deleted_tax(self): # create tax dummy_50_perc_tax = self.env['account.tax'].create({ 'name': 'Tax 50%', 'amount_type': 'percent', 'amount': 50.0, 'price_include': 0 }) # set tax to product product5 = self.env['product.product'].create({ 'name': 'product5', 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, 'taxes_id': dummy_50_perc_tax.ids }) # sell product thru pos self.pos_config.open_session_cb(check_coa=False) pos_session = self.pos_config.current_session_id untax, atax = self.compute_tax(product5, 10.0) product5_order = {'data': {'amount_paid': untax + atax, 'amount_return': 0, 'amount_tax': atax, 'amount_total': untax + atax, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, {'discount': 0, 'pack_lot_ids': [], 'price_unit': 10.0, 'product_id': product5.id, 'price_subtotal': 10.0, 'price_subtotal_incl': 15.0, 'qty': 1, 'tax_ids': [(6, 0, product5.taxes_id.ids)]}]], 'name': 'Order 12345-123-1234', 'partner_id': False, 'pos_session_id': pos_session.id, 'sequence_number': 2, 'statement_ids': [[0, 0, {'amount': untax + atax, 'name': fields.Datetime.now(), 'payment_method_id': self.cash_payment_method.id}]], 'uid': '12345-123-1234', 'user_id': self.env.uid}, 'to_invoice': False} self.PosOrder.create_from_ui([product5_order]) # delete tax dummy_50_perc_tax.unlink() total_cash_payment = sum(pos_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) pos_session.post_closing_cash_details(total_cash_payment) # close session (should not fail here) # We don't call `action_pos_session_closing_control` to force the failed # closing which will return the action because the internal rollback call messes # with the rollback of the test runner. So instead, we directly call the method # that returns the action by specifying the imbalance amount. action = pos_session._close_session_action(5.0) wizard = self.env['pos.close.session.wizard'].browse(action['res_id']) wizard.with_context(action['context']).close_session() # check the difference line diff_line = pos_session.move_id.line_ids.filtered(lambda line: line.name == 'Difference at closing PoS session') self.assertAlmostEqual(diff_line.credit, 5.0, msg="Missing amount of 5.0") def test_order_refund_picking(self): self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id current_session.update_stock_at_closing = True # I create a new PoS order with 1 line order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product3.id, 'price_unit': 450, 'discount': 5.0, 'qty': 2.0, 'tax_ids': [(6, 0, self.product3.taxes_id.ids)], 'price_subtotal': 450 * (1 - 5/100.0) * 2, 'price_subtotal_incl': 450 * (1 - 5/100.0) * 2, })], 'amount_total': 1710.0, 'amount_tax': 0.0, 'amount_paid': 0.0, 'amount_return': 0.0, 'to_invoice': True }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() # I create a refund refund_action = order.refund() refund = self.PosOrder.browse(refund_action['res_id']) payment_context = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. refund_payment.with_context(**payment_context).check() refund.action_pos_order_invoice() self.assertEqual(refund.picking_count, 1) def test_order_with_different_payments_and_refund(self): """ Test that all the payments are correctly taken into account when the order contains multiple payments and money refund. In this example, we create an order with two payments for a product of 750$: - one payment of $300 with customer account - one payment of $460 with cash Then, we refund the order with $10, and check that the amount still due is 300$. """ product5 = self.env['product.product'].create({ 'name': 'product5', 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, }) # sell product thru pos self.pos_config.open_session_cb() pos_session = self.pos_config.current_session_id product5_order = {'data': {'amount_paid': 750, 'amount_return': 10, 'amount_tax': 0, 'amount_total': 750, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, { 'discount': 0, 'pack_lot_ids': [], 'price_unit': 750.0, 'product_id': product5.id, 'price_subtotal': 750.0, 'price_subtotal_incl': 750.0, 'tax_ids': [[6, False, []]], 'qty': 1, }]], 'name': 'Order 12345-123-1234', 'partner_id': self.partner1.id, 'pos_session_id': pos_session.id, 'sequence_number': 2, 'statement_ids': [[0, 0, { 'amount': 460, 'name': fields.Datetime.now(), 'payment_method_id': self.cash_payment_method.id }], [0, 0, { 'amount': 300, 'name': fields.Datetime.now(), 'payment_method_id': self.credit_payment_method.id }]], 'uid': '12345-123-1234', 'user_id': self.env.uid, 'to_invoice': True, } } pos_order_id = self.PosOrder.create_from_ui([product5_order])[0]['id'] pos_order = self.PosOrder.search([('id', '=', pos_order_id)]) #assert account_move amount_residual is 300 self.assertEqual(pos_order.account_move.amount_residual, 300) def test_order_pos_tax_same_as_company(self): """Test that when the default_pos_receivable_account and the partner account_receivable are the same, payment are correctly reconciled and the invoice is correctly marked as paid. """ self.pos_config.open_session_cb() current_session = self.pos_config.current_session_id current_session.company_id.account_default_pos_receivable_account_id = self.partner1.property_account_receivable_id product5_order = {'data': {'amount_paid': 750, 'amount_tax': 0, 'amount_return':0, 'amount_total': 750, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, { 'discount': 0, 'pack_lot_ids': [], 'price_unit': 750.0, 'product_id': self.product3.id, 'price_subtotal': 750.0, 'price_subtotal_incl': 750.0, 'tax_ids': [[6, False, []]], 'qty': 1, }]], 'name': 'Order 12345-123-1234', 'partner_id': self.partner1.id, 'pos_session_id': current_session.id, 'sequence_number': 2, 'statement_ids': [[0, 0, { 'amount': 450, 'name': fields.Datetime.now(), 'payment_method_id': self.cash_payment_method.id }], [0, 0, { 'amount': 300, 'name': fields.Datetime.now(), 'payment_method_id': self.bank_payment_method.id }]], 'uid': '12345-123-1234', 'user_id': self.env.uid, 'to_invoice': True, } } pos_order_id = self.PosOrder.create_from_ui([product5_order])[0]['id'] pos_order = self.PosOrder.search([('id', '=', pos_order_id)]) self.assertEqual(pos_order.account_move.amount_residual, 0) def test_order_refund_with_owner(self): # open pos session self.pos_config.open_session_cb() current_session = self.pos_config.current_session_id # set up product iwith SN tracing and create two lots (1001, 1002) self.stock_location = self.company_data['default_warehouse'].lot_stock_id self.product2 = self.env['product.product'].create({ 'name': 'Product A', 'type': 'product', 'categ_id': self.env.ref('product.product_category_all').id, }) self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product2.id, 'inventory_quantity': 1, 'location_id': self.stock_location.id, 'owner_id': self.partner1.id }).action_apply_inventory() # create pos order with the two SN created before order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product2.id, 'price_unit': 6, 'discount': 0, 'qty': 1, 'tax_ids': [[6, False, []]], 'price_subtotal': 6, 'price_subtotal_incl': 6, })], 'pricelist_id': self.pos_config.pricelist_id.id, 'amount_paid': 6.0, 'amount_total': 6.0, 'amount_tax': 0.0, 'amount_return': 0.0, 'to_invoice': False, }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() # I create a refund refund_action = order.refund() refund = self.PosOrder.browse(refund_action['res_id']) payment_context = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_payment_method.id, }) # I click on the validate button to register the payment. refund_payment.with_context(**payment_context).check() current_session.action_pos_session_closing_control() self.assertEqual(refund.picking_ids.move_line_ids_without_package.owner_id.id, order.picking_ids.move_line_ids_without_package.owner_id.id, "The owner of the refund is not the same as the owner of the original order") def test_journal_entries_category_without_account(self): #create a new product category without account category = self.env['product.category'].create({ 'name': 'Category without account', 'property_account_income_categ_id': False, 'property_account_expense_categ_id': False, }) product = self.env['product.product'].create({ 'name': 'Product with category without account', 'type': 'product', 'categ_id': category.id, }) account = self.env['account.account'].create({ 'name': 'Account for category without account', 'code': 'X1111', 'user_type_id': self.env.ref('account.data_account_type_revenue').id, 'reconcile': True, }) self.pos_config.journal_id.default_account_id = account.id #create a new pos order with the product self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'pricelist_id': self.partner1.property_product_pricelist.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': product.id, 'price_unit': 10, 'discount': 0.0, 'qty': 1, 'tax_ids': [], 'price_subtotal': 10, 'price_subtotal_incl': 10, })], 'amount_total': 10, 'amount_tax': 0.0, 'amount_paid': 10, 'amount_return': 0.0, 'to_invoice': True }) #create a payment payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() current_session.action_pos_session_closing_control() self.assertEqual(current_session.move_id.line_ids[0].account_id.id, account.id) def test_tracked_product_with_owner(self): # open pos session self.pos_config.open_session_cb() current_session = self.pos_config.current_session_id # set up product iwith SN tracing and create two lots (1001, 1002) self.stock_location = self.company_data['default_warehouse'].lot_stock_id self.product2 = self.env['product.product'].create({ 'name': 'Product A', 'type': 'product', 'tracking': 'serial', 'categ_id': self.env.ref('product.product_category_all').id, }) lot1 = self.env['stock.production.lot'].create({ 'name': '1001', 'product_id': self.product2.id, 'company_id': self.env.company.id, }) self.env['stock.quant']._update_available_quantity(self.product2, self.stock_location, 1, lot_id=lot1, owner_id=self.partner1) # create pos order with the two SN created before order = self.PosOrder.create({ 'company_id': self.env.company.id, 'session_id': current_session.id, 'partner_id': self.partner1.id, 'lines': [(0, 0, { 'name': "OL/0001", 'product_id': self.product2.id, 'price_unit': 6, 'discount': 0, 'qty': 1, 'tax_ids': [[6, False, []]], 'price_subtotal': 6, 'price_subtotal_incl': 6, 'pack_lot_ids': [ [0, 0, {'lot_name': '1001'}], ] })], 'pricelist_id': self.pos_config.pricelist_id.id, 'amount_paid': 6.0, 'amount_total': 6.0, 'amount_tax': 0.0, 'amount_return': 0.0, 'to_invoice': False, }) payment_context = {"active_ids": order.ids, "active_id": order.id} order_payment = self.PosMakePayment.with_context(**payment_context).create({ 'amount': order.amount_total, 'payment_method_id': self.cash_payment_method.id }) order_payment.with_context(**payment_context).check() current_session.action_pos_session_closing_control() self.assertEqual(current_session.picking_ids.move_line_ids.owner_id.id, self.partner1.id) def test_order_refund_with_invoice(self): """This test make sure that credit notes of pos orders are correctly linked to the original invoice.""" self.pos_config.open_session_cb(check_coa=False) current_session = self.pos_config.current_session_id order_data = {'data': {'amount_paid': 450, 'amount_tax': 0, 'amount_return': 0, 'amount_total': 450, 'creation_date': fields.Datetime.to_string(fields.Datetime.now()), 'fiscal_position_id': False, 'pricelist_id': self.pos_config.available_pricelist_ids[0].id, 'lines': [[0, 0, { 'discount': 0, 'pack_lot_ids': [], 'price_unit': 450.0, 'product_id': self.product3.id, 'price_subtotal': 450.0, 'price_subtotal_incl': 450.0, 'tax_ids': [[6, False, []]], 'qty': 1, }]], 'name': 'Order 12345-123-1234', 'partner_id': self.partner1.id, 'pos_session_id': current_session.id, 'sequence_number': 2, 'statement_ids': [[0, 0, { 'amount': 450, 'name': fields.Datetime.now(), 'payment_method_id': self.cash_payment_method.id }]], 'uid': '12345-123-1234', 'user_id': self.env.uid, 'to_invoice': True, } } order = self.PosOrder.create_from_ui([order_data]) order = self.PosOrder.browse(order[0]['id']) refund_id = order.refund()['res_id'] refund = self.PosOrder.browse(refund_id) context_payment = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.PosMakePayment.with_context(**context_payment).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_payment_method.id }) refund_payment.with_context(**context_payment).check() refund.action_pos_order_invoice() #get last invoice created current_session.action_pos_session_closing_control() invoices = self.env['account.move'].search([('move_type', '=', 'out_invoice')], order='id desc', limit=1) credit_notes = self.env['account.move'].search([('move_type', '=', 'out_refund')], order='id desc', limit=1) self.assertEqual(credit_notes.ref, "Reversal of: "+invoices.name) self.assertEqual(credit_notes.reversed_entry_id.id, invoices.id)
42.922977
65,758
19,545
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo import tools from odoo.tests.common import Form from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSOtherCurrencyConfig(TestPoSCommon): """ Test PoS with basic configuration """ def setUp(self): super(TestPoSOtherCurrencyConfig, self).setUp() self.config = self.other_currency_config self.product1 = self.create_product('Product 1', self.categ_basic, 10.0, 5) self.product2 = self.create_product('Product 2', self.categ_basic, 20.0, 10) self.product3 = self.create_product('Product 3', self.categ_basic, 30.0, 15) self.product4 = self.create_product('Product 4', self.categ_anglo, 100, 50) self.product5 = self.create_product('Product 5', self.categ_anglo, 200, 70) self.product6 = self.create_product('Product 6', self.categ_anglo, 45.3, 10.73) self.product7 = self.create_product('Product 7', self.categ_basic, 7, 7, tax_ids=self.taxes['tax7'].ids) self.adjust_inventory( [self.product1, self.product2, self.product3, self.product4, self.product5, self.product6, self.product7], [100, 50, 50, 100, 100, 100, 100] ) # change the price of product2 to 12.99 fixed. No need to convert. pricelist_item = self.env['product.pricelist.item'].create({ 'product_tmpl_id': self.product2.product_tmpl_id.id, 'fixed_price': 12.99, }) self.config.pricelist_id.write({'item_ids': [(6, 0, (self.config.pricelist_id.item_ids | pricelist_item).ids)]}) self.output_account = self.categ_anglo.property_stock_account_output_categ_id self.expense_account = self.categ_anglo.property_account_expense_categ_id def test_01_check_product_cost(self): # Product price should be half of the original price because currency rate is 0.5. # (see `self._create_other_currency_config` method) # Except for product2 where the price is specified in the pricelist. self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product1, 1, self.customer), 5.00) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product2, 1, self.customer), 12.99) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product3, 1, self.customer), 15.00) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product4, 1, self.customer), 50) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product5, 1, self.customer), 100) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product6, 1, self.customer), 22.65) self.assertAlmostEqual(self.config.pricelist_id.get_product_price(self.product7, 1, self.customer), 3.50) def test_02_orders_without_invoice(self): """ orders without invoice Orders ====== +---------+----------+-----------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +---------+----------+-----------+----------+-----+-------+ | order 1 | cash | no | product1 | 10 | 50 | | | | | product2 | 10 | 129.9 | | | | | product3 | 10 | 150 | +---------+----------+-----------+----------+-----+-------+ | order 2 | cash | no | product1 | 5 | 25 | | | | | product2 | 5 | 64.95 | +---------+----------+-----------+----------+-----+-------+ | order 3 | bank | no | product2 | 5 | 64.95 | | | | | product3 | 5 | 75 | +---------+----------+-----------+----------+-----+-------+ Expected Result =============== +---------------------+---------+-----------------+ | account | balance | amount_currency | +---------------------+---------+-----------------+ | sale_account | -1119.6 | -559.80 | | pos receivable bank | 279.9 | 139.95 | | pos receivable cash | 839.7 | 419.85 | +---------------------+---------+-----------------+ | Total balance | 0.0 | 0.00 | +---------------------+---------+-----------------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self._run_test({ 'payment_methods': self.cash_pm2 | self.bank_pm2, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm2, 139.95)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 1119.6, 'reconciled': False, 'amount_currency': -559.80}, {'account_id': self.bank_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 279.9, 'credit': 0, 'reconciled': True, 'amount_currency': 139.95}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 839.7, 'credit': 0, 'reconciled': True, 'amount_currency': 419.85}, ], }, 'cash_statement': [ ((419.85, ), { 'line_ids': [ {'account_id': self.cash_pm2.journal_id.default_account_id.id, 'partner_id': False, 'debit': 839.7, 'credit': 0, 'reconciled': False, 'amount_currency': 419.85}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 839.7, 'reconciled': True, 'amount_currency': -419.85}, ] }), ], 'bank_payments': [ ((139.95, ), { 'line_ids': [ {'account_id': self.bank_pm2.outstanding_account_id.id, 'partner_id': False, 'debit': 279.9, 'credit': 0, 'reconciled': False, 'amount_currency': 139.95}, {'account_id': self.bank_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 279.9, 'reconciled': True, 'amount_currency': -139.95}, ] }), ], }, }) def test_03_orders_with_invoice(self): """ orders with invoice Orders ====== +---------+----------+---------------+----------+-----+-------+ | order | payments | invoiced? | product | qty | total | +---------+----------+---------------+----------+-----+-------+ | order 1 | cash | no | product1 | 10 | 50 | | | | | product2 | 10 | 129.9 | | | | | product3 | 10 | 150 | +---------+----------+---------------+----------+-----+-------+ | order 2 | cash | yes, customer | product1 | 5 | 25 | | | | | product2 | 5 | 64.95 | +---------+----------+---------------+----------+-----+-------+ | order 3 | bank | yes, customer | product2 | 5 | 64.95 | | | | | product3 | 5 | 75 | +---------+----------+---------------+----------+-----+-------+ Expected Result =============== +---------------------+---------+-----------------+ | account | balance | amount_currency | +---------------------+---------+-----------------+ | sale_account | -659.8 | -329.90 | | pos receivable bank | 279.9 | 139.95 | | pos receivable cash | 839.7 | 419.85 | | invoice receivable | -179.9 | -89.95 | | invoice receivable | -279.9 | -139.95 | +---------------------+---------+-----------------+ | Total balance | 0.0 | 0.00 | +---------------------+---------+-----------------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self._run_test({ 'payment_methods': self.cash_pm2 | self.bank_pm2, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'is_invoiced': True, 'customer': self.customer, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm2, 139.95)], 'is_invoiced': True, 'customer': self.customer, 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '00100-010-0002': { 'payments': [ ((self.cash_pm2, 89.95), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 179.90, 'reconciled': True, 'amount_currency': -89.95}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 179.90, 'credit': 0, 'reconciled': False, 'amount_currency': 89.95}, ] }), ], }, '00100-010-0003': { 'payments': [ ((self.bank_pm2, 139.95), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 279.9, 'reconciled': True, 'amount_currency': -139.95}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 279.9, 'credit': 0, 'reconciled': False, 'amount_currency': 139.95}, ] }), ], }, }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 659.8, 'reconciled': False, 'amount_currency': -329.90}, {'account_id': self.bank_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 279.9, 'credit': 0, 'reconciled': True, 'amount_currency': 139.95}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 839.7, 'credit': 0, 'reconciled': True, 'amount_currency': 419.85}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 179.90, 'reconciled': True, 'amount_currency': -89.95}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 279.9, 'reconciled': True, 'amount_currency': -139.95}, ], }, 'cash_statement': [ ((419.85, ), { 'line_ids': [ {'account_id': self.cash_pm2.journal_id.default_account_id.id, 'partner_id': False, 'debit': 839.7, 'credit': 0, 'reconciled': False, 'amount_currency': 419.85}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 839.7, 'reconciled': True, 'amount_currency': -419.85}, ] }), ], 'bank_payments': [ ((139.95, ), { 'line_ids': [ {'account_id': self.bank_pm2.outstanding_account_id.id, 'partner_id': False, 'debit': 279.9, 'credit': 0, 'reconciled': False, 'amount_currency': 139.95}, {'account_id': self.bank_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 279.9, 'reconciled': True, 'amount_currency': -139.95}, ] }), ], }, }) def test_04_anglo_saxon_products(self): """ ====== Orders ====== +---------+----------+-----------+----------+-----+----------+------------+ | order | payments | invoiced? | product | qty | total | total cost | | | | | | | | | +---------+----------+-----------+----------+-----+----------+------------+ | order 1 | cash | no | product4 | 7 | 700 | 350 | | | | | product5 | 7 | 1400 | 490 | +---------+----------+-----------+----------+-----+----------+------------+ | order 2 | cash | no | product5 | 6 | 1200 | 420 | | | | | product4 | 6 | 600 | 300 | | | | | product6 | 49 | 2219.7 | 525.77 | +---------+----------+-----------+----------+-----+----------+------------+ | order 3 | cash | no | product5 | 2 | 400 | 140 | | | | | product6 | 13 | 588.9 | 139.49 | +---------+----------+-----------+----------+-----+----------+------------+ | order 4 | cash | no | product6 | 1 | 45.3 | 10.73 | +---------+----------+-----------+----------+-----+----------+------------+ =============== Expected Result =============== +---------------------+------------+-----------------+ | account | balance | amount_currency | +---------------------+------------+-----------------+ | sale_account | -7153.90 | -3576.95 | | pos_receivable-cash | 7153.90 | 3576.95 | | expense_account | 2375.99 | 2375.99 | | output_account | -2375.99 | -2375.99 | +---------------------+------------+-----------------+ | Total balance | 0.00 | 0.00 | +---------------------+------------+-----------------+ """ self._run_test({ 'payment_methods': self.cash_pm2, 'orders': [ {'pos_order_lines_ui_args': [(self.product4, 7), (self.product5, 7)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product5, 6), (self.product4, 6), (self.product6, 49)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product5, 2), (self.product6, 13)], 'uid': '00100-010-0003'}, {'pos_order_lines_ui_args': [(self.product6, 1)], 'uid': '00100-010-0004'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 7153.90, 'reconciled': False, 'amount_currency': -3576.95}, {'account_id': self.expense_account.id, 'partner_id': False, 'debit': 2375.99, 'credit': 0, 'reconciled': False, 'amount_currency': 2375.99}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 7153.90, 'credit': 0, 'reconciled': True, 'amount_currency': 3576.95}, {'account_id': self.output_account.id, 'partner_id': False, 'debit': 0, 'credit': 2375.99, 'reconciled': True, 'amount_currency': -2375.99}, ], }, 'cash_statement': [ ((3576.95, ), { 'line_ids': [ {'account_id': self.cash_pm2.journal_id.default_account_id.id, 'partner_id': False, 'debit': 7153.90, 'credit': 0, 'reconciled': False, 'amount_currency': 3576.95}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 7153.90, 'reconciled': True, 'amount_currency': -3576.95}, ] }), ], 'bank_payments': [], }, }) def test_05_tax_base_amount(self): self._run_test({ 'payment_methods': self.cash_pm2, 'orders': [ {'pos_order_lines_ui_args': [(self.product7, 7)], 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 3.43, 'reconciled': False, 'amount_currency': -1.715, 'tax_base_amount': 49}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 49, 'reconciled': False, 'amount_currency': -24.5, 'tax_base_amount': 0}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 52.43, 'credit': 0, 'reconciled': True, 'amount_currency': 26.215, 'tax_base_amount': 0}, ], }, 'cash_statement': [ ((26.215, ), { 'line_ids': [ {'account_id': self.cash_pm2.journal_id.default_account_id.id, 'partner_id': False, 'debit': 52.43, 'credit': 0, 'reconciled': False, 'amount_currency': 26.215}, {'account_id': self.cash_pm2.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 52.43, 'reconciled': True, 'amount_currency': -26.215}, ] }), ], 'bank_payments': [], }, })
61.462264
19,545
22,163
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSWithFiscalPosition(TestPoSCommon): """ Tests to pos orders with fiscal position. keywords/phrases: fiscal position """ @classmethod def setUpClass(cls): super(TestPoSWithFiscalPosition, cls).setUpClass() cls.config = cls.basic_config cls.new_tax_17 = cls.env['account.tax'].create({'name': 'New Tax 17%', 'amount': 17}) cls.new_tax_17.invoice_repartition_line_ids.write({'account_id': cls.tax_received_account.id}) cls.fpos = cls._create_fiscal_position() cls.fpos_no_tax_dest = cls._create_fiscal_position_no_tax_dest() cls.product1 = cls.create_product( 'Product 1', cls.categ_basic, lst_price=10.99, standard_price=5.0, tax_ids=cls.taxes['tax7'].ids, ) cls.product2 = cls.create_product( 'Product 2', cls.categ_basic, lst_price=19.99, standard_price=10.0, tax_ids=cls.taxes['tax10'].ids, ) cls.product3 = cls.create_product( 'Product 3', cls.categ_basic, lst_price=30.99, standard_price=15.0, tax_ids=cls.taxes['tax7'].ids, ) cls.adjust_inventory([cls.product1, cls.product2, cls.product3], [100, 50, 50]) @classmethod def _create_fiscal_position(cls): fpos = cls.env['account.fiscal.position'].create({'name': 'Test Fiscal Position'}) account_fpos = cls.env['account.fiscal.position.account'].create({ 'position_id': fpos.id, 'account_src_id': cls.sale_account.id, 'account_dest_id': cls.other_sale_account.id, }) tax_fpos = cls.env['account.fiscal.position.tax'].create({ 'position_id': fpos.id, 'tax_src_id': cls.taxes['tax7'].id, 'tax_dest_id': cls.new_tax_17.id, }) fpos.write({ 'account_ids': [(6, 0, account_fpos.ids)], 'tax_ids': [(6, 0, tax_fpos.ids)], }) return fpos @classmethod def _create_fiscal_position_no_tax_dest(cls): fpos_no_tax_dest = cls.env['account.fiscal.position'].create({'name': 'Test Fiscal Position'}) account_fpos = cls.env['account.fiscal.position.account'].create({ 'position_id': fpos_no_tax_dest.id, 'account_src_id': cls.sale_account.id, 'account_dest_id': cls.other_sale_account.id, }) tax_fpos = cls.env['account.fiscal.position.tax'].create({ 'position_id': fpos_no_tax_dest.id, 'tax_src_id': cls.taxes['tax7'].id, }) fpos_no_tax_dest.write({ 'account_ids': [(6, 0, account_fpos.ids)], 'tax_ids': [(6, 0, tax_fpos.ids)], }) return fpos_no_tax_dest def test_01_no_invoice_fpos(self): """ orders without invoice Orders ====== +---------+----------+---------------+----------+-----+---------+-----------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+---------------+----------+-----+---------+-----------------+--------+ | order 1 | cash | yes, customer | product1 | 10 | 109.90 | 18.68 [7%->17%] | 128.58 | | | | | product2 | 10 | 181.73 | 18.17 [10%] | 199.90 | | | | | product3 | 10 | 309.90 | 52.68 [7%->17%] | 362.58 | +---------+----------+---------------+----------+-----+---------+-----------------+--------+ | order 2 | cash | yes, customer | product1 | 5 | 54.95 | 9.34 [7%->17%] | 64.29 | | | | | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | +---------+----------+---------------+----------+-----+---------+-----------------+--------+ | order 3 | bank | no | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | | | | | product3 | 5 | 154.95 | 10.85 [7%] | 165.8 | +---------+----------+---------------+----------+-----+---------+-----------------+--------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale_account | -154.95 | (for the 7% base amount) | sale_account | -90.86 | (for the 10% base amount) | other_sale_account | -474.75 | (for the 17% base amount) | other_sale_account | -272.59 | (for the 10% base amount) | tax 17% | -80.70 | | tax 10% | -36.35 | | tax 7% | -10.85 | | pos receivable bank | 265.75 | | pos receivable cash | 855.30 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ self.customer.write({'property_account_position_id': self.fpos.id}) def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'customer': self.customer, 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'customer': self.customer, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm1, 265.75)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 80.70, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 36.35, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 10.85, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 474.75, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 272.59, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 154.95, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 265.75, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 855.30, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((855.30, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 855.30, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 855.30, 'reconciled': True}, ] }), ], 'bank_payments': [ ((265.75, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 265.75, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 265.75, 'reconciled': True}, ] }), ], }, }) def test_02_no_invoice_fpos_no_tax_dest(self): """ Customer with fiscal position that maps a tax to no tax. Orders ====== +---------+----------+---------------+----------+-----+---------+-------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+---------------+----------+-----+---------+-------------+--------+ | order 1 | bank | yes, customer | product1 | 10 | 109.90 | 0 | 109.90 | | | | | product2 | 10 | 181.73 | 18.17 [10%] | 199.90 | | | | | product3 | 10 | 309.90 | 0 | 309.90 | +---------+----------+---------------+----------+-----+---------+-------------+--------+ | order 2 | cash | yes, customer | product1 | 5 | 54.95 | 0 | 54.95 | | | | | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | +---------+----------+---------------+----------+-----+---------+-------------+--------+ | order 3 | bank | no | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | | | | | product3 | 5 | 154.95 | 10.85 [7%] | 165.80 | +---------+----------+---------------+----------+-----+---------+-------------+--------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale_account | -154.95 | (for the 7% base amount) | sale_account | -90.86 | (for the 10% base amount) | other_sale_account | -272.59 | (for the 10% base amount) | other_sale_account | -474.75 | (no tax) | tax 10% | -36.35 | | tax 7% | -10.85 | | pos receivable bank | 885.45 | | pos receivable cash | 154.9 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ self.customer.write({'property_account_position_id': self.fpos_no_tax_dest.id}) def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'payments': [(self.bank_pm1, 619.7)], 'customer': self.customer, 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'customer': self.customer, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'payments': [(self.bank_pm1, 265.75)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 36.35, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 10.85, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 474.75, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 272.59, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 154.95, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 885.45, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 154.9, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((154.9, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 154.9, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 154.9, 'reconciled': True}, ] }), ], 'bank_payments': [ ((885.45, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 885.45, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 885.45, 'reconciled': True}, ] }), ], }, }) def test_03_invoiced_fpos(self): """ Invoice 2 orders. Orders ====== +---------+----------+---------------------+----------+-----+---------+-----------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+---------------------+----------+-----+---------+-----------------+--------+ | order 1 | bank | yes, customer | product1 | 10 | 109.90 | 18.68 [7%->17%] | 128.58 | | | | | product2 | 10 | 181.73 | 18.17 [10%] | 199.90 | | | | | product3 | 10 | 309.90 | 52.68 [7%->17%] | 362.58 | +---------+----------+---------------------+----------+-----+---------+-----------------+--------+ | order 2 | cash | no, customer | product1 | 5 | 54.95 | 9.34 [7%->17%] | 64.29 | | | | | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | +---------+----------+---------------------+----------+-----+---------+-----------------+--------+ | order 3 | cash | yes, other_customer | product2 | 5 | 90.86 | 9.09 [10%] | 99.95 | | | | | product3 | 5 | 154.95 | 10.85 [7%] | 165.80 | +---------+----------+---------------------+----------+-----+---------+-----------------+--------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | other_sale_account | -54.95 | (for the 17% base amount) | other_sale_account | -90.86 | (for the 10% base amount) | tax 10% | -9.09 | | tax 17% | -9.34 | | pos receivable cash | 429.99 | | pos receivable bank | 691.06 | | receivable | -691.06 | | other receivable | -265.75 | +---------------------+---------+ | Total balance | 0.0 | +---------------------+---------+ """ self.customer.write({'property_account_position_id': self.fpos.id}) def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') invoiced_order_1 = self.pos_session.order_ids.filtered(lambda order: '00100-010-0001' in order.pos_reference) invoiced_order_2 = self.pos_session.order_ids.filtered(lambda order: '00100-010-0003' in order.pos_reference) self.assertTrue(invoiced_order_1, msg='Invoiced order 1 should exist.') self.assertTrue(invoiced_order_2, msg='Invoiced order 2 should exist.') self.assertTrue(invoiced_order_1.account_move, msg='Invoiced order 1 should have invoice (account_move).') self.assertTrue(invoiced_order_2.account_move, msg='Invoiced order 2 should have invoice (account_move).') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10), (self.product3, 10)], 'payments': [(self.bank_pm1, 691.06)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product1, 5), (self.product2, 5)], 'customer': self.customer, 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product2, 5), (self.product3, 5)], 'customer': self.other_customer, 'is_invoiced': True, 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '00100-010-0001': { 'payments': [ ((self.bank_pm1, 691.06), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 691.06, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 691.06, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0003': { 'payments': [ ((self.cash_pm1, 265.75), { 'line_ids': [ {'account_id': self.other_receivable_account.id, 'partner_id': self.other_customer.id, 'debit': 0, 'credit': 265.75, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 265.75, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 9.34, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 9.09, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 54.95, 'reconciled': False}, {'account_id': self.other_sale_account.id, 'partner_id': False, 'debit': 0, 'credit': 90.86, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 691.06, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 429.99, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 691.06, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 265.75, 'reconciled': True}, ], }, 'cash_statement': [ ((429.99, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 429.99, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 429.99, 'reconciled': True}, ] }), ], 'bank_payments': [ ((691.06, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 691.06, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 691.06, 'reconciled': True}, ] }), ], }, })
59.101333
22,163
32,572
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPosSimpleOrders(TestPoSCommon): """ Each test case only make a single order. Name of each test corresponds to a sheet in: https://docs.google.com/spreadsheets/d/1mt2jRSDU7OONPBFjwyTcnhRjITQI8rGMLLQA5K3fAjo/edit?usp=sharing """ def setUp(self): super(TestPosSimpleOrders, self).setUp() self.config = self.basic_config self.product100 = self.create_product('Product_100', self.categ_basic, 100, 50) def test_01(self): self._run_test({ 'payment_methods': self.cash_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_02(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_03(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.pay_later_pm, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [], }, }) def test_04(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_05(self): self._run_test({ 'payment_methods': self.cash_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_06(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [], 'payments': [(self.cash_pm1, 100), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_07(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [], 'payments': [(self.bank_pm1, 100), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_08(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [], 'payments': [(self.bank_split_pm1, 100), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((100, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], }, }) def test_09(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [], 'payments': [(self.cash_split_pm1, 100), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_10(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_11(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_12(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_13(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 200), (self.pay_later_pm, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_14(self): self._run_test({ 'payment_methods': self.cash_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_15(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((-100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_16(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 200), (self.cash_pm1, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((-100, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [ ((200, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }) ], }, }) def test_17(self): self._run_test({ 'payment_methods': self.cash_split_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 200), (self.cash_split_pm1, -100)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': True}, ], }, 'cash_statement': [ ((200, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 200, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 200, 'reconciled': True}, ] }), ((-100, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 100, 'credit': 0, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_18(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((50, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], 'bank_payments': [], }, }) def test_19(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((50, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], }, }) def test_20(self): self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.bank_split_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': True}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, ], }, 'cash_statement': [], 'bank_payments': [ ((50, ), { 'line_ids': [ {'account_id': self.bank_split_pm1.outstanding_account_id.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], }, }) def test_21(self): self._run_test({ 'payment_methods': self.cash_split_pm1 | self.pay_later_pm, 'orders': [ {'pos_order_lines_ui_args': [(self.product100, 1)], 'payments': [(self.cash_split_pm1, 50), (self.pay_later_pm, 50)], 'customer': self.customer, 'is_invoiced': False, 'uid': '00100-010-0001'}, ], 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 100, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((50, ), { 'line_ids': [ {'account_id': self.cash_split_pm1.journal_id.default_account_id.id, 'partner_id': self.customer.id, 'debit': 50, 'credit': 0, 'reconciled': False}, {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 50, 'reconciled': True}, ] }) ], 'bank_payments': [], }, })
55.300509
32,572
31,480
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSProductsWithTax(TestPoSCommon): """ Test normal configuration PoS selling products with tax """ def setUp(self): super(TestPoSProductsWithTax, self).setUp() self.config = self.basic_config self.product1 = self.create_product( 'Product 1', self.categ_basic, 10.0, 5.0, tax_ids=self.taxes['tax7'].ids, ) self.product2 = self.create_product( 'Product 2', self.categ_basic, 20.0, 10.0, tax_ids=self.taxes['tax10'].ids, ) self.product3 = self.create_product( 'Product 3', self.categ_basic, 30.0, 15.0, tax_ids=self.taxes['tax_group_7_10'].ids, ) self.product4 = self.create_product( 'Product 4', self.categ_basic, 54.99, tax_ids=[self.taxes['tax_fixed006'].id, self.taxes['tax_fixed012'].id, self.taxes['tax21'].id], ) self.adjust_inventory([self.product1, self.product2, self.product3], [100, 50, 50]) def test_orders_no_invoiced(self): """ Test for orders without invoice Orders ====== +---------+----------+-----------+----------+-----+---------+-----------------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+-----------+----------+-----+---------+-----------------------+--------+ | order 1 | cash | no | product1 | 10 | 100 | 7 | 107 | | | | | product2 | 5 | 90.91 | 9.09 | 100 | +---------+----------+-----------+----------+-----+---------+-----------------------+--------+ | order 2 | cash | no | product2 | 7 | 127.27 | 12.73 | 140 | | | | | product3 | 4 | 109.09 | 10.91[10%] + 7.64[7%] | 127.64 | +---------+----------+-----------+----------+-----+---------+-----------------------+--------+ | order 3 | bank | no | product1 | 1 | 10 | 0.7 | 10.7 | | | | | product2 | 3 | 54.55 | 5.45 | 60 | | | | | product3 | 5 | 136.36 | 13.64[10%] + 9.55[7%] | 159.55 | +---------+----------+-----------+----------+-----+---------+-----------------------+--------+ Calculated taxes ================ total tax 7% only + group tax (10+7%) (7 + 0.7) + (7.64 + 9.55) = 7.7 + 17.19 = 24.89 total tax 10% only + group tax (10+7%) (9.09 + 12.73 + 5.45) + (10.91 + 13.64) = 27.27 + 24.55 = 51.82 Thus, manually_calculated_taxes = (-24,89, -51.82) """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, 'Total order amount should be equal to the total payment amount.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 5)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 7), (self.product3, 4)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 1), (self.product3, 5), (self.product2, 3)], 'payments': [(self.bank_pm1, 230.25)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 24.89, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 51.82, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 110, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 272.73, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 245.45, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 230.25, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 474.64, 'credit': 0, 'reconciled': True}, ], }, 'cash_statement': [ ((474.64, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 474.64, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 474.64, 'reconciled': True}, ] }), ], 'bank_payments': [ ((230.25, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 230.25, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 230.25, 'reconciled': True}, ] }), ], }, }) def test_orders_with_invoiced(self): """ Test for orders: one with invoice Orders ====== +---------+----------+---------------+----------+-----+---------+---------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+---------------+----------+-----+---------+---------------+--------+ | order 1 | cash | no | product1 | 6 | 60 | 4.2 | 64.2 | | | | | product2 | 3 | 54.55 | 5.45 | 60 | | | | | product3 | 1 | 27.27 | 2.73 + 1.91 | 31.91 | +---------+----------+---------------+----------+-----+---------+---------------+--------+ | order 2 | bank | no | product1 | 1 | 10 | 0.7 | 10.7 | | | | | product2 | 20 | 363.64 | 36.36 | 400 | +---------+----------+---------------+----------+-----+---------+---------------+--------+ | order 3 | bank | yes, customer | product1 | 10 | 100 | 7 | 107 | | | | | product3 | 10 | 272.73 | 27.27 + 19.09 | 319.09 | +---------+----------+---------------+----------+-----+---------+---------------+--------+ Calculated taxes ================ total tax 7% only 4.2 + 0.7 => 4.9 + 1.91 = 6.81 total tax 10% only 5.45 + 36.36 => 41.81 + 2.73 = 44.54 Thus, manually_calculated_taxes = (-6.81, -44.54) """ def _before_closing_cb(): # check values before closing the session self.assertEqual(4, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # check account move in the invoiced order invoiced_orders = self.pos_session.order_ids.filtered(lambda order: order.is_invoiced) self.assertEqual(2, len(invoiced_orders), 'Only one order is invoiced in this test.') invoices = invoiced_orders.mapped('account_move') self.assertAlmostEqual(sum(invoices.mapped('amount_total')), 481.08) def _after_closing_cb(): session_move = self.pos_session.move_id tax_lines = session_move.line_ids.filtered(lambda line: line.account_id == self.tax_received_account) manually_calculated_taxes = (-6.81, -44.54) self.assertAlmostEqual(sum(manually_calculated_taxes), sum(tax_lines.mapped('balance'))) for t1, t2 in zip(sorted(manually_calculated_taxes), sorted(tax_lines.mapped('balance'))): self.assertAlmostEqual(t1, t2, msg='Taxes should be correctly combined.') base_amounts = (97.27, 445.46) # computation does not include invoiced order. self.assertAlmostEqual(sum(base_amounts), sum(tax_lines.mapped('tax_base_amount'))) self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product3, 1), (self.product1, 6), (self.product2, 3)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 20), (self.product1, 1)], 'payments': [(self.bank_pm1, 410.7)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 10), (self.product3, 10)], 'payments': [(self.bank_pm1, 426.09)], 'customer': self.customer, 'is_invoiced': True, 'uid': '09876-098-0987'}, {'pos_order_lines_ui_args': [(self.product4, 1)], 'payments': [(self.bank_pm1, 54.99)], 'customer': self.customer, 'is_invoiced': True, 'uid': '00100-010-0004'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '09876-098-0987': { 'payments': [ ((self.bank_pm1, 426.09), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 426.09, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 426.09, 'credit': 0, 'reconciled': False}, ] }), ], }, '00100-010-0004': { 'payments': [ ((self.bank_pm1, 54.99), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 54.99, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 54.99, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'after_closing_cb': _after_closing_cb, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 6.81, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 0, 'credit': 44.54, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 27.27, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 70, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 418.19, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 891.78, 'credit': 0, 'reconciled': True}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 156.11, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 481.08, 'reconciled': True}, ], }, 'cash_statement': [ ((156.11, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 156.11, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 156.11, 'reconciled': True}, ] }), ], 'bank_payments': [ ((891.78, ), { 'line_ids': [ {'account_id': self.bank_pm1.outstanding_account_id.id, 'partner_id': False, 'debit': 891.78, 'credit': 0, 'reconciled': False}, {'account_id': self.bank_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 891.78, 'reconciled': True}, ] }), ], }, }) def test_return_order(self): """ Test return order Order (invoiced) ====== +----------+----------+---------------+----------+-----+---------+-------------+-------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +----------+----------+---------------+----------+-----+---------+-------------+-------+ | order 1 | cash | yes, customer | product1 | 3 | 30 | 2.1 | 32.1 | | | | | product2 | 2 | 36.36 | 3.64 | 40 | | | | | product3 | 1 | 27.27 | 2.73 + 1.91 | 31.91 | +----------+----------+---------------+----------+-----+---------+-------------+-------+ The order is invoiced so the tax of the invoiced order is in the account_move of the order. However, the return order is not invoiced, thus, the journal items are in the session_move, which will contain the tax lines of the returned products. manually_calculated_taxes = (4.01, 6.37) """ def _before_closing_cb(): # check values before closing the session self.assertEqual(1, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') # return order order_to_return = self.pos_session.order_ids.filtered(lambda order: '12345-123-1234' in order.pos_reference) order_to_return.refund() refund_order = self.pos_session.order_ids.filtered(lambda order: order.state == 'draft') context_make_payment = {"active_ids": [refund_order.id], "active_id": refund_order.id} make_payment = self.env['pos.make.payment'].with_context(context_make_payment).create({ 'payment_method_id': self.cash_pm1.id, 'amount': -104.01, }) make_payment.check() self.assertEqual(refund_order.state, 'paid', 'Payment is registered, order should be paid.') self.assertAlmostEqual(refund_order.amount_paid, -104.01, msg='Amount paid for return order should be negative.') def _after_closing_cb(): manually_calculated_taxes = (4.01, 6.37) # should be positive since it is return order tax_lines = self.pos_session.move_id.line_ids.filtered(lambda line: line.account_id == self.tax_received_account) self.assertAlmostEqual(sum(manually_calculated_taxes), sum(tax_lines.mapped('balance'))) for t1, t2 in zip(sorted(manually_calculated_taxes), sorted(tax_lines.mapped('balance'))): self.assertAlmostEqual(t1, t2, msg='Taxes should be correctly combined and should be debit.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 3), (self.product2, 2), (self.product3, 1)], 'payments': [(self.cash_pm1, 104.01)], 'customer': self.customer, 'is_invoiced': True, 'uid': '12345-123-1234'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '12345-123-1234': { 'payments': [ ((self.cash_pm1, 104.01), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 104.01, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 104.01, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'after_closing_cb': _after_closing_cb, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 4.01, 'credit': 0, 'reconciled': False}, {'account_id': self.tax_received_account.id, 'partner_id': False, 'debit': 6.37, 'credit': 0, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 30, 'credit': 0, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 36.36, 'credit': 0, 'reconciled': False}, {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 27.27, 'credit': 0, 'reconciled': False}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 104.01, 'reconciled': True}, ], }, 'cash_statement': [], 'bank_payments': [], }, }) def test_pos_create_correct_account_move(self): """ Test for orders with global rounding disabled Orders ====== +---------+----------+-----------+----------+------+----------+------------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+-----------+----------+------+----------+------------------+--------+ | order 1 | cash | no | product1 | 1 | 10.0 | 2.10 | 12.10 | | | | | product2 | -1 | -5.0 | -1.05 | -6.05 | +---------+----------+-----------+----------+------+----------+------------------+--------+ """ tax_21_incl = self.taxes['tax21'] product1 = self.create_product( name='Product 1', category=self.categ_basic, lst_price=12.10, tax_ids=tax_21_incl.ids, ) product2 = self.create_product( name='Product 2', category=self.categ_basic, lst_price=6.05, tax_ids=tax_21_incl.ids, ) self.open_new_session() self.env['pos.order'].create_from_ui([self.create_ui_order_data([ (product1, 1), (product2, -1), ])]) self.pos_session.action_pos_session_validate() lines = self.pos_session.move_id.line_ids.sorted('balance') self.assertEqual(2, len(lines.filtered(lambda l: l.tax_ids)), "Taxes should have been set on 2 lines") self.assertEqual(4, len(lines.filtered(lambda l: l.tax_tag_ids)), "Tags should have been set on 4 lines") self.assertRecordValues(lines, [ {'account_id': self.sale_account.id, 'balance': -10.0, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_invoice_base.ids}, {'account_id': self.tax_received_account.id, 'balance': -2.10, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_invoice_tax.ids}, {'account_id': self.tax_received_account.id, 'balance': 1.05, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_refund_tax.ids}, {'account_id': self.sale_account.id, 'balance': 5.00, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_refund_base.ids}, {'account_id': self.cash_pm1.receivable_account_id.id, 'balance': 6.05, 'tax_ids': [], 'tax_tag_ids': []}, ]) def test_pos_create_account_move_round_globally(self): """ Test for orders with global rounding enabled Orders ====== +---------+----------+-----------+----------+------+----------+------------------+--------+ | order | payments | invoiced? | product | qty | untaxed | tax | total | +---------+----------+-----------+----------+------+----------+------------------+--------+ | order 1 | cash | no | product1 | 1 | 10.0 | 2.10 | 12.10 | | | | | product2 | -1 | -5.0 | -1.05 | -6.05 | +---------+----------+-----------+----------+------+----------+------------------+--------+ """ tax_21_incl = self.taxes['tax21'] tax_21_incl.company_id.tax_calculation_rounding_method = 'round_globally' product1 = self.create_product( name='Product 1', category=self.categ_basic, lst_price=12.10, tax_ids=tax_21_incl.ids, ) product2 = self.create_product( name='Product 2', category=self.categ_basic, lst_price=6.05, tax_ids=tax_21_incl.ids, ) self.open_new_session() self.env['pos.order'].create_from_ui([self.create_ui_order_data([ (product1, 1), (product2, -1), ])]) self.pos_session.action_pos_session_validate() lines = self.pos_session.move_id.line_ids.sorted('balance') self.assertEqual(2, len(lines.filtered(lambda l: l.tax_ids)), "Taxes should have been set on 2 lines") self.assertEqual(4, len(lines.filtered(lambda l: l.tax_tag_ids)), "Tags should have been set on 4 lines") self.assertRecordValues(lines, [ {'account_id': self.sale_account.id, 'balance': -10.0, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_invoice_base.ids}, {'account_id': self.tax_received_account.id, 'balance': -2.10, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_invoice_tax.ids}, {'account_id': self.tax_received_account.id, 'balance': 1.05, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_refund_tax.ids}, {'account_id': self.sale_account.id, 'balance': 5.00, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_refund_base.ids}, {'account_id': self.cash_pm1.receivable_account_id.id, 'balance': 6.05, 'tax_ids': [], 'tax_tag_ids': []}, ]) def test_pos_create_correct_account_move_round_globally_discount(self): """ Test for orders with global rounding enabled Orders ====== +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ | order | payments | inv? | product | qty | original price unit | Discount | price unit after discount | untaxed | tax | total | +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ | order 1 | cash | no | product1 | 1 | 12.10 | 5% | 10.89 | 9.00 | 1.89 | 10.89 | | | | | product2 | -1 | 6.05 | 5% | 5.45 | -4.50 | -0.95 | -5.445 | +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ """ tax_21_incl = self.taxes['tax21'] tax_21_incl.company_id.tax_calculation_rounding_method = 'round_globally' product1 = self.create_product( name='Product 1', category=self.categ_basic, lst_price=12.10, tax_ids=tax_21_incl.ids, ) product2 = self.create_product( name='Product 2', category=self.categ_basic, lst_price=6.05, tax_ids=tax_21_incl.ids, ) self.open_new_session() self.env['pos.order'].create_from_ui([self.create_ui_order_data([ (product1, 1, 10), (product2, -1, 10), ])]) self.pos_session.action_pos_session_validate() lines = self.pos_session.move_id.line_ids.sorted('balance') self.assertEqual(2, len(lines.filtered(lambda l: l.tax_ids)), "Taxes should have been set on 2 lines") self.assertEqual(4, len(lines.filtered(lambda l: l.tax_tag_ids)), "Tags should have been set on 4 lines") self.assertRecordValues(lines, [ {'account_id': self.sale_account.id, 'balance': - 9.0, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_invoice_base.ids}, {'account_id': self.tax_received_account.id, 'balance': -1.89, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_invoice_tax.ids}, {'account_id': self.tax_received_account.id, 'balance': 0.95, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_refund_tax.ids}, {'account_id': self.sale_account.id, 'balance': 4.5, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_refund_base.ids}, {'account_id': self.cash_pm1.receivable_account_id.id, 'balance': 5.44, 'tax_ids': [], 'tax_tag_ids': []}, ]) def test_pos_create_correct_account_move_round_globally_discount_real_use_case(self): """ Test for orders with global rounding enabled Orders ====== +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ | order | payments | inv? | product | qty | original price unit | Discount | price unit after discount | untaxed | tax | total | +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ | order 1 | cash | no | product1 | 6 | 11.80 | 5% | 11.21 | 55.59 | 11.67 | 67.26 | | | | | product2 | -6 | 15.30 | 5% | 14.535 | -72.07 | -15.14 | -87.21 | +---------+----------+------+----------+------+---------------------+-----------+---------------------------+---------+--------+--------+ """ tax_21_incl = self.taxes['tax21'] tax_21_incl.company_id.tax_calculation_rounding_method = 'round_globally' product1 = self.create_product( name='Product 1', category=self.categ_basic, lst_price=11.80, tax_ids=tax_21_incl.ids, ) product2 = self.create_product( name='Product 2', category=self.categ_basic, lst_price=15.30, tax_ids=tax_21_incl.ids, ) self.open_new_session() self.env['pos.order'].create_from_ui([self.create_ui_order_data([ (product1, 6, 5), (product2, -6, 5), ])]) self.pos_session.action_pos_session_validate() lines = self.pos_session.move_id.line_ids.sorted('balance') self.assertEqual(2, len(lines.filtered(lambda l: l.tax_ids)), "Taxes should have been set on 2 lines") self.assertEqual(4, len(lines.filtered(lambda l: l.tax_tag_ids)), "Tags should have been set on 4 lines") self.assertRecordValues(lines, [ {'account_id': self.sale_account.id, 'balance': -55.59, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_invoice_base.ids}, {'account_id': self.cash_pm1.receivable_account_id.id, 'balance': -19.95, 'tax_ids': [], 'tax_tag_ids': []}, {'account_id': self.tax_received_account.id, 'balance': -11.67, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_invoice_tax.ids}, {'account_id': self.tax_received_account.id, 'balance': 15.14, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_refund_tax.ids}, {'account_id': self.sale_account.id, 'balance': 72.07, 'tax_ids': tax_21_incl.ids, 'tax_tag_ids': self.tax_tag_refund_base.ids}, ]) def test_fixed_tax_positive_qty(self): fixed_tax = self.env['account.tax'].create({ 'name': 'fixed amount tax', 'amount_type': 'fixed', 'amount': 1, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, self.tax_tag_invoice_base.ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': self.tax_received_account.id, 'tag_ids': [(6, 0, self.tax_tag_invoice_tax.ids)], }), ], }) zero_amount_product = self.env['product.product'].create({ 'name': 'Zero Amount Product', 'available_in_pos': True, 'list_price': 0, 'taxes_id': [(6, 0, [fixed_tax.id])], }) self.open_new_session() self.env['pos.order'].create_from_ui([self.create_ui_order_data([ (zero_amount_product, 1), ])]) self.pos_session.action_pos_session_validate() lines = self.pos_session.move_id.line_ids.sorted('balance') self.assertRecordValues(lines, [ {'account_id': self.tax_received_account.id, 'balance': -1}, {'account_id': self.sale_account.id, 'balance': 0}, {'account_id': self.cash_pm1.receivable_account_id.id, 'balance': 1}, ])
58.18854
31,480
15,246
py
PYTHON
15.0
# -*- coding: utf-8 -*- import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPosMargin(TestPoSCommon): """ Test the margin computation on orders with basic configuration The tests contain the base scenarios. """ def setUp(self): super(TestPosMargin, self).setUp() self.config = self.basic_config self.stock_location = self.env['stock.warehouse'].create({ 'partner_id': self.env.user.partner_id.id, 'name': 'Stock location', 'code': 'WH' }).lot_stock_id self.customer_location = self.env.ref('stock.stock_location_customers') self.supplier_location = self.env.ref('stock.stock_location_suppliers') self.uom_unit = self.env.ref('uom.product_uom_unit') def test_positive_margin(self): """ Test margin where it should be more than zero """ product1 = self.create_product('Product 1', self.categ_basic, 10, 5) product2 = self.create_product('Product 2', self.categ_basic, 50, 30) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, 5) self.assertEqual(self.pos_session.order_ids[1].margin, 20) self.assertEqual(self.pos_session.order_ids[2].margin, 50) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.4) self.assertEqual(round(self.pos_session.order_ids[2].margin_percent, 2), 0.42) # close session self.pos_session.action_pos_session_validate() def test_negative_margin(self): """ Test margin where it should be less than zero """ product1 = self.create_product('Product 1', self.categ_basic, 10, 15) product2 = self.create_product('Product 2', self.categ_basic, 50, 100) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, -5) self.assertEqual(self.pos_session.order_ids[1].margin, -50) self.assertEqual(self.pos_session.order_ids[2].margin, -110) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, -0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, -1) self.assertEqual(round(self.pos_session.order_ids[2].margin_percent, 2), -0.92) # close session self.pos_session.action_pos_session_validate() def test_full_margin(self): """ Test margin where the product cost is always 0 """ product1 = self.create_product('Product 1', self.categ_basic, 10) product2 = self.create_product('Product 2', self.categ_basic, 50) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, 10) self.assertEqual(self.pos_session.order_ids[1].margin, 50) self.assertEqual(self.pos_session.order_ids[2].margin, 120) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 1) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 1) self.assertEqual(self.pos_session.order_ids[2].margin_percent, 1) # close session self.pos_session.action_pos_session_validate() def test_tax_margin(self): """ Test margin with tax on products Product 1 price without tax = 10 Product 2 price without tax = 50 """ product1 = self.create_product('Product 1', self.categ_basic, 10, 5, self.taxes['tax7'].ids) product2 = self.create_product('Product 2', self.categ_basic, 55, 30, self.taxes['tax10'].ids) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, 5) self.assertEqual(self.pos_session.order_ids[1].margin, 20) self.assertEqual(self.pos_session.order_ids[2].margin, 50) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.4) self.assertEqual(round(self.pos_session.order_ids[2].margin_percent, 2), 0.42) # close session self.pos_session.action_pos_session_validate() def test_other_currency_margin(self): """ Test margin with tax on products and with different currency The currency rate is 0.5 so the product price is halved in this currency. """ # change the config current_config = self.config self.config = self.other_currency_config # same parameters as test_positive_margin product1 = self.create_product('Product 1', self.categ_basic, 10, 5) product2 = self.create_product('Product 2', self.categ_basic, 50, 30) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins in the config currency self.assertEqual(self.pos_session.order_ids[0].margin, 2.5) self.assertEqual(self.pos_session.order_ids[1].margin, 10) self.assertEqual(self.pos_session.order_ids[2].margin, 25) # check margins percent which should be the same as test_positive_margin self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.4) self.assertEqual(round(self.pos_session.order_ids[2].margin_percent, 2), 0.42) # close session self.pos_session.action_pos_session_validate() # set the config back self.config = current_config def test_tax_and_other_currency_margin(self): """ Test margin with different currency between products and config with taxes. Product 1 price without tax = 10 Product 2 price without tax = 50 The currency rate is 0.5 so the product price is halved in this currency. """ # change the config current_config = self.config self.config = self.other_currency_config product1 = self.create_product('Product 1', self.categ_basic, 10, 5, self.taxes['tax7'].ids) product2 = self.create_product('Product 2', self.categ_basic, 55, 30, self.taxes['tax10'].ids) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1)]), self.create_ui_order_data([(product2, 1)]), self.create_ui_order_data([(product1, 2), (product2, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins in the config currency self.assertEqual(self.pos_session.order_ids[0].margin, 2.5) self.assertEqual(self.pos_session.order_ids[1].margin, 10) self.assertEqual(self.pos_session.order_ids[2].margin, 25) # check margins percent which should be the same as test_tax_margin self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.4) self.assertEqual(self.pos_session.order_ids[2].margin_percent, 0.4167) # close session self.pos_session.action_pos_session_validate() # set the config back self.config = current_config def test_return_margin(self): """ Test margin where we return product (negative line quantity) """ product1 = self.create_product('Product 1', self.categ_basic, 10, 5) product2 = self.create_product('Product 2', self.categ_basic, 50, 30) # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, -1)]), self.create_ui_order_data([(product2, -1)]), self.create_ui_order_data([(product1, -2), (product2, -2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, -5) self.assertEqual(self.pos_session.order_ids[1].margin, -20) self.assertEqual(self.pos_session.order_ids[2].margin, -50) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.5) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.4) self.assertEqual(round(self.pos_session.order_ids[2].margin_percent, 2), 0.42) # close session self.pos_session.action_pos_session_validate() def test_fifo_margin_real_time(self): """ Test margin where there is product in FIFO with stock update in real time """ product1 = self.create_product('Product 1', self.categ_anglo, 10, 5) product2 = self.create_product('Product 2', self.categ_basic, 50, 30) move1 = self.env['stock.move'].create({ 'name': 'IN 2 unit @ 3 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.stock_location.id, 'product_id': product1.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 2, 'price_unit': 3, }).sudo() move1._action_confirm() move1._action_assign() move1.move_line_ids.qty_done = 2 move1._action_done() move2 = self.env['stock.move'].create({ 'name': 'IN 1 unit @ 7 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.stock_location.id, 'product_id': product1.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 1, 'price_unit': 7, }).sudo() move2._action_confirm() move2._action_assign() move2.move_line_ids.qty_done = 1 move2._action_done() # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1), (product2, 1)]), self.create_ui_order_data([(product1, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins self.assertEqual(self.pos_session.order_ids[0].margin, 27) self.assertEqual(self.pos_session.order_ids[1].margin, 10) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.45) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.5) # close session self.pos_session.action_pos_session_validate() def test_avco_margin_closing_time(self): """ Test margin where there is product in AVCO with stock update in closing """ self.categ_anglo.property_cost_method = 'average' product1 = self.create_product('Product 1', self.categ_anglo, 10, 5) product2 = self.create_product('Product 2', self.categ_basic, 50, 30) self.env.company.point_of_sale_update_stock_quantities = 'closing' move1 = self.env['stock.move'].create({ 'name': 'IN 2 unit @ 3 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.stock_location.id, 'product_id': product1.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 2, 'price_unit': 3, }).sudo() move1._action_confirm() move1._action_assign() move1.move_line_ids.qty_done = 2 move1._action_done() move2 = self.env['stock.move'].create({ 'name': 'IN 1 unit @ 6 per unit', 'location_id': self.supplier_location.id, 'location_dest_id': self.stock_location.id, 'product_id': product1.id, 'product_uom': self.uom_unit.id, 'product_uom_qty': 1, 'price_unit': 6, }).sudo() move2._action_confirm() move2._action_assign() move2.move_line_ids.qty_done = 1 move2._action_done() # open a session self.open_new_session() # create orders orders = [self.create_ui_order_data([(product1, 1), (product2, 1)]), self.create_ui_order_data([(product1, 2)])] # sync orders self.env['pos.order'].create_from_ui(orders) # check margins which are not really computed so it should be 0 self.assertEqual(self.pos_session.order_ids[0].margin, 0) self.assertEqual(self.pos_session.order_ids[1].margin, 0) # check margins percent (same as above) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0) # close session total_cash_payment = sum(self.pos_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')) self.pos_session.post_closing_cash_details(total_cash_payment) self.pos_session.close_session_from_ui() # check margins self.assertEqual(self.pos_session.order_ids[0].margin, 26) self.assertEqual(self.pos_session.order_ids[1].margin, 12) # check margins percent self.assertEqual(self.pos_session.order_ids[0].margin_percent, 0.4333) self.assertEqual(self.pos_session.order_ids[1].margin_percent, 0.6) self.env.company.point_of_sale_update_stock_quantities = 'real'
38.115
15,246
13,937
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import tools import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSStock(TestPoSCommon): """ Tests for anglo saxon accounting scenario. """ def setUp(self): super(TestPoSStock, self).setUp() self.config = self.basic_config self.product1 = self.create_product('Product 1', self.categ_anglo, 10.0, 5.0) self.product2 = self.create_product('Product 2', self.categ_anglo, 20.0, 10.0) self.product3 = self.create_product('Product 3', self.categ_basic, 30.0, 15.0) # start inventory with 10 items for each product self.adjust_inventory([self.product1, self.product2, self.product3], [10, 10, 10]) # change cost(standard_price) of anglo products # then set inventory from 10 -> 15 self.product1.write({'standard_price': 6.0}) self.product2.write({'standard_price': 6.0}) self.adjust_inventory([self.product1, self.product2, self.product3], [15, 15, 15]) # change cost(standard_price) of anglo products # then set inventory from 15 -> 25 self.product1.write({'standard_price': 13.0}) self.product2.write({'standard_price': 13.0}) self.adjust_inventory([self.product1, self.product2, self.product3], [25, 25, 25]) self.output_account = self.categ_anglo.property_stock_account_output_categ_id self.expense_account = self.categ_anglo.property_account_expense_categ_id self.valuation_account = self.categ_anglo.property_stock_valuation_account_id def test_01_orders_no_invoiced(self): """ Orders ====== +---------+----------+-----+-------------+------------+ | order | product | qty | total price | total cost | +---------+----------+-----+-------------+------------+ | order 1 | product1 | 10 | 100.0 | 50.0 | -> 10 items at cost of 5.0 is consumed, remains 5 items at 6.0 and 10 items at 13.0 | | product2 | 10 | 200.0 | 100.0 | -> 10 items at cost of 10.0 is consumed, remains 5 items at 6.0 and 10 items at 13.0 +---------+----------+-----+-------------+------------+ | order 2 | product2 | 7 | 140.0 | 56.0 | -> 5 items at cost of 6.0 and 2 items at cost of 13.0, remains 8 items at cost of 13.0 | | product3 | 7 | 210.0 | 0.0 | +---------+----------+-----+-------------+------------+ | order 3 | product1 | 6 | 60.0 | 43.0 | -> 5 items at cost of 6.0 and 1 item at cost of 13.0, remains 9 items at cost of 13.0 | | product2 | 6 | 120.0 | 78.0 | -> 6 items at cost of 13.0, remains 2 items at cost of 13.0 | | product3 | 6 | 180.0 | 0.0 | +---------+----------+-----+-------------+------------+ Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale_account | -1010.0 | | pos_receivable-cash | 1010.0 | | expense_account | 327.0 | | output_account | -327.0 | +---------------------+---------+ | Total balance | 0.00 | +---------------------+---------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self.assertAlmostEqual(orders_total, 1010.0, msg='The orders\'s total amount should equal the computed.') # check product qty_available after syncing the order self.assertEqual(self.product1.qty_available, 9) self.assertEqual(self.product2.qty_available, 2) self.assertEqual(self.product3.qty_available, 12) # picking and stock moves should be in done state for order in self.pos_session.order_ids: self.assertEqual(order.picking_ids[0].state, 'done', 'Picking should be in done state.') self.assertTrue(all(state == 'done' for state in order.picking_ids[0].move_lines.mapped('state')), 'Move Lines should be in done state.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 7), (self.product3, 7)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 6), (self.product2, 6), (self.product3, 6)], 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': {}, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 1010.0, 'reconciled': False}, {'account_id': self.expense_account.id, 'partner_id': False, 'debit': 327, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 1010.0, 'credit': 0, 'reconciled': True}, {'account_id': self.output_account.id, 'partner_id': False, 'debit': 0, 'credit': 327, 'reconciled': True}, ], }, 'cash_statement': [ ((1010.0, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 1010.0, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 1010.0, 'reconciled': True}, ] }), ], 'bank_payments': [], }, }) def test_02_orders_with_invoice(self): """ Orders ====== Same with test_01 but order 3 is invoiced. Expected Result =============== +---------------------+---------+ | account | balance | +---------------------+---------+ | sale_account | -650.0 | | pos_receivable-cash | 1010.0 | | receivable | -360.0 | | expense_account | 206.0 | | output_account | -206.0 | +---------------------+---------+ | Total balance | 0.00 | +---------------------+---------+ """ def _before_closing_cb(): # check values before closing the session self.assertEqual(3, self.pos_session.order_count) orders_total = sum(order.amount_total for order in self.pos_session.order_ids) self.assertAlmostEqual(orders_total, self.pos_session.total_payments_amount, msg='Total order amount should be equal to the total payment amount.') self.assertAlmostEqual(orders_total, 1010.0, msg='The orders\'s total amount should equal the computed.') # check product qty_available after syncing the order self.assertEqual(self.product1.qty_available, 9) self.assertEqual(self.product2.qty_available, 2) self.assertEqual(self.product3.qty_available, 12) # picking and stock moves should be in done state for order in self.pos_session.order_ids: self.assertEqual(order.picking_ids[0].state, 'done', 'Picking should be in done state.') self.assertTrue(all(state == 'done' for state in order.picking_ids[0].move_lines.mapped('state')), 'Move Lines should be in done state.') self._run_test({ 'payment_methods': self.cash_pm1 | self.bank_pm1, 'orders': [ {'pos_order_lines_ui_args': [(self.product1, 10), (self.product2, 10)], 'uid': '00100-010-0001'}, {'pos_order_lines_ui_args': [(self.product2, 7), (self.product3, 7)], 'uid': '00100-010-0002'}, {'pos_order_lines_ui_args': [(self.product1, 6), (self.product2, 6), (self.product3, 6)], 'is_invoiced': True, 'customer': self.customer, 'uid': '00100-010-0003'}, ], 'before_closing_cb': _before_closing_cb, 'journal_entries_before_closing': { '00100-010-0003': { 'payments': [ ((self.cash_pm1, 360.0), { 'line_ids': [ {'account_id': self.c1_receivable.id, 'partner_id': self.customer.id, 'debit': 0, 'credit': 360.0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 360.0, 'credit': 0, 'reconciled': False}, ] }), ], }, }, 'journal_entries_after_closing': { 'session_journal_entry': { 'line_ids': [ {'account_id': self.sales_account.id, 'partner_id': False, 'debit': 0, 'credit': 650, 'reconciled': False}, {'account_id': self.expense_account.id, 'partner_id': False, 'debit': 206, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 1010.0, 'credit': 0, 'reconciled': True}, {'account_id': self.pos_receivable_account.id, 'partner_id': False, 'debit': 0, 'credit': 360, 'reconciled': True}, {'account_id': self.output_account.id, 'partner_id': False, 'debit': 0, 'credit': 206, 'reconciled': True}, ], }, 'cash_statement': [ ((1010.0, ), { 'line_ids': [ {'account_id': self.cash_pm1.journal_id.default_account_id.id, 'partner_id': False, 'debit': 1010.0, 'credit': 0, 'reconciled': False}, {'account_id': self.cash_pm1.receivable_account_id.id, 'partner_id': False, 'debit': 0, 'credit': 1010.0, 'reconciled': True}, ] }), ], 'bank_payments': [], }, }) def test_03_order_product_w_owner(self): """ Test order via POS a product having stock owner. """ group_owner = self.env.ref('stock.group_tracking_owner') self.env.user.write({'groups_id': [(4, group_owner.id)]}) self.product4 = self.create_product('Product 3', self.categ_basic, 30.0, 15.0) self.env['stock.quant'].with_context(inventory_mode=True).create({ 'product_id': self.product4.id, 'inventory_quantity': 10, 'location_id': self.stock_location_components.id, 'owner_id': self.partner_a.id, }).action_apply_inventory() self.open_new_session() # create orders orders = [] orders.append(self.create_ui_order_data([(self.product4, 1)])) # sync orders order = self.env['pos.order'].create_from_ui(orders) # check values before closing the session self.assertEqual(1, self.pos_session.order_count) # check product qty_available after syncing the order self.assertEqual(self.product4.qty_available, 9) # picking and stock moves should be in done state for order in self.pos_session.order_ids: self.assertEqual(order.picking_ids[0].state, 'done', 'Picking should be in done state.') self.assertTrue(all(state == 'done' for state in order.picking_ids[0].move_lines.mapped('state')), 'Move Lines should be in done state.') self.assertTrue(self.partner_a == order.picking_ids[0].move_lines[0].move_line_ids[0].owner_id, 'Move Lines Owner should be taken into account.') # close the session self.pos_session.action_pos_session_validate() def test_04_order_refund(self): self.categ4 = self.env['product.category'].create({ 'name': 'Category 4', 'property_cost_method': 'fifo', 'property_valuation': 'real_time', }) self.product4 = self.create_product('Product 4', self.categ4, 30.0, 15.0) self.open_new_session() orders = [] orders.append(self.create_ui_order_data([(self.product4, 1)])) order = self.env['pos.order'].create_from_ui(orders) refund_action = self.env['pos.order'].browse(order[0]['id']).refund() refund = self.env['pos.order'].browse(refund_action['res_id']) payment_context = {"active_ids": refund.ids, "active_id": refund.id} refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create({ 'amount': refund.amount_total, 'payment_method_id': self.cash_pm1.id, }) refund_payment.with_context(**payment_context).check() self.pos_session.action_pos_session_validate() expense_account_move_line = self.env['account.move.line'].search([('account_id', '=', self.expense_account.id)]) self.assertEqual(expense_account_move_line.balance, 0.0, "Expense account should be 0.0")
52.791667
13,937
1,861
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 PosOpenStatement(models.TransientModel): _name = 'pos.open.statement' _description = 'Point of Sale Open Statement' def open_statement(self): self.ensure_one() BankStatement = self.env['account.bank.statement'] journals = self.env['account.journal'].search([('journal_user', '=', True)]) if not journals: raise UserError(_('You have to define which payment method must be available in the point of sale by reusing existing bank and cash through "Accounting / Configuration / Journals / Journals". Select a journal and check the field "PoS Payment Method" from the "Point of Sale" tab. You can also create new payment methods directly from menu "PoS Backend / Configuration / Payment Methods".')) for journal in journals: if journal.sequence_id: number = journal.sequence_id.next_by_id() else: raise UserError(_("No sequence defined on the journal")) BankStatement += BankStatement.create({'journal_id': journal.id, 'user_id': self.env.uid, 'name': number}) tree_id = self.env.ref('account.view_bank_statement_tree').id form_id = self.env.ref('account.view_bank_statement_form').id search_id = self.env.ref('account.view_bank_statement_search').id return { 'type': 'ir.actions.act_window', 'name': _('List of Cash Registers'), 'view_mode': 'tree,form', 'res_model': 'account.bank.statement', 'domain': str([('id', 'in', BankStatement.ids)]), 'views': [(tree_id, 'tree'), (form_id, 'form')], 'search_view_id': [search_id], }
48.973684
1,861
1,310
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, _ from odoo.exceptions import UserError from odoo.addons.account.wizard.pos_box import CashBox class PosBox(CashBox): _register = False def run(self): active_model = self.env.context.get('active_model', False) active_ids = self.env.context.get('active_ids', []) if active_model == 'pos.session': bank_statements = [session.cash_register_id for session in self.env[active_model].browse(active_ids) if session.cash_register_id] if not bank_statements: raise UserError(_("There is no cash register for this PoS Session")) return self._run(bank_statements) else: return super(PosBox, self).run() class PosBoxOut(PosBox): _inherit = 'cash.box.out' def _calculate_values_for_statement_line(self, record): values = super(PosBoxOut, self)._calculate_values_for_statement_line(record) active_model = self.env.context.get('active_model', False) active_ids = self.env.context.get('active_ids', []) if active_model == 'pos.session' and active_ids: values['ref'] = self.env[active_model].browse(active_ids)[0].name return values
37.428571
1,310
1,969
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 PosDetails(models.TransientModel): _name = 'pos.details.wizard' _description = 'Point of Sale Details Report' def _default_start_date(self): """ Find the earliest start_date of the latests sessions """ # restrict to configs available to the user config_ids = self.env['pos.config'].search([]).ids # exclude configs has not been opened for 2 days self.env.cr.execute(""" SELECT max(start_at) as start, config_id FROM pos_session WHERE config_id = ANY(%s) AND start_at > (NOW() - INTERVAL '2 DAYS') GROUP BY config_id """, (config_ids,)) latest_start_dates = [res['start'] for res in self.env.cr.dictfetchall()] # earliest of the latest sessions return latest_start_dates and min(latest_start_dates) or fields.Datetime.now() start_date = fields.Datetime(required=True, default=_default_start_date) end_date = fields.Datetime(required=True, default=fields.Datetime.now) pos_config_ids = fields.Many2many('pos.config', 'pos_detail_configs', default=lambda s: s.env['pos.config'].search([])) @api.onchange('start_date') def _onchange_start_date(self): if self.start_date and self.end_date and self.end_date < self.start_date: self.end_date = self.start_date @api.onchange('end_date') def _onchange_end_date(self): if self.end_date and self.end_date < self.start_date: self.start_date = self.end_date def generate_report(self): data = {'date_start': self.start_date, 'date_stop': self.end_date, 'config_ids': self.pos_config_ids.ids} return self.env.ref('point_of_sale.sale_details_report').report_action([], data=data)
41.893617
1,969
2,926
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.tools import float_is_zero class PosMakePayment(models.TransientModel): _name = 'pos.make.payment' _description = 'Point of Sale Make Payment Wizard' def _default_config(self): active_id = self.env.context.get('active_id') if active_id: return self.env['pos.order'].browse(active_id).session_id.config_id return False def _default_amount(self): active_id = self.env.context.get('active_id') if active_id: order = self.env['pos.order'].browse(active_id) return order.amount_total - order.amount_paid return False def _default_payment_method(self): active_id = self.env.context.get('active_id') if active_id: order_id = self.env['pos.order'].browse(active_id) return order_id.session_id.payment_method_ids.sorted(lambda pm: pm.is_cash_count, reverse=True)[:1] return False config_id = fields.Many2one('pos.config', string='Point of Sale Configuration', required=True, default=_default_config) amount = fields.Float(digits=0, required=True, default=_default_amount) payment_method_id = fields.Many2one('pos.payment.method', string='Payment Method', required=True, default=_default_payment_method) payment_name = fields.Char(string='Payment Reference') payment_date = fields.Datetime(string='Payment Date', required=True, default=lambda self: fields.Datetime.now()) def check(self): """Check the order: if the order is not paid: continue payment, if the order is paid print ticket. """ self.ensure_one() order = self.env['pos.order'].browse(self.env.context.get('active_id', False)) currency = order.currency_id init_data = self.read()[0] if not float_is_zero(init_data['amount'], precision_rounding=currency.rounding): order.add_payment({ 'pos_order_id': order.id, 'amount': order._get_rounded_amount(init_data['amount']), 'name': init_data['payment_name'], 'payment_method_id': init_data['payment_method_id'][0], }) if order._is_pos_order_paid(): order.action_pos_order_paid() order._create_order_picking() order._compute_total_cost_in_real_time() return {'type': 'ir.actions.act_window_close'} return self.launch_payment() def launch_payment(self): return { 'name': _('Payment'), 'view_mode': 'form', 'res_model': 'pos.make.payment', 'view_id': False, 'target': 'new', 'views': False, 'type': 'ir.actions.act_window', 'context': self.env.context, }
39.013333
2,926
755
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 PosCloseSessionWizard(models.TransientModel): _name = "pos.close.session.wizard" _description = "Close Session Wizard" amount_to_balance = fields.Float("Amount to balance") account_id = fields.Many2one("account.account", "Destination account") account_readonly = fields.Boolean("Destination account is readonly") message = fields.Text("Information message") def close_session(self): session = self.env["pos.session"].browse(self.env.context["active_ids"]) return session.action_pos_session_closing_control( self.account_id, self.amount_to_balance )
37.75
755
1,272
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 Digest(models.Model): _inherit = 'digest.digest' kpi_pos_total = fields.Boolean('POS Sales') kpi_pos_total_value = fields.Monetary(compute='_compute_kpi_pos_total_value') def _compute_kpi_pos_total_value(self): if not self.env.user.has_group('point_of_sale.group_pos_user'): raise AccessError(_("Do not have access, skip this data for user's digest email")) for record in self: start, end, company = record._get_kpi_compute_parameters() record.kpi_pos_total_value = sum(self.env['pos.order'].search([ ('date_order', '>=', start), ('date_order', '<', end), ('state', 'not in', ['draft', 'cancel', 'invoiced']), ('company_id', '=', company.id) ]).mapped('amount_total')) def _compute_kpis_actions(self, company, user): res = super(Digest, self)._compute_kpis_actions(company, user) res['kpi_pos_total'] = 'point_of_sale.action_pos_sale_graph&menu_id=%s' % self.env.ref('point_of_sale.menu_point_root').id return res
43.862069
1,272
1,612
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import _, api, models from odoo.exceptions import UserError from odoo.tools import split_every class AccountTax(models.Model): _inherit = 'account.tax' def write(self, vals): forbidden_fields = { 'amount_type', 'amount', 'type_tax_use', 'tax_group_id', 'price_include', 'include_base_amount', 'is_base_affected', } if forbidden_fields & set(vals.keys()): lines = self.env['pos.order.line'].sudo().search([ ('order_id.session_id.state', '!=', 'closed') ]) self_ids = set(self.ids) for lines_chunk in map(self.env['pos.order.line'].browse, split_every(100000, lines.ids)): if any(tid in self_ids for ts in lines_chunk.read(['tax_ids']) for tid in ts['tax_ids']): raise UserError(_( 'It is forbidden to modify a tax used in a POS order not posted. ' 'You must close the POS sessions before modifying the tax.' )) lines_chunk.invalidate_cache(['tax_ids'], lines_chunk.ids) return super(AccountTax, self).write(vals) def get_real_tax_amount(self): tax_list = [] for tax in self: tax_repartition_lines = tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') total_factor = sum(tax_repartition_lines.mapped('factor')) real_amount = tax.amount * total_factor tax_list.append({'id': tax.id, 'amount': real_amount}) return tax_list
43.567568
1,612
2,925
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class AccountMove(models.Model): _inherit = 'account.move' pos_order_ids = fields.One2many('pos.order', 'account_move') pos_payment_ids = fields.One2many('pos.payment', 'account_move_id') def _stock_account_get_last_step_stock_moves(self): stock_moves = super(AccountMove, self)._stock_account_get_last_step_stock_moves() for invoice in self.filtered(lambda x: x.move_type == 'out_invoice'): stock_moves += invoice.sudo().mapped('pos_order_ids.picking_ids.move_lines').filtered(lambda x: x.state == 'done' and x.location_dest_id.usage == 'customer') for invoice in self.filtered(lambda x: x.move_type == 'out_refund'): stock_moves += invoice.sudo().mapped('pos_order_ids.picking_ids.move_lines').filtered(lambda x: x.state == 'done' and x.location_id.usage == 'customer') return stock_moves def _get_invoiced_lot_values(self): self.ensure_one() lot_values = super(AccountMove, self)._get_invoiced_lot_values() if self.state == 'draft': return lot_values # user may not have access to POS orders, but it's ok if they have # access to the invoice for order in self.sudo().pos_order_ids: for line in order.lines: lots = line.pack_lot_ids or False if lots: for lot in lots: lot_values.append({ 'product_name': lot.product_id.name, 'quantity': line.qty if lot.product_id.tracking == 'lot' else 1.0, 'uom_name': line.product_uom_id.name, 'lot_name': lot.lot_name, }) return lot_values def _get_reconciled_vals(self, partial, amount, counterpart_line): """Add pos_payment_name field in the reconciled vals to be able to show the payment method in the invoice.""" result = super()._get_reconciled_vals(partial, amount, counterpart_line) if counterpart_line.move_id.sudo().pos_payment_ids: pos_payment = counterpart_line.move_id.sudo().pos_payment_ids result['pos_payment_name'] = pos_payment.payment_method_id.name return result class AccountMoveLine(models.Model): _inherit = 'account.move.line' def _stock_account_get_anglo_saxon_price_unit(self): self.ensure_one() if not self.product_id: return self.price_unit price_unit = super(AccountMoveLine, self)._stock_account_get_anglo_saxon_price_unit() order = self.move_id.pos_order_ids if order: price_unit = order._get_pos_anglo_saxon_price_unit(self.product_id, self.move_id.partner_id.id, self.quantity) return price_unit
45
2,925