import { Partner } from "../../../odoo/models/res.partner"; import { ProductProduct } from "../../../odoo/models/product.product"; import { CartItem } from "./cart-item" export class Cart { customer: Partner; items: Array; total: number; constructor( customer?: Partner, items?: Array, total?: number ) { this.customer = customer; this.items = items ? items : []; this.total = total ? total : 0; } /** * */ getCustomer(): Partner { return this.customer; } /** * */ getItems(): Array { return this.items; } /** * */ getTotal(): number { return this.total; } /** * * @param customer */ setCustomer(customer: Partner): void { this.customer = customer; } /** * * @param items */ setItems(items: Array): void { this.items = items; } /** * * @param total */ setTotal(total: number): void { this.total = total; } /** * * @param index */ getItem(index: number): CartItem { return this.getItems()[index]; } /** * */ size(): number { return this.getItems().length; } /** * * @param item */ add(product: ProductProduct, price: number, quantity: number): void { let index = this.exists(product); let item: CartItem = null; if (index === -1) { item = new CartItem(); item.setProduct(product); item.setPrice(price); item.updateQuantity(quantity) this.getItems().push(item); } else { let item = this.getItem(index); item.setPrice(price); item.setQuantity(item.getQuantity() + quantity); item.computeSubtotal(); } this.updateTotal(); } /** * * @param item */ remove(item: CartItem): void { let index = this.exists(item.getProduct()); this.getItems().splice(index, 1); this.updateTotal(); } /** * * @param items */ exists(product: ProductProduct): number { for (let i = 0; i < this.size(); i++) { if (product._id === this.getItem(i).getProduct()._id) { return i; } } return -1; } /** * */ updateTotal(): void { let sum = 0; for (let i = 0; i < this.size(); i++) { sum = sum + this.getItem(i).getSubtotal(); } this.setTotal(sum); } /** * */ empty(): boolean { return this.size() === 0; } /** * */ isValid(): boolean { return this.getCustomer() && !!this.size(); } }