/** @odoo-module **/
import { patch } from "@web/core/utils/patch";
import { Orderline } from "@point_of_sale/app/components/orderline/orderline";
import { useEffect } from "@odoo/owl";
import { usePos } from "@point_of_sale/app/hooks/pos_hook";
import { useService } from "@web/core/utils/hooks";
import { _t } from "@web/core/l10n/translation";
import { rpc } from "@web/core/network/rpc";
import { CustomDiscountLimitPopup } from "./discount_popup";
patch(Orderline.prototype, {
setup() {
super.setup();
this.pos = usePos();
this.dialog = useService("dialog");
this.notification = useService("notification");
const checkDiscountLimit = async () => {
const currentOrder = this.pos.getOrder();
const isRefund = currentOrder
.getOrderlines()
.some((l) => l.getQuantity() < 0);
const screen = this.pos.router.state.current;
if (screen !== "ProductScreen" || isRefund) return;
if (!this.pos.config?.access_discount_limit) return;
const orderline = currentOrder?.getSelectedOrderline();
const discountAmount = parseFloat(orderline?.discount || 0);
const limit = parseFloat(this.pos.config?.discount_limit || 0);
if (!orderline) return;
if (limit > 0 && discountAmount > limit) {
this.dialog.add(CustomDiscountLimitPopup, {
title: _t("Discount Limit Exceeded"),
body: _t(
"The discount amount %(discount)s exceeds the allowed limit of %(limit)s. Please enter approval pin.",
{ discount: discountAmount, limit }
),
confirm: async (password) => {
try {
const employee = await rpc("/pos/check_employee_pin", {
pin: password,
});
if (employee && employee.discount_approval) {
this.notification.add(
_t(`Discount approved by ${employee.name}`),
{ type: "success" }
);
} else {
this.notification.add(
_t("You do not have approval for this discount."),
{ type: "danger" }
);
this.pos.numberBuffer.reset();
orderline.setDiscount(0);
this.pos.setDiscountFromUI(orderline, 0);
}
} catch (err) {
console.error("RPC error:", err);
this.notification.add(_t("Server error."), { type: "danger" });
this.pos.numberBuffer.reset();
orderline.setDiscount(0);
this.pos.setDiscountFromUI(orderline, 0);
}
},
cancel: () => {
this.pos.numberBuffer.reset();
orderline.setDiscount(0);
this.pos.setDiscountFromUI(orderline, 0);
},
});
}
};
useEffect(
() => {
if (this.pos.config.access_discount_limit) {
checkDiscountLimit();
}
},
() => [this.props.line?.discount]
);
},
});