Hello, in v17 I have the POS module, I need the seller who loaded each product to store me.
example
john - product1
peter - product2
The problem is that I need to enable Share open orders, the seller always overwrites me, I manage to make it so that if Juan opens the order he loads 2 products and I save and store product1 - Juan
product2-juan but if I open it with Pedro from pos2 it says that the seller was Pedro.
from odoo import models, fields, apiimport logging
_logger = logging.getLogger(__name__)
class PosOrder(models.Model): _inherit = "pos.order"
@api.model def _order_fields(self, ui_order): # Recorrer las líneas de la orden for line in ui_order.get('lines', []): # Asegurarse de que la línea tiene la estructura esperada if isinstance(line, list) and len(line) > 2: line_id = line[0] # ID de la línea de pedido new_cashier_id = line[2] # ID del cajero (cashier_id)
# Buscar el cajero original en la tabla auxiliar cashier_record = self.env['pos.order.line.cashier'].search([('order_line_id', '=', line_id)], limit=1)
if cashier_record: cached_cashier_id = cashier_record.cashier_id.id if cached_cashier_id and cached_cashier_id != new_cashier_id: _logger.info(f"Keeping original cashier {cached_cashier_id} for line {line_id}.") line[2] = cached_cashier_id # Mantener el cajero original
return super(PosOrder, self)._order_fields(ui_order)
class PosOrderLine(models.Model): _inherit = 'pos.order.line'
cashier_id = fields.Many2one('res.users', string='Cashier', ondelete='set null', readonly=True)
@api.model def create(self, vals_list): if isinstance(vals_list, dict): vals_list = [vals_list]
order_lines = super(PosOrderLine, self).create(vals_list)
for line in order_lines: cashier_id = self.env.user.id # El cajero actual line.cashier_id = cashier_id # Asigna el cajero a la línea de pedido
self.env['pos.order.line.cashier'].create({ 'order_line_id': line.id, 'cashier_id': cashier_id, }) _logger.info(f'Creating cashier_id {cashier_id} for order line {line.id}')
return order_lines
def write(self, vals): for line in self: cashier_record = self.env['pos.order.line.cashier'].search([('order_line_id', '=', line.id)], limit=1) if cashier_record: cached_cashier_id = cashier_record.cashier_id.id if 'cashier_id' in vals and vals['cashier_id'] != cached_cashier_id: vals['cashier_id'] = cached_cashier_id # Mantiene el cajero original else: # Si el vals no incluye cashier_id, asigna el original if 'cashier_id' not in vals: vals['cashier_id'] = cached_cashier_id
return super(PosOrderLine, self).write(vals)
class PosOrderLineCashier(models.Model): _name = 'pos.order.line.cashier' _description = 'Pos Order Line Cashier Relationship'
order_line_id = fields.Many2one('pos.order.line', string="Order Line", required=True, ondelete='cascade') cashier_id = fields.Many2one('res.users', string="Cashier", required=True, ondelete='restrict')
_sql_constraints = [ ('unique_order_line_cashier', 'unique(order_line_id)', 'Each order line must be linked to a cashier only once!') ]
odoo.define('pos_cashier_assignment.pos_cashier', function (require) { 'use strict';
const PosModel = require('point_of_sale.models'); const Order = PosModel.Order; const Orderline = PosModel.Orderline;
const _super_order = Order.prototype; Order.prototype = Object.assign({}, _super_order, { add_product: function (product, options) { // Llamar al método original _super_order.add_product.call(this, product, options);
const orderLine = this.get_last_orderline(); // Obtener la última línea de pedido const currentCashierId = this.pos.get_cashier().id; // Obtener el cajero de la sesión actual
// Solo asignar el cajero si la línea no tiene uno if (!orderLine.get_cashier()) { orderLine.set_cashier(currentCashierId); // Asignar el cajero a la línea de pedido }
// Guardar el cajero actual en el historial orderLine.add_cashier_to_history(currentCashierId); },
initialize: function (attributes, options) { _super_order.initialize.apply(this, arguments); this.orderlines.each(function (line) { const cashierId = line.get_cashier(); // Asignar el cajero si no tiene uno if (!cashierId) { line.set_cashier(line.pos.get_cashier().id); }
// Restaurar el cajero desde el historial si es necesario if (!cashierId && line.get_cashier_history().length > 0) { const lastCashierId = line.get_last_cashier_from_history(); line.set_cashier(lastCashierId); } }); },
async load_server_data() { // Cargar datos desde el servidor y obtener información adicional de los cajeros const loadedData = await this.orm.silent.call("pos.session", "load_pos_data", [ [odoo.pos_session_id], ]);
// Procesar los datos de la sesión POS await this._processData(loadedData); // Cargar cajeros (asumiendo que tienes un método en el servidor para eso) const cashiersData = await this.orm.silent.call("pos.session", "load_cashiers", [ [odoo.pos_session_id], ]); this.load_cashiers(cashiersData); // Método para cargar los cajeros
return this.after_load_server_data(); },
async _processData(loadedData) { // Procesar otros datos como antes... this.version = loadedData["version"]; this.company = loadedData["res.company"]; this.dp = loadedData["decimal.precision"]; // Otros datos...
// Aquí podrías agregar el procesamiento de los cajeros si los estás recibiendo aquí if (loadedData["cashiers"]) { this.cashiers = loadedData["cashiers"]; // Almacena los cajeros en una propiedad del objeto } // Continúa con el procesamiento normal... },
load_cashiers(cashiersData) { // Agregar cajeros a la base de datos local cashiersData.forEach(cashier => { // Asumiendo que tienes un método para agregar cajeros a la base de datos local this.db.add_cashier(cashier); // Implementa este método en tu db }); }, });
const _super_orderline = Orderline.prototype; Orderline.prototype = Object.assign({}, _super_orderline, { initialize: function () { _super_orderline.initialize.apply(this, arguments); this.cashier_id = this.cashier_id || null; // Inicializar el campo cashier_id si es necesario this.cashier_history = this.cashier_history || []; // Inicializar el historial de cajeros },
set_cashier: function (cashierId) { // Asignar solo si no tiene cajero o si coincide con el cajero actual if (!this.cashier_id || this.cashier_id === cashierId) { this.cashier_id = cashierId; } },
get_cashier: function () { return this.cashier_id; // Retornar el cashier_id de la línea },
// Agregar el cajero al historial de cajeros add_cashier_to_history: function (cashierId) { if (!this.cashier_history.includes(cashierId)) { this.cashier_history.push(cashierId); } },
// Obtener el historial de cajeros get_cashier_history: function () { return this.cashier_history || []; },
// Obtener el último cajero del historial get_last_cashier_from_history: function () { return this.cashier_history.length > 0 ? this.cashier_history[this.cashier_history.length - 1] : null; }, });});