From 8fb53c53c3128e8cea7ef20b9ab4946ac2f9b7d9 Mon Sep 17 00:00:00 2001 From: Joseph Caburnay Date: Fri, 15 Oct 2021 14:31:00 +0000 Subject: [PATCH] [REF] point_of_sale,*pos*: remove Backbone.js, single loading request This commit accomplishes multiple objectives: 1. Loading of model data for the POS UI is now done in single request (with some exemptions). 2. Backbone.js is removed and is replaced by reactivity.js authored by the js framework team. 3. Better organization of assets in the `__manifest__.py` Data Loading ------------ One request per model -- that's always been how the data is loaded in POS UI. Now, we move the aggregation of data to the backend which simplified the data loading. In the frontend, data loading is initiated in `load_server_data` which makes the single rpc call to the `load_pos_data` defined in `pos.session` model. There remains some rpc calls during loading but the number is greatly reduced. This change result to faster loading of the POS UI. However, there is no more progress bar during the loading. Notable entry points: - .js: `PosGlobalState.load_server_data` - .py: `pos.session.load_pos_data` It is possible to make customizations in the loading, but is done in several steps: 1. Override `_pos_ui_models_to_load` to include the new model to load. 2. Define `_loader_params_` to define the `search_params` and optional `context`. 3. Define `_get_pos_ui_` to return the data that will be included in the full `loaded_data`. Perform the organization in this method whenever necessary. 4. Override `_pos_data_process` for further post processing. The final form of `loaded_data` in this method will be sent to the frontend. Removal of Backbone.js ---------------------- POS is no longer dependent from `Backbone.js`, but it's replaced by a new dependency -- `reactivity.js`. It's invented by the js framework team which will be available in owl v2. The consequences of this change are the following: 1. The old `PosModel` is renamed to `PosGlobalState`. 2. The name of the other models are kept (except Paymentline which is renamed to Payment). 3. The name `PosModel` is now used as the base model of the data models. This is symmetric to our use of `PosComponent`. 4. The instance of `PosGlobalState` is made reactive in `Chrome` (the root component). As a result, whatever mutation made in that instance, `Chrome` will rerender. But rendering is batched so multiple mutations in a single sychronous function call will only result to a single render call. 5. `PosModel`s can be extended in the `Registries` the same way as we extend the `PosComponent`s. ```js // E.g. Registries.Component.extend(Chrome, PosResChrome); Registries.Model.extend(Order, PosResOrder); ``` Reorganization of assets declaration ------------------------------------ This is a simple change that replaced the explicit enumeration of loaded .js and .xml files. Also, we now have regions in the manifest separating: 1. Augmentations of dependencies 2. Assets for `point_of_sale.index` 3. Assets for the qunit test (soon will be improved) Other notable changes --------------------- - Automatic call to `Order.save_to_db` is batched. - Instances of `devices.DeviceProxy` (`proxy`), `devices.JobQueue` (`proxy_queue`) and `BarcodeReader` (`barcode_reader`) are moved to `point_of_sale.env`. Together with `posbus` and `posMutex` (previously `flush_mutex`). - `ActivePrograms` is now passed a props. - `cashier` is no longer saved to `localStorage`. - `pos_cache` is overhauled. - `cache` is taken out from `PosDB` to prevent infinite rendering loop whenever `cache` is mutated. It's now called `CACHE` in the `db.js` file. - reactive version of `posmodel` is exposed globally when in debug mode. This means that calling when calling a mutator, the UI will react. - Added control buttons in the `ProductScreen` is sorted during `Chrome` setup. As a result, we don't need to worry on the loading order of the control buttons components. - Model can be simply instantiated using `BaseModel.create(obj)`. This takes into account the extensions. - `pos_coupon`: rewards are now updated whenever set_order is called. - Component unit tests were removed. It wasn't useful and it just blocks the development. We'll be introducing better unit testing later. closes odoo/odoo#82461 Related: odoo/enterprise#23344 Signed-off-by: Masereel Pierre Co-authored-by: Jacky (trj) --- addons/account/models/account_tax.py | 8 + addons/l10n_co_pos/static/src/js/pos.js | 36 +- .../static/src/js/NumpadWidget.js | 20 - addons/l10n_fr_pos_cert/static/src/js/pos.js | 92 +- addons/l10n_in_pos/models/__init__.py | 1 + addons/l10n_in_pos/models/pos_session.py | 13 + addons/l10n_in_pos/static/src/js/receipt.js | 16 +- addons/l10n_sa_pos/static/src/js/models.js | 21 +- addons/point_of_sale/__manifest__.py | 190 +- addons/point_of_sale/controllers/main.py | 2 + addons/point_of_sale/models/account_tax.py | 9 - addons/point_of_sale/models/pos_order.py | 2 +- addons/point_of_sale/models/pos_session.py | 420 +++ .../static/lib/backbone/backbone.js | 1581 ----------- .../src/{js => backend}/debug_manager.js | 0 .../{js => backend}/tours/point_of_sale.js | 0 .../web_overrides/pos_config_form.js | 0 addons/point_of_sale/static/src/css/pos.css | 63 +- .../src/{js => entry}/chrome_adapter.js | 33 +- .../static/src/{js => entry}/main.js | 3 +- addons/point_of_sale/static/src/js/Chrome.js | 182 +- .../src/js/ChromeWidgets/CashMoveButton.js | 4 +- .../src/js/ChromeWidgets/CashierName.js | 4 +- .../js/ChromeWidgets/ClientScreenButton.js | 12 +- .../src/js/ChromeWidgets/DebugWidget.js | 14 +- .../src/js/ChromeWidgets/ProxyStatus.js | 17 +- .../src/js/ChromeWidgets/SaleDetailsButton.js | 2 +- .../src/js/ChromeWidgets/SyncNotification.js | 21 - .../src/js/ChromeWidgets/TicketButton.js | 15 +- .../static/src/js/ControlButtonsMixin.js | 89 +- .../src/js/Misc/AbstractReceiptScreen.js | 4 +- .../src/js/Misc/IndependentToOrderScreen.js | 14 +- .../static/src/js/Misc/MobileOrderWidget.js | 23 +- .../static/src/js/Popups/ProductInfoPopup.js | 5 +- .../static/src/js/PosComponent.js | 8 + .../point_of_sale/static/src/js/PosContext.js | 1 - .../point_of_sale/static/src/js/Registries.js | 18 +- .../OrderManagementScreen/OrderFetcher.js | 0 .../js/Screens/PaymentScreen/PaymentScreen.js | 116 +- .../PaymentScreenElectronicPayment.js | 12 +- .../PaymentScreen/PaymentScreenStatus.js | 9 +- .../Screens/ProductScreen/ActionpadWidget.js | 5 +- .../ControlButtons/ProductInfoButton.js | 8 - .../ControlButtons/SetFiscalPositionButton.js | 13 +- .../ControlButtons/SetPricelistButton.js | 8 - .../js/Screens/ProductScreen/NumpadWidget.js | 21 +- .../js/Screens/ProductScreen/OrderSummary.js | 16 +- .../js/Screens/ProductScreen/OrderWidget.js | 42 +- .../js/Screens/ProductScreen/ProductItem.js | 1 - .../js/Screens/ProductScreen/ProductScreen.js | 41 +- .../Screens/ProductScreen/ProductsWidget.js | 8 +- .../ProductsWidgetControlPanel.js | 5 +- .../js/Screens/ReceiptScreen/ReceiptScreen.js | 9 +- .../ReceiptScreen/WrappedProductNameLines.js | 7 +- .../src/js/Screens/ScaleScreen/ScaleScreen.js | 6 +- .../ControlButtons/InvoiceButton.js | 2 +- .../js/Screens/TicketScreen/OrderDetails.js | 2 +- .../TicketScreen/ReprintReceiptScreen.js | 2 +- .../js/Screens/TicketScreen/TicketScreen.js | 39 +- .../static/src/js/barcode_reader.js | 2 +- .../static/src/js/custom_hooks.js | 45 +- addons/point_of_sale/static/src/js/db.js | 39 +- addons/point_of_sale/static/src/js/devices.js | 9 +- addons/point_of_sale/static/src/js/models.js | 2359 ++++++----------- addons/point_of_sale/static/src/js/payment.js | 4 +- addons/point_of_sale/static/src/js/pos_env.js | 21 + .../point_of_sale/static/src/js/reactivity.js | 271 ++ addons/point_of_sale/static/src/js/utils.js | 2 +- .../point_of_sale/static/src/xml/Chrome.xml | 33 +- .../src/xml/ChromeWidgets/ProxyStatus.xml | 2 +- .../xml/ChromeWidgets/SyncNotification.xml | 12 +- .../CustomerFacingDisplayOrder.xml | 2 +- .../Screens/PaymentScreen/PaymentScreen.xml | 21 +- .../PaymentScreen/PaymentScreenStatus.xml | 6 +- .../Screens/ProductScreen/ActionpadWidget.xml | 4 +- .../Screens/ProductScreen/OrderSummary.xml | 10 +- .../xml/Screens/ProductScreen/OrderWidget.xml | 2 +- .../xml/Screens/ProductScreen/Orderline.xml | 4 +- .../Screens/ProductScreen/ProductScreen.xml | 2 +- .../Screens/ReceiptScreen/OrderReceipt.xml | 2 +- .../static/tests/unit/helpers/test_env.js | 29 +- .../static/tests/unit/test_ChromeWidgets.js | 69 - .../static/tests/unit/test_PaymentScreen.js | 310 --- .../static/tests/unit/test_ProductScreen.js | 603 ----- .../static/tests/unit/test_popups.js | 180 -- addons/point_of_sale/tests/test_js.py | 1 + .../point_of_sale/views/pos_assets_common.xml | 1 - .../point_of_sale/views/pos_assets_index.xml | 1 + .../point_of_sale/views/pos_assets_qunit.xml | 5 +- addons/pos_adyen/models/__init__.py | 1 + addons/pos_adyen/models/pos_session.py | 13 + addons/pos_adyen/static/src/js/models.js | 1 - addons/pos_cache/models/__init__.py | 1 + addons/pos_cache/models/pos_cache.py | 24 +- addons/pos_cache/models/pos_session.py | 53 + addons/pos_cache/static/src/js/Chrome.js | 33 + addons/pos_cache/static/src/js/pos_cache.js | 102 +- addons/pos_coupon/__manifest__.py | 1 + addons/pos_coupon/models/__init__.py | 1 + addons/pos_coupon/models/pos_session.py | 37 + .../static/src/js/ActivePrograms.js | 78 +- .../pos_coupon/static/src/js/OrderWidget.js | 59 + .../pos_coupon/static/src/js/PaymentScreen.js | 2 +- .../pos_coupon/static/src/js/ProductScreen.js | 7 +- addons/pos_coupon/static/src/js/coupon.js | 349 ++- .../static/src/xml/ActivePrograms.xml | 8 +- .../pos_coupon/static/src/xml/OrderWidget.xml | 2 +- addons/pos_discount/models/__init__.py | 1 + addons/pos_discount/models/pos_session.py | 15 + addons/pos_discount/static/src/js/models.js | 21 - .../static/src/js/pos_epson_printer.js | 18 +- .../models/__init__.py | 1 + .../models/pos_session.py | 13 + .../static/src/js/multiprint.js | 17 +- addons/pos_gift_card/models/__init__.py | 1 + addons/pos_gift_card/models/pos_session.py | 15 + .../static/src/js/GiftCardPopup.js | 2 +- .../static/src/js/PaymentScreen.js | 11 +- addons/pos_gift_card/static/src/js/models.js | 78 +- addons/pos_hr/models/__init__.py | 1 + addons/pos_hr/models/pos_session.py | 43 + addons/pos_hr/static/src/js/CashierName.js | 6 - addons/pos_hr/static/src/js/Chrome.js | 10 +- addons/pos_hr/static/src/js/LoginScreen.js | 3 +- addons/pos_hr/static/src/js/models.js | 130 +- addons/pos_mercury/models/__init__.py | 1 + addons/pos_mercury/models/pos_session.py | 13 + .../pos_mercury/static/src/js/pos_mercury.js | 66 +- addons/pos_restaurant/__manifest__.py | 3 - addons/pos_restaurant/models/__init__.py | 1 + .../pos_restaurant/models/pos_restaurant.py | 7 +- addons/pos_restaurant/models/pos_session.py | 64 + addons/pos_restaurant/static/src/js/Chrome.js | 12 - .../src/js/ChromeWidgets/BackToFloorButton.js | 7 - .../src/js/ChromeWidgets/TicketButton.js | 9 +- .../src/js/Screens/FloorScreen/FloorScreen.js | 24 +- .../ControlButtons/SubmitOrderButton.js | 25 +- .../ControlButtons/TransferOrderButton.js | 3 +- .../SplitBillScreen/SplitBillScreen.js | 51 +- .../static/src/js/Screens/TicketScreen.js | 35 +- .../static/src/js/Screens/TipScreen.js | 8 +- addons/pos_restaurant/static/src/js/floors.js | 288 +- .../static/src/js/multiprint.js | 173 +- addons/pos_restaurant/static/src/js/notes.js | 49 +- .../SplitBillScreen/SplitBillScreen.xml | 2 +- .../static/src/xml/Screens/TipScreen.xml | 2 +- .../static/tests/unit/test_FloorScreen.js | 197 -- .../pos_restaurant_adyen/models/__init__.py | 1 + .../models/pos_session.py | 13 + .../static/src/js/models.js | 5 - .../static/src/js/payment_adyen.js | 3 +- addons/pos_sale/__manifest__.py | 1 - addons/pos_sale/models/pos_session.py | 7 + .../OrderManagementScreen/SaleOrderFetcher.js | 1 - .../SaleOrderManagementControlPanel.js | 2 +- .../SaleOrderManagementScreen.js | 9 +- .../pos_sale/static/src/js/ProductScreen.js | 30 - .../static/src/js/SetSaleOrderButton.js | 8 - addons/pos_sale/static/src/js/models.js | 64 +- .../models/__init__.py | 1 + .../models/pos_session.py | 13 + .../static/src/js/models.js | 15 +- addons/pos_six/models/__init__.py | 1 + addons/pos_six/models/pos_session.py | 13 + addons/pos_six/static/src/js/models.js | 2 - addons/pos_six/static/src/js/payment_six.js | 6 +- 166 files changed, 3354 insertions(+), 6405 deletions(-) delete mode 100644 addons/l10n_fr_pos_cert/static/src/js/NumpadWidget.js create mode 100644 addons/l10n_in_pos/models/pos_session.py delete mode 100644 addons/point_of_sale/static/lib/backbone/backbone.js rename addons/point_of_sale/static/src/{js => backend}/debug_manager.js (100%) rename addons/point_of_sale/static/src/{js => backend}/tours/point_of_sale.js (100%) rename addons/point_of_sale/static/src/{js => backend}/web_overrides/pos_config_form.js (100%) rename addons/point_of_sale/static/src/{js => entry}/chrome_adapter.js (58%) rename addons/point_of_sale/static/src/{js => entry}/main.js (90%) delete mode 100644 addons/point_of_sale/static/src/js/Screens/OrderManagementScreen/OrderFetcher.js create mode 100644 addons/point_of_sale/static/src/js/pos_env.js create mode 100644 addons/point_of_sale/static/src/js/reactivity.js delete mode 100644 addons/point_of_sale/static/tests/unit/test_ChromeWidgets.js delete mode 100644 addons/point_of_sale/static/tests/unit/test_PaymentScreen.js delete mode 100644 addons/point_of_sale/static/tests/unit/test_ProductScreen.js delete mode 100644 addons/point_of_sale/static/tests/unit/test_popups.js create mode 100644 addons/pos_adyen/models/pos_session.py create mode 100644 addons/pos_cache/models/pos_session.py create mode 100644 addons/pos_cache/static/src/js/Chrome.js create mode 100644 addons/pos_coupon/models/pos_session.py create mode 100644 addons/pos_coupon/static/src/js/OrderWidget.js create mode 100644 addons/pos_discount/models/pos_session.py delete mode 100644 addons/pos_discount/static/src/js/models.js create mode 100644 addons/pos_epson_printer_restaurant/models/pos_session.py create mode 100644 addons/pos_gift_card/models/pos_session.py create mode 100644 addons/pos_hr/models/pos_session.py create mode 100644 addons/pos_mercury/models/pos_session.py create mode 100644 addons/pos_restaurant/models/pos_session.py delete mode 100644 addons/pos_restaurant/static/tests/unit/test_FloorScreen.js create mode 100644 addons/pos_restaurant_adyen/models/pos_session.py delete mode 100644 addons/pos_restaurant_adyen/static/src/js/models.js delete mode 100644 addons/pos_sale/static/src/js/ProductScreen.js create mode 100644 addons/pos_sale_product_configurator/models/pos_session.py create mode 100644 addons/pos_six/models/pos_session.py diff --git a/addons/account/models/account_tax.py b/addons/account/models/account_tax.py index 2f8389069d6..edf04fac1b5 100644 --- a/addons/account/models/account_tax.py +++ b/addons/account/models/account_tax.py @@ -105,6 +105,7 @@ class AccountTax(models.Model): sequence = fields.Integer(required=True, default=1, help="The sequence field is used to define order in which the tax lines are applied.") amount = fields.Float(required=True, digits=(16, 4), default=0.0) + real_amount = fields.Float(string='Real amount to apply', compute='_compute_real_amount', store=True) description = fields.Char(string='Label on Invoices') price_include = fields.Boolean(string='Included in Price', default=False, help="Check this if the price you use on the product and invoices includes this tax.") @@ -296,6 +297,13 @@ class AccountTax(models.Model): if self.price_include: self.include_base_amount = True + @api.depends('invoice_repartition_line_ids', 'amount', 'invoice_repartition_line_ids.factor') + def _compute_real_amount(self): + 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')) + tax.real_amount = tax.amount * total_factor + def _compute_amount(self, base_amount, price_unit, quantity=1.0, product=None, partner=None): """ Returns the amount of a single tax. base_amount is the actual amount on which the tax is applied, which is price_unit * quantity eventually affected by previous taxes (if tax is include_base_amount XOR price_include) diff --git a/addons/l10n_co_pos/static/src/js/pos.js b/addons/l10n_co_pos/static/src/js/pos.js index ff07dae1295..b7719f4f57d 100644 --- a/addons/l10n_co_pos/static/src/js/pos.js +++ b/addons/l10n_co_pos/static/src/js/pos.js @@ -1,32 +1,34 @@ odoo.define('l10n_co_pos.pos', function (require) { "use strict"; -var models = require('point_of_sale.models'); +var { PosGlobalState, Order } = require('point_of_sale.models'); +const Registries = require('point_of_sale.Registries'); -models.PosModel = models.PosModel.extend({ - is_colombian_country: function () { +const L10nCoPosGlobalState = (PosGlobalState) => class L10nCoPosGlobalState extends PosGlobalState { + is_colombian_country() { return this.company.country.code === 'CO'; - }, -}); + } +} +Registries.Model.extend(PosGlobalState, L10nCoPosGlobalState); -var _super_order = models.Order.prototype; -models.Order = models.Order.extend({ - export_for_printing: function () { - var result = _super_order.export_for_printing.apply(this, arguments); +const L10nCoPosOrder = (Order) => class L10nCoPosOrder extends Order { + export_for_printing() { + var result = super.export_for_printing(...arguments); result.l10n_co_dian = this.get_l10n_co_dian(); return result; - }, - set_l10n_co_dian: function (l10n_co_dian) { + } + set_l10n_co_dian(l10n_co_dian) { this.l10n_co_dian = l10n_co_dian; - }, - get_l10n_co_dian: function () { + } + get_l10n_co_dian() { return this.l10n_co_dian; - }, - wait_for_push_order: function () { - var result = _super_order.wait_for_push_order.apply(this, arguments); + } + wait_for_push_order() { + var result = super.wait_for_push_order(...arguments); result = Boolean(result || this.pos.is_colombian_country()); return result; } -}); +} +Registries.Model.extend(Order, L10nCoPosOrder); }); diff --git a/addons/l10n_fr_pos_cert/static/src/js/NumpadWidget.js b/addons/l10n_fr_pos_cert/static/src/js/NumpadWidget.js deleted file mode 100644 index ad6f0948850..00000000000 --- a/addons/l10n_fr_pos_cert/static/src/js/NumpadWidget.js +++ /dev/null @@ -1,20 +0,0 @@ -odoo.define('l10n_fr_pos_cert.NumpadWidget', function(require) { - 'use strict'; - - const NumpadWidget = require('point_of_sale.NumpadWidget'); - const Registries = require('point_of_sale.Registries'); - - const PosFrNumpadWidget = NumpadWidget => class extends NumpadWidget { - get hasPriceControlRights() { - if (this.env.pos.is_french_country()) { - return false; - } else { - return super.hasPriceControlRights; - } - } - }; - - Registries.Component.extend(NumpadWidget, PosFrNumpadWidget); - - return NumpadWidget; - }); diff --git a/addons/l10n_fr_pos_cert/static/src/js/pos.js b/addons/l10n_fr_pos_cert/static/src/js/pos.js index 79e06ed6cb1..bbfbc5aa283 100644 --- a/addons/l10n_fr_pos_cert/static/src/js/pos.js +++ b/addons/l10n_fr_pos_cert/static/src/js/pos.js @@ -2,18 +2,14 @@ odoo.define('l10n_fr_pos_cert.pos', function (require) { "use strict"; const { Gui } = require('point_of_sale.Gui'); -var models = require('point_of_sale.models'); -var rpc = require('web.rpc'); -var session = require('web.session'); +var { PosGlobalState, Order, Orderline } = require('point_of_sale.models'); var core = require('web.core'); -var utils = require('web.utils'); +const Registries = require('point_of_sale.Registries'); var _t = core._t; -var round_di = utils.round_decimals; -var _super_posmodel = models.PosModel.prototype; -models.PosModel = models.PosModel.extend({ - is_french_country: function(){ +const L10nFrPosGlobalState = (PosGlobalState) => class L10nFrPosGlobalState extends PosGlobalState { + is_french_country(){ var french_countries = ['FR', 'MF', 'MQ', 'NC', 'PF', 'RE', 'GF', 'GP', 'TF']; if (!this.company.country) { Gui.showPopup("ErrorPopup", { @@ -23,38 +19,45 @@ models.PosModel = models.PosModel.extend({ return false; } return _.contains(french_countries, this.company.country.code); - }, + } disallowLineQuantityChange() { - let result = _super_posmodel.disallowLineQuantityChange.bind(this)(); + let result = super.disallowLineQuantityChange(...arguments); return this.is_french_country() || result; } -}); + cashierHasPriceControlRights() { + if (this.is_french_country()) { + return false; + } else { + return super.cashierHasPriceControlRights(); + } + } +} +Registries.Model.extend(PosGlobalState, L10nFrPosGlobalState); -var _super_order = models.Order.prototype; -models.Order = models.Order.extend({ - initialize: function() { - _super_order.initialize.apply(this,arguments); +const L10nFrOrder = (Order) => class L10nFrOrder extends Order { + constructor() { + super(...arguments); this.l10n_fr_hash = this.l10n_fr_hash || false; this.save_to_db(); - }, - export_for_printing: function() { - var result = _super_order.export_for_printing.apply(this,arguments); + } + export_for_printing() { + var result = super.export_for_printing(...arguments); result.l10n_fr_hash = this.get_l10n_fr_hash(); return result; - }, - set_l10n_fr_hash: function (l10n_fr_hash){ + } + set_l10n_fr_hash (l10n_fr_hash){ this.l10n_fr_hash = l10n_fr_hash; - }, - get_l10n_fr_hash: function() { + } + get_l10n_fr_hash() { return this.l10n_fr_hash; - }, - wait_for_push_order: function() { - var result = _super_order.wait_for_push_order.apply(this,arguments); + } + wait_for_push_order() { + var result = super.wait_for_push_order(...arguments); result = Boolean(result || this.pos.is_french_country()); return result; - }, - destroy: function(option) { + } + destroy (option) { // SUGGESTION: It's probably more appropriate to apply this restriction // in the TicketScreen. if (option && option.reason == 'abandon' && this.pos.is_french_country() && this.get_orderlines().length) { @@ -63,23 +66,26 @@ models.Order = models.Order.extend({ 'body': _t("Deleting of orders is not allowed."), }); } else { - _super_order.destroy.apply(this, arguments); - } - }, -}); - -var orderline_super = models.Orderline.prototype; -models.Orderline = models.Orderline.extend({ - can_be_merged_with: function(orderline) { - let order = this.pos.get_order(); - let lastId = order.orderlines.last().cid; - - if(this.pos.is_french_country() && (order.orderlines._byId[lastId].product.id !== orderline.product.id || order.orderlines._byId[lastId].quantity < 0)) { - return false; - } else { - return orderline_super.can_be_merged_with.apply(this, arguments); + super.destroy(...arguments); } } -}); +} +Registries.Model.extend(Order, L10nFrOrder); + + +const L10nFrOrderline = (Orderline) => class L10nFrOrderline extends Orderline { + can_be_merged_with(orderline) { + let order = this.pos.get_order(); + let orderlines = order.orderlines; + let lastOrderline = order.orderlines.at(orderlines.length - 1); + + if(this.pos.is_french_country() && (lastOrderline.product.id !== orderline.product.id || lastOrderline.quantity < 0)) { + return false; + } else { + return super.can_be_merged_with(...arguments); + } + } +} +Registries.Model.extend(Orderline, L10nFrOrderline); }); diff --git a/addons/l10n_in_pos/models/__init__.py b/addons/l10n_in_pos/models/__init__.py index 04f8c2cc55d..9fb4d858140 100644 --- a/addons/l10n_in_pos/models/__init__.py +++ b/addons/l10n_in_pos/models/__init__.py @@ -2,3 +2,4 @@ # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import pos_order +from . import pos_session diff --git a/addons/l10n_in_pos/models/pos_session.py b/addons/l10n_in_pos/models/pos_session.py new file mode 100644 index 00000000000..1161e1bcdfb --- /dev/null +++ b/addons/l10n_in_pos/models/pos_session.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo import models + + +class PosSession(models.Model): + _inherit = 'pos.session' + + def _loader_params_product_product(self): + result = super()._loader_params_product_product() + result['search_params']['fields'].append('l10n_in_hsn_code') + return result diff --git a/addons/l10n_in_pos/static/src/js/receipt.js b/addons/l10n_in_pos/static/src/js/receipt.js index 89ccc681059..94ef5e56130 100644 --- a/addons/l10n_in_pos/static/src/js/receipt.js +++ b/addons/l10n_in_pos/static/src/js/receipt.js @@ -1,17 +1,17 @@ odoo.define('l10n_in_pos.receipt', function (require) { "use strict"; -var models = require('point_of_sale.models'); +var { Orderline } = require('point_of_sale.models'); +const Registries = require('point_of_sale.Registries'); -models.load_fields('product.product', 'l10n_in_hsn_code'); -var _super_orderline = models.Orderline.prototype; -models.Orderline = models.Orderline.extend({ - export_for_printing: function() { - var line = _super_orderline.export_for_printing.apply(this,arguments); +const L10nInOrderline = (Orderline) => class L10nInOrderline extends Orderline { + export_for_printing() { + var line = super.export_for_printing(...arguments); line.l10n_in_hsn_code = this.get_product().l10n_in_hsn_code; return line; - }, -}); + } +} +Registries.Model.extend(Orderline, L10nInOrderline); }); diff --git a/addons/l10n_sa_pos/static/src/js/models.js b/addons/l10n_sa_pos/static/src/js/models.js index e73966a9e5b..8f1e8244549 100644 --- a/addons/l10n_sa_pos/static/src/js/models.js +++ b/addons/l10n_sa_pos/static/src/js/models.js @@ -2,20 +2,20 @@ odoo.define('l10n_sa_pos.pos', function (require) { "use strict"; const { Gui } = require('point_of_sale.Gui'); -var models = require('point_of_sale.models'); +var { Order } = require('point_of_sale.models'); var rpc = require('web.rpc'); var session = require('web.session'); var core = require('web.core'); var utils = require('web.utils'); +var Registries = require('point_of_sale.Registries'); var _t = core._t; var round_di = utils.round_decimals; -var _super_order = models.Order.prototype; -models.Order = models.Order.extend({ - export_for_printing: function() { - var result = _super_order.export_for_printing.apply(this,arguments); +const PosL10nSAOrder = (Order) => class PosL10nSAOrder extends Order { + export_for_printing() { + var result = super.export_for_printing(...arguments); if (this.pos.company.country.code === 'SA') { const codeWriter = new window.ZXing.BrowserQRCodeSvgWriter() let qr_values = this.compute_sa_qr_code(result.company.name, result.company.vat, result.date.isostring, result.total_with_tax, result.total_tax); @@ -23,7 +23,7 @@ models.Order = models.Order.extend({ result.qr_code = "data:image/svg+xml;base64,"+ window.btoa(qr_code_svg); } return result; - }, + } compute_sa_qr_code(name, vat, date_isostring, amount_total, amount_tax) { /* Generate the qr code for Saudi e-invoicing. Specs are available at the following link at page 23 https://zatca.gov.sa/ar/E-Invoicing/SystemsDevelopers/Documents/20210528_ZATCA_Electronic_Invoice_Security_Features_Implementation_Standards_vShared.pdf @@ -41,7 +41,7 @@ models.Order = models.Order.extend({ binary += String.fromCharCode(str_to_encode[i]); } return btoa(binary); - }, + } _compute_qr_code_field(tag, field) { const textEncoder = new TextEncoder(); @@ -49,8 +49,9 @@ models.Order = models.Order.extend({ const name_tag_encoding = [tag]; const name_length_encoding = [name_byte_array.length]; return name_tag_encoding.concat(name_length_encoding, name_byte_array); - }, - -}); + } + +} +Registries.Model.extend(Order, PosL10nSAOrder); }); diff --git a/addons/point_of_sale/__manifest__.py b/addons/point_of_sale/__manifest__.py index 52a10c0c982..208434919d8 100644 --- a/addons/point_of_sale/__manifest__.py +++ b/addons/point_of_sale/__manifest__.py @@ -51,9 +51,61 @@ 'application': True, 'website': 'https://www.odoo.com/app/point-of-sale-shop', 'assets': { + + ## In general, you DON'T NEED to declare new assets here, just put the files in the proper directory. + ## NOTABLE EXCEPTION: List the new .css files in the `point_of_sale.assets` bundle taking into consideration + ## the order of the .css files. + ## + ## 1. When defining new component, put the .js files in `point_of_sale/static/src/js/` + ## and the corresponding .xml files in `point_of_sale/static/src/xml/` + ## * POS is setup to automatically include the .xml files in `web.assets_qweb` and the `.js` files + ## * in `point_of_sale.assets`. + ## 2. When adding new tour tests, put the .js files in `point_of_sale/static/tests/tours/`. + ## 3. When adding new qunit tests, put the .js files in `point_of_sale/static/tests/unit/`. + ## + ## If your use case doesn't fit anything above, you might need to properly understand each "asset bundle" + ## defined here and check how they are used in the following "index templates": + ## 1. point_of_sale.index + ## -> This is the POS UI, accessible by opening a session. + ## 2. point_of_sale.qunit_suite + ## -> This is the unit test, accessible by clicking the "Run Point of Sale JS Tests" button + ## in the "debug" button from the backend interface. + + ##################################### + ## Augmentation of existing assets ## + ##################################### + + 'web.assets_backend': [ + 'point_of_sale/static/src/scss/pos_dashboard.scss', + 'point_of_sale/static/src/backend/tours/point_of_sale.js', + 'point_of_sale/static/src/backend/debug_manager.js', + 'point_of_sale/static/src/backend/web_overrides/pos_config_form.js', + ], 'web.assets_tests': [ 'point_of_sale/static/tests/tours/**/*', ], + 'web.assets_qweb': [ + 'point_of_sale/static/src/xml/**/*.xml', + ], + + #################################################### + ## Exclusive POS Assets 1: For running the POS UI ## + #################################################### + + 'point_of_sale.pos_assets_backend_style': [ + "web/static/src/core/ui/**/*.scss", + ], + # TODO: We need to control this asset bundle. + # We can reduce the size of loaded assets in POS UI by selectively + # loading the `web` assets. We should only include what POS needs. + 'point_of_sale.pos_assets_backend': [ + ('include', 'web.assets_common'), + ('include', 'web.assets_backend'), + ('remove', 'web/static/src/webclient/menus/menu_service.js'), + ('remove', 'web/static/src/core/errors/error_handlers.js'), + ('remove', 'web/static/src/legacy/legacy_rpc_error_handler.js'), + ], + # This bundle includes the main pos assets. 'point_of_sale.assets': [ 'web/static/fonts/fonts.scss', 'web/static/lib/fontawesome/css/font-awesome.css', @@ -66,119 +118,25 @@ '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/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/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', + + # Here includes the lib and POS UI assets. + 'point_of_sale/static/lib/**/*.js', + 'point_of_sale/static/src/js/**/*.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/webclient/menus/menu_service.js'), - ('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", + # This bundle contains the code responsible for starting the POS UI. + # It is practically the entry point. + 'point_of_sale.assets_backend_prod_only': [ + 'point_of_sale/static/src/entry/chrome_adapter.js', + 'point_of_sale/static/src/entry/main.js', + 'web/static/src/start.js', + 'web/static/src/legacy/legacy_setup.js', ], + + ######################################################### + ## Exclusive POS Assets 2: For running the QUnit tests ## + ######################################################### + + # This bundle includes the helper assets for the unit testing. 'point_of_sale.tests_assets': [ 'web/static/lib/qunit/qunit-2.9.1.css', 'web/static/lib/qunit/qunit-2.9.1.js', @@ -201,18 +159,10 @@ ('include', 'web.frontend_legacy'), ], + # This bundle includes the unit tests. 'point_of_sale.qunit_suite_tests': [ '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', } diff --git a/addons/point_of_sale/controllers/main.py b/addons/point_of_sale/controllers/main.py index f3b701c6905..4341b597f01 100644 --- a/addons/point_of_sale/controllers/main.py +++ b/addons/point_of_sale/controllers/main.py @@ -57,6 +57,7 @@ class PosController(http.Controller): context = { 'session_info': session_info, 'login_number': pos_session.login(), + 'pos_session_id': pos_session.id, } response = request.render('point_of_sale.index', context) response.headers['Cache-Control'] = 'no-store' @@ -74,6 +75,7 @@ class PosController(http.Controller): session_info['user_context']['allowed_company_ids'] = pos_session.company_id.ids context = { 'session_info': session_info, + 'pos_session_id': pos_session.id, } return request.render('point_of_sale.qunit_suite', qcontext=context) diff --git a/addons/point_of_sale/models/account_tax.py b/addons/point_of_sale/models/account_tax.py index 6e8dfae8b5e..c95074d157f 100644 --- a/addons/point_of_sale/models/account_tax.py +++ b/addons/point_of_sale/models/account_tax.py @@ -24,12 +24,3 @@ class AccountTax(models.Model): 'You must close the POS sessions before modifying the tax.' )) 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 diff --git a/addons/point_of_sale/models/pos_order.py b/addons/point_of_sale/models/pos_order.py index d1be9036afc..7ab9772dbed 100644 --- a/addons/point_of_sale/models/pos_order.py +++ b/addons/point_of_sale/models/pos_order.py @@ -682,7 +682,7 @@ class PosOrder(models.Model): if (existing_order and existing_order.state == 'draft') or not existing_order: order_ids.append(self._process_order(order, draft, existing_order)) - return self.env['pos.order'].search_read(domain = [('id', 'in', order_ids)], fields = ['id', 'pos_reference']) + return self.env['pos.order'].search_read(domain=[('id', 'in', order_ids)], fields=['id', 'pos_reference', 'account_move'], load=False) def _should_create_picking_real_time(self): return not self.session_id.update_stock_at_closing or (self.company_id.anglo_saxon_accounting and self.to_invoice) diff --git a/addons/point_of_sale/models/pos_session.py b/addons/point_of_sale/models/pos_session.py index 6550641e6fc..99c489ee126 100644 --- a/addons/point_of_sale/models/pos_session.py +++ b/addons/point_of_sale/models/pos_session.py @@ -3,10 +3,13 @@ from collections import defaultdict from datetime import timedelta +from itertools import groupby from odoo import api, fields, models, _, Command from odoo.exceptions import AccessError, UserError, ValidationError from odoo.tools import float_is_zero, float_compare +from odoo.osv.expression import AND, OR +from odoo.service.common import exp_version class PosSession(models.Model): _name = 'pos.session' @@ -1550,6 +1553,423 @@ class PosSession(models.Model): message_content.append(f'- Reason: {reason}') self.message_post(body='
\n'.join(message_content)) + def get_onboarding_data(self): + return { + "categories": self._load_model('pos.category'), + "products": self._load_model('product.product'), + } + + def _load_model(self, model): + model_name = model.replace('.', '_') + loader = getattr(self, '_get_pos_ui_%s' % model_name, None) + params = getattr(self, '_loader_params_%s' % model_name, None) + if loader and params: + return loader(params()) + else: + raise NotImplementedError(_("The function to load %s has not been implemented.", model)) + + def load_pos_data(self): + loaded_data = {} + self = self.with_context(loaded_data=loaded_data) + for model in self._pos_ui_models_to_load(): + loaded_data[model] = self._load_model(model) + self._pos_data_process(loaded_data) + return loaded_data + + def _get_attributes_by_ptal_id(self): + product_attributes = self.env['product.attribute'].search([('create_variant', '=', 'no_variant')]) + product_attributes_by_id = {product_attribute.id: product_attribute for product_attribute in product_attributes} + domain = [('attribute_id', 'in', product_attributes.mapped('id'))] + product_template_attribute_values = self.env['product.template.attribute.value'].search(domain) + key = lambda ptav: (ptav.attribute_line_id.id, ptav.attribute_id.id) + res = {} + for key, group in groupby(sorted(product_template_attribute_values, key=key), key=key): + attribute_line_id, attribute_id = key + values = [{**ptav.product_attribute_value_id.read(['name', 'is_custom', 'html_color'])[0], + 'price_extra': ptav.price_extra} for ptav in list(group)] + res[attribute_line_id] = { + 'id': attribute_line_id, + 'name': product_attributes_by_id[attribute_id].name, + 'display_type': product_attributes_by_id[attribute_id].display_type, + 'values': values + } + + return res + + def _pos_data_process(self, loaded_data): + """ + This is where we need to process the data if we can't do it in the loader/getter + """ + loaded_data['version'] = exp_version() + + loaded_data['units_by_id'] = {unit['id']: unit for unit in loaded_data['uom.uom']} + + loaded_data['taxes_by_id'] = {tax['id']: tax for tax in loaded_data['account.tax']} + for tax in loaded_data['taxes_by_id'].values(): + tax['children_tax_ids'] = [loaded_data['taxes_by_id'][id] for id in tax['children_tax_ids']] + + for pricelist in loaded_data['product.pricelist']: + if pricelist['id'] == self.config_id.pricelist_id.id: + loaded_data['default_pricelist'] = pricelist + break + + fiscal_position_by_id = {fpt['id']: fpt for fpt in self._get_pos_ui_account_fiscal_position_tax( + self._loader_params_account_fiscal_position_tax())} + for fiscal_position in loaded_data['account.fiscal.position']: + fiscal_position['fiscal_position_taxes_by_id'] = {tax_id: fiscal_position_by_id[tax_id] for tax_id in fiscal_position['tax_ids']} + + if self.config_id.product_configurator: + loaded_data['attributes_by_ptal_id'] = self._get_attributes_by_ptal_id() + + @api.model + def _pos_ui_models_to_load(self): + models_to_load = [ + 'res.company', + 'decimal.precision', + 'uom.uom', + 'res.country.state', + 'res.country', + 'res.lang', + 'account.tax', + 'pos.session', + 'pos.config', + 'pos.bill', + 'res.partner', + 'stock.picking.type', + 'res.users', + 'product.pricelist', + 'res.currency', + 'pos.category', + 'product.product', + 'product.packaging', + 'account.cash.rounding', + 'pos.payment.method', + 'account.fiscal.position', + ] + if self.config_id.cash_control: + models_to_load.append('account.bank.statement') + + return models_to_load + + def _loader_params_res_company(self): + return { + 'search_params': { + 'domain': [('id', '=', self.company_id.id)], + 'fields': [ + 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id', + 'country_id', 'state_id', 'tax_calculation_rounding_method' + ], + } + } + + def _get_pos_ui_res_company(self, params): + company = self.env['res.company'].search_read(**params['search_params'])[0] + params_country = self._loader_params_res_country() + if company['country_id']: + # TODO: this is redundant we have country_id and country + params_country['search_params']['domain'] = [('id', '=', company['country_id'][0])] + company['country'] = self.env['res.country'].search_read(**params_country['search_params'])[0] + else: + company['country'] = None + + return company + + def _loader_params_decimal_precision(self): + return {'search_params': {'domain': [], 'fields': ['name', 'digits']}} + + def _get_pos_ui_decimal_precision(self, params): + decimal_precisions = self.env['decimal.precision'].search_read(**params['search_params']) + return {dp['name']: dp['digits'] for dp in decimal_precisions} + + def _loader_params_uom_uom(self): + return {'search_params': {'domain': [], 'fields': []}, 'context': {'active_test': False}} + + def _get_pos_ui_uom_uom(self, params): + return self.env['uom.uom'].with_context(**params['context']).search_read(**params['search_params']) + + def _loader_params_res_country_state(self): + return {'search_params': {'domain': [], 'fields': ['name', 'country_id']}} + + def _get_pos_ui_res_country_state(self, params): + return self.env['res.country.state'].search_read(**params['search_params']) + + def _loader_params_res_country(self): + return {'search_params': {'domain': [], 'fields': ['name', 'vat_label', 'code']}} + + def _get_pos_ui_res_country(self, params): + return self.env['res.country'].search_read(**params['search_params']) + + def _loader_params_res_lang(self): + return {'search_params': {'domain': [], 'fields': ['name', 'code']}} + + def _get_pos_ui_res_lang(self, params): + return self.env['res.lang'].search_read(**params['search_params']) + + def _loader_params_account_tax(self): + return { + 'search_params': { + 'domain': [('company_id', '=', self.company_id.id)], + 'fields': [ + 'name', 'real_amount', 'price_include', 'include_base_amount', 'is_base_affected', + 'amount_type', 'children_tax_ids' + ], + }, + } + + def _get_pos_ui_account_tax(self, params): + taxes = self.env['account.tax'].search_read(**params['search_params']) + # TODO: rename amount to real_amount in front end + for tax in taxes: + tax['amount'] = tax['real_amount'] + del tax['real_amount'] + return taxes + + def _loader_params_pos_session(self): + return { + 'search_params': { + 'domain': [('id', '=', self.id)], + 'fields': [ + 'id', 'name', 'user_id', 'config_id', 'start_at', 'stop_at', 'sequence_number', + 'payment_method_ids', 'cash_register_id', 'state', 'update_stock_at_closing' + ], + }, + } + + def _get_pos_ui_pos_session(self, params): + return self.env['pos.session'].search_read(**params['search_params'])[0] + + def _loader_params_pos_config(self): + return {'search_params': {'domain': [('id', '=', self.config_id.id)], 'fields': []}} + + def _get_pos_ui_pos_config(self, params): + config = self.env['pos.config'].search_read(**params['search_params'])[0] + config['use_proxy'] = config['is_posbox'] and (config['iface_electronic_scale'] or config['iface_print_via_proxy'] + or config['iface_scan_via_proxy'] or config['iface_customer_facing_display_via_proxy']) + return config + + def _loader_params_pos_bill(self): + return {'search_params': {'domain': [('id', 'in', self.config_id.default_bill_ids.ids)], 'fields': ['name', 'value']}} + + def _get_pos_ui_pos_bill(self, params): + return self.env['pos.bill'].search_read(**params['search_params']) + + def _loader_params_res_partner(self): + return { + 'search_params': { + 'domain': [], + 'fields': [ + 'name', 'street', 'city', 'state_id', 'country_id', 'vat', 'lang', 'phone', 'zip', 'mobile', 'email', + 'barcode', 'write_date', 'property_account_position_id', 'property_product_pricelist' + ], + }, + } + + def _get_pos_ui_res_partner(self, params): + if not self.config_id.limited_partners_loading: + return self.env['res.partner'].search_read(**params['search_params']) + partner_ids = [res[0] for res in self.config_id.get_limited_partners_loading()] + return self.env['res.partner'].browse(partner_ids).read(params['search_params']['fields']) + + def _loader_params_stock_picking_type(self): + return { + 'search_params': { + 'domain': [('id', '=', self.config_id.picking_type_id.id)], + 'fields': ['use_create_lots', 'use_existing_lots'], + }, + } + + def _get_pos_ui_stock_picking_type(self, params): + return self.env['stock.picking.type'].search_read(**params['search_params'])[0] + + def _loader_params_res_users(self): + return { + 'search_params': { + 'domain': [('id', '=', self.env.user.id)], + 'fields': ['name', 'groups_id'], + }, + } + + def _get_pos_ui_res_users(self, params): + user = self.env['res.users'].search_read(**params['search_params'])[0] + user['role'] = 'manager' if any(id == self.config_id.group_pos_manager_id.id for id in user['groups_id']) else 'cashier' + del user['groups_id'] + return user + + def _loader_params_product_pricelist(self): + if self.config_id.use_pricelist: + domain = [('id', 'in', self.config_id.available_pricelist_ids.ids)] + else: + domain = [('id', '=', self.config_id.pricelist_id.id)] + return {'search_params': {'domain': domain, 'fields': ['name', 'display_name', 'discount_policy']}} + + def _get_pos_ui_product_pricelist(self, params): + pricelists = self.env['product.pricelist'].search_read(**params['search_params']) + for pricelist in pricelists: + pricelist['items'] = [] + + pricelist_by_id = {pricelist['id']: pricelist for pricelist in pricelists} + pricelist_item_domain = [('pricelist_id', 'in', [p['id'] for p in pricelists])] + for item in self.env['product.pricelist.item'].search_read(pricelist_item_domain, []): + pricelist_by_id[item['pricelist_id'][0]]['items'].append(item) + item['base_pricelist'] = pricelist_by_id.get(item['base_pricelist_id'][0]) if item['base_pricelist_id'] else None + + return pricelists + + def _loader_params_account_bank_statement(self): + return {'search_params': {'domain': [('id', '=', self.cash_register_id.id)], 'fields': ['id', 'balance_start']}} + + def _get_pos_ui_account_bank_statement(self, params): + return self.env['account.bank.statement'].search_read(**params['search_params'])[0] + + def _loader_params_product_category(self): + return {'search_params': {'domain': [], 'fields': ['name', 'parent_id']}} + + def _get_pos_ui_product_category(self, params): + categories = self.env['product.category'].search_read(**params['search_params']) + category_by_id = {category['id']: category for category in categories} + for category in categories: + category['parent'] = category_by_id[category['parent_id'][0]] if category['parent_id'] else None + return categories + + def _loader_params_res_currency(self): + return { + 'search_params': { + 'domain': [('id', '=', self.config_id.currency_id.id)], + 'fields': ['name', 'symbol', 'position', 'rounding', 'rate', 'decimal_places'], + }, + } + + def _get_pos_ui_res_currency(self, params): + return self.env['res.currency'].search_read(**params['search_params'])[0] + + def _loader_params_pos_category(self): + domain = [] + if self.config_id.limit_categories and self.config_id.iface_available_categ_ids: + domain = [('id', 'in', self.config_id.iface_available_categ_ids.ids)] + + return {'search_params': {'domain': domain, 'fields': ['id', 'name', 'parent_id', 'child_id', 'write_date']}} + + def _get_pos_ui_pos_category(self, params): + return self.env['pos.category'].search_read(**params['search_params']) + + def _loader_params_product_product(self): + domain = [ + '&', '&', ('sale_ok', '=', True), ('available_in_pos', '=', True), '|', + ('company_id', '=', self.config_id.company_id.id), ('company_id', '=', False) + ] + if self.config_id.limit_categories and self.config_id.iface_available_categ_ids: + domain = AND([domain, [('pos_categ_id', 'in', self.config_id.iface_available_categ_ids.ids)]]) + if self.config_id.iface_tipproduct: + domain = OR([domain, [('id', '=', self.config_id.tip_product_id.id)]]) + + return { + 'search_params': { + 'domain': domain, + 'fields': [ + 'display_name', 'lst_price', 'standard_price', 'categ_id', 'pos_categ_id', 'taxes_id', 'barcode', + 'default_code', 'to_weight', 'uom_id', 'description_sale', 'description', 'product_tmpl_id', 'tracking', + 'write_date', 'available_in_pos', 'attribute_line_ids', 'active' + ], + 'order': 'sequence,default_code,name', + }, + 'context': {'display_default_code': False}, + } + + def _process_pos_ui_product_product(self, products): + """ + Modify the list of products to add the categories as well as adapt the lst_price + :param products: a list of products + """ + if self.config_id.currency_id != self.company_id.currency_id: + for product in products: + product['lst_price'] = self.company_id.currency_id._convert(product['lst_price'], self.config_id.currency_id, + self.company_id, fields.Date.today()) + categories = self._get_pos_ui_product_category(self._loader_params_product_category()) + product_category_by_id = {category['id']: category for category in categories} + for product in products: + product['categ'] = product_category_by_id[product['categ_id'][0]] + + def _get_pos_ui_product_product(self, params): + self = self.with_context(**params['context']) + if not self.config_id.limited_products_loading: + products = self.env['product.product'].search_read(**params['search_params']) + else: + products = self.config_id.get_limited_products_loading(params['search_params']['fields']) + + self._process_pos_ui_product_product(products) + return products + + def _loader_params_product_packaging(self): + return { + 'search_params': { + 'domain': [('barcode', 'not in', ['', False])], + 'fields': ['name', 'barcode', 'product_id', 'qty'], + }, + } + + def _get_pos_ui_product_packaging(self, params): + return self.env['product.packaging'].search_read(**params['search_params']) + + def _loader_params_account_cash_rounding(self): + return { + 'search_params': { + 'domain': [('id', '=', self.config_id.rounding_method.id)], + 'fields': ['name', 'rounding', 'rounding_method'], + }, + } + + def _get_pos_ui_account_cash_rounding(self, params): + return self.env['account.cash.rounding'].search_read(**params['search_params']) + + def _loader_params_pos_payment_method(self): + return { + 'search_params': { + 'domain': [], + 'fields': ['name', 'is_cash_count', 'use_payment_terminal', 'split_transactions', 'type'], + 'order': 'is_cash_count desc, id', + }, + } + + def _get_pos_ui_pos_payment_method(self, params): + return self.env['pos.payment.method'].search_read(**params['search_params']) + + def _loader_params_account_fiscal_position(self): + return {'search_params': {'domain': [('id', 'in', self.config_id.fiscal_position_ids.ids)], 'fields': []}} + + def _get_pos_ui_account_fiscal_position(self, params): + return self.env['account.fiscal.position'].search_read(**params['search_params']) + + def _loader_params_account_fiscal_position_tax(self): + loaded_data = self._context.get('loaded_data') + fps = loaded_data['account.fiscal.position'] + fiscal_position_tax_ids = sum([fpos['tax_ids'] for fpos in fps], []) + return {'search_params': {'domain': [('id', 'in', fiscal_position_tax_ids)], 'fields': []}} + + def _get_pos_ui_account_fiscal_position_tax(self, params): + return self.env['account.fiscal.position.tax'].search_read(**params['search_params']) + + def get_pos_ui_product_product_by_params(self, custom_search_params): + """ + :param custom_search_params: a dictionary containing params of a search_read() + """ + params = self._loader_params_product_product() + # custom_search_params will take priority + params['search_params'] = {**params['search_params'], **custom_search_params} + products = self.env['product.product'].search_read(**params['search_params']) + if len(products) > 0: + self._process_pos_ui_product_product(products) + return products + + def get_pos_ui_res_partner_by_params(self, custom_search_params): + """ + :param custom_search_params: a dictionary containing params of a search_read() + """ + params = self._loader_params_res_partner() + # custom_search_params will take priority + params['search_params'] = {**params['search_params'], **custom_search_params} + partners = self.env['res.partner'].search_read(**params['search_params']) + return partners + class ProcurementGroup(models.Model): _inherit = 'procurement.group' diff --git a/addons/point_of_sale/static/lib/backbone/backbone.js b/addons/point_of_sale/static/lib/backbone/backbone.js deleted file mode 100644 index f7783c2c199..00000000000 --- a/addons/point_of_sale/static/lib/backbone/backbone.js +++ /dev/null @@ -1,1581 +0,0 @@ -// Backbone.js 1.1.0 - -// (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc. -// (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors -// Backbone may be freely distributed under the MIT license. -// For all details and documentation: -// http://backbonejs.org - -(function(){ - - // Initial Setup - // ------------- - - // Save a reference to the global object (`window` in the browser, `exports` - // on the server). - var root = this; - - // Save the previous value of the `Backbone` variable, so that it can be - // restored later on, if `noConflict` is used. - var previousBackbone = root.Backbone; - - // Create local references to array methods we'll want to use later. - var array = []; - var push = array.push; - var slice = array.slice; - var splice = array.splice; - - // The top-level namespace. All public Backbone classes and modules will - // be attached to this. Exported for both the browser and the server. - var Backbone; - if (typeof exports !== 'undefined') { - Backbone = exports; - } else { - Backbone = root.Backbone = {}; - } - - // Current version of the library. Keep in sync with `package.json`. - Backbone.VERSION = '1.1.0'; - - // Require Underscore, if we're on the server, and it's not already present. - var _ = root._; - if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); - - // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns - // the `$` variable. - Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; - - // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable - // to its previous owner. Returns a reference to this Backbone object. - Backbone.noConflict = function() { - root.Backbone = previousBackbone; - return this; - }; - - // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option - // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and - // set a `X-Http-Method-Override` header. - Backbone.emulateHTTP = false; - - // Turn on `emulateJSON` to support legacy servers that can't deal with direct - // `application/json` requests ... will encode the body as - // `application/x-www-form-urlencoded` instead and will send the model in a - // form param named `model`. - Backbone.emulateJSON = false; - - // Backbone.Events - // --------------- - - // A module that can be mixed in to *any object* in order to provide it with - // custom events. You may bind with `on` or remove with `off` callback - // functions to an event; `trigger`-ing an event fires all callbacks in - // succession. - // - // var object = {}; - // _.extend(object, Backbone.Events); - // object.on('expand', function(){ alert('expanded'); }); - // object.trigger('expand'); - // - var Events = Backbone.Events = { - - // Bind an event to a `callback` function. Passing `"all"` will bind - // the callback to all events fired. - on: function(name, callback, context) { - if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; - this._events || (this._events = {}); - var events = this._events[name] || (this._events[name] = []); - events.push({callback: callback, context: context, ctx: context || this}); - return this; - }, - - // Bind an event to only be triggered a single time. After the first time - // the callback is invoked, it will be removed. - once: function(name, callback, context) { - if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; - var self = this; - var once = _.once(function() { - self.off(name, once); - callback.apply(this, arguments); - }); - once._callback = callback; - return this.on(name, once, context); - }, - - // Remove one or many callbacks. If `context` is null, removes all - // callbacks with that function. If `callback` is null, removes all - // callbacks for the event. If `name` is null, removes all bound - // callbacks for all events. - off: function(name, callback, context) { - var retain, ev, events, names, i, l, j, k; - if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; - if (!name && !callback && !context) { - this._events = {}; - return this; - } - names = name ? [name] : _.keys(this._events); - for (i = 0, l = names.length; i < l; i++) { - name = names[i]; - if (events = this._events[name]) { - this._events[name] = retain = []; - if (callback || context) { - for (j = 0, k = events.length; j < k; j++) { - ev = events[j]; - if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || - (context && context !== ev.context)) { - retain.push(ev); - } - } - } - if (!retain.length) delete this._events[name]; - } - } - - return this; - }, - - // Trigger one or many events, firing all bound callbacks. Callbacks are - // passed the same arguments as `trigger` is, apart from the event name - // (unless you're listening on `"all"`, which will cause your callback to - // receive the true name of the event as the first argument). - trigger: function(name) { - if (!this._events) return this; - var args = slice.call(arguments, 1); - if (!eventsApi(this, 'trigger', name, args)) return this; - var events = this._events[name]; - var allEvents = this._events.all; - if (events) triggerEvents(events, args); - if (allEvents) triggerEvents(allEvents, arguments); - return this; - }, - - // Tell this object to stop listening to either specific events ... or - // to every object it's currently listening to. - stopListening: function(obj, name, callback) { - var listeningTo = this._listeningTo; - if (!listeningTo) return this; - var remove = !name && !callback; - if (!callback && typeof name === 'object') callback = this; - if (obj) (listeningTo = {})[obj._listenId] = obj; - for (var id in listeningTo) { - obj = listeningTo[id]; - obj.off(name, callback, this); - if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; - } - return this; - } - - }; - - // Regular expression used to split event strings. - var eventSplitter = /\s+/; - - // Implement fancy features of the Events API such as multiple event - // names `"change blur"` and jQuery-style event maps `{change: action}` - // in terms of the existing API. - var eventsApi = function(obj, action, name, rest) { - if (!name) return true; - - // Handle event maps. - if (typeof name === 'object') { - for (var key in name) { - obj[action].apply(obj, [key, name[key]].concat(rest)); - } - return false; - } - - // Handle space separated event names. - if (eventSplitter.test(name)) { - var names = name.split(eventSplitter); - for (var i = 0, l = names.length; i < l; i++) { - obj[action].apply(obj, [names[i]].concat(rest)); - } - return false; - } - - return true; - }; - - // A difficult-to-believe, but optimized internal dispatch function for - // triggering events. Tries to keep the usual cases speedy (most internal - // Backbone events have 3 arguments). - var triggerEvents = function(events, args) { - var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; - switch (args.length) { - case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; - case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; - case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; - case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; - default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); - } - }; - - var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; - - // Inversion-of-control versions of `on` and `once`. Tell *this* object to - // listen to an event in another object ... keeping track of what it's - // listening to. - _.each(listenMethods, function(implementation, method) { - Events[method] = function(obj, name, callback) { - var listeningTo = this._listeningTo || (this._listeningTo = {}); - var id = obj._listenId || (obj._listenId = _.uniqueId('l')); - listeningTo[id] = obj; - if (!callback && typeof name === 'object') callback = this; - obj[implementation](name, callback, this); - return this; - }; - }); - - // Aliases for backwards compatibility. - Events.bind = Events.on; - Events.unbind = Events.off; - - // Allow the `Backbone` object to serve as a global event bus, for folks who - // want global "pubsub" in a convenient place. - _.extend(Backbone, Events); - - // Backbone.Model - // -------------- - - // Backbone **Models** are the basic data object in the framework -- - // frequently representing a row in a table in a database on your server. - // A discrete chunk of data and a bunch of useful, related methods for - // performing computations and transformations on that data. - - // Create a new model with the specified attributes. A client id (`cid`) - // is automatically generated and assigned for you. - var Model = Backbone.Model = function(attributes, options) { - var attrs = attributes || {}; - options || (options = {}); - this.cid = _.uniqueId('c'); - this.attributes = {}; - if (options.collection) this.collection = options.collection; - if (options.parse) attrs = this.parse(attrs, options) || {}; - attrs = _.defaults({}, attrs, _.result(this, 'defaults')); - this.set(attrs, options); - this.changed = {}; - this.initialize.apply(this, arguments); - }; - - // Attach all inheritable methods to the Model prototype. - _.extend(Model.prototype, Events, { - - // A hash of attributes whose current and previous value differ. - changed: null, - - // The value returned during the last failed validation. - validationError: null, - - // The default name for the JSON `id` attribute is `"id"`. MongoDB and - // CouchDB users may want to set this to `"_id"`. - idAttribute: 'id', - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // Return a copy of the model's `attributes` object. - toJSON: function(options) { - return _.clone(this.attributes); - }, - - // Proxy `Backbone.sync` by default -- but override this if you need - // custom syncing semantics for *this* particular model. - sync: function() { - return Backbone.sync.apply(this, arguments); - }, - - // Get the value of an attribute. - get: function(attr) { - return this.attributes[attr]; - }, - - // Get the HTML-escaped value of an attribute. - escape: function(attr) { - return _.escape(this.get(attr)); - }, - - // Returns `true` if the attribute contains a value that is not null - // or undefined. - has: function(attr) { - return this.get(attr) != null; - }, - - // Set a hash of model attributes on the object, firing `"change"`. This is - // the core primitive operation of a model, updating the data and notifying - // anyone who needs to know about the change in state. The heart of the beast. - set: function(key, val, options) { - var attr, attrs, unset, changes, silent, changing, prev, current; - if (key == null) return this; - - // Handle both `"key", value` and `{key: value}` -style arguments. - if (typeof key === 'object') { - attrs = key; - options = val; - } else { - (attrs = {})[key] = val; - } - - options || (options = {}); - - // Run validation. - if (!this._validate(attrs, options)) return false; - - // Extract attributes and options. - unset = options.unset; - silent = options.silent; - changes = []; - changing = this._changing; - this._changing = true; - - if (!changing) { - this._previousAttributes = _.clone(this.attributes); - this.changed = {}; - } - current = this.attributes, prev = this._previousAttributes; - - // Check for changes of `id`. - if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; - - // For each `set` attribute, update or delete the current value. - for (attr in attrs) { - val = attrs[attr]; - if (!_.isEqual(current[attr], val)) changes.push(attr); - if (!_.isEqual(prev[attr], val)) { - this.changed[attr] = val; - } else { - delete this.changed[attr]; - } - unset ? delete current[attr] : current[attr] = val; - } - - // Trigger all relevant attribute changes. - if (!silent) { - if (changes.length) this._pending = true; - for (var i = 0, l = changes.length; i < l; i++) { - this.trigger('change:' + changes[i], this, current[changes[i]], options); - } - } - - // You might be wondering why there's a `while` loop here. Changes can - // be recursively nested within `"change"` events. - if (changing) return this; - if (!silent) { - while (this._pending) { - this._pending = false; - this.trigger('change', this, options); - } - } - this._pending = false; - this._changing = false; - return this; - }, - - // Remove an attribute from the model, firing `"change"`. `unset` is a noop - // if the attribute doesn't exist. - unset: function(attr, options) { - return this.set(attr, void 0, _.extend({}, options, {unset: true})); - }, - - // Clear all attributes on the model, firing `"change"`. - clear: function(options) { - var attrs = {}; - for (var key in this.attributes) attrs[key] = void 0; - return this.set(attrs, _.extend({}, options, {unset: true})); - }, - - // Determine if the model has changed since the last `"change"` event. - // If you specify an attribute name, determine if that attribute has changed. - hasChanged: function(attr) { - if (attr == null) return !_.isEmpty(this.changed); - return _.has(this.changed, attr); - }, - - // Return an object containing all the attributes that have changed, or - // false if there are no changed attributes. Useful for determining what - // parts of a view need to be updated and/or what attributes need to be - // persisted to the server. Unset attributes will be set to undefined. - // You can also pass an attributes object to diff against the model, - // determining if there *would be* a change. - changedAttributes: function(diff) { - if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; - var val, changed = false; - var old = this._changing ? this._previousAttributes : this.attributes; - for (var attr in diff) { - if (_.isEqual(old[attr], (val = diff[attr]))) continue; - (changed || (changed = {}))[attr] = val; - } - return changed; - }, - - // Get the previous value of an attribute, recorded at the time the last - // `"change"` event was fired. - previous: function(attr) { - if (attr == null || !this._previousAttributes) return null; - return this._previousAttributes[attr]; - }, - - // Get all of the attributes of the model at the time of the previous - // `"change"` event. - previousAttributes: function() { - return _.clone(this._previousAttributes); - }, - - // Fetch the model from the server. If the server's representation of the - // model differs from its current attributes, they will be overridden, - // triggering a `"change"` event. - fetch: function(options) { - options = options ? _.clone(options) : {}; - if (options.parse === void 0) options.parse = true; - var model = this; - var success = options.success; - options.success = function(resp) { - if (!model.set(model.parse(resp, options), options)) return false; - if (success) success(model, resp, options); - model.trigger('sync', model, resp, options); - }; - wrapError(this, options); - return this.sync('read', this, options); - }, - - // Set a hash of model attributes, and sync the model to the server. - // If the server returns an attributes hash that differs, the model's - // state will be `set` again. - save: function(key, val, options) { - var attrs, method, xhr, attributes = this.attributes; - - // Handle both `"key", value` and `{key: value}` -style arguments. - if (key == null || typeof key === 'object') { - attrs = key; - options = val; - } else { - (attrs = {})[key] = val; - } - - options = _.extend({validate: true}, options); - - // If we're not waiting and attributes exist, save acts as - // `set(attr).save(null, opts)` with validation. Otherwise, check if - // the model will be valid when the attributes, if any, are set. - if (attrs && !options.wait) { - if (!this.set(attrs, options)) return false; - } else { - if (!this._validate(attrs, options)) return false; - } - - // Set temporary attributes if `{wait: true}`. - if (attrs && options.wait) { - this.attributes = _.extend({}, attributes, attrs); - } - - // After a successful server-side save, the client is (optionally) - // updated with the server-side state. - if (options.parse === void 0) options.parse = true; - var model = this; - var success = options.success; - options.success = function(resp) { - // Ensure attributes are restored during synchronous saves. - model.attributes = attributes; - var serverAttrs = model.parse(resp, options); - if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); - if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { - return false; - } - if (success) success(model, resp, options); - model.trigger('sync', model, resp, options); - }; - wrapError(this, options); - - method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); - if (method === 'patch') options.attrs = attrs; - xhr = this.sync(method, this, options); - - // Restore attributes. - if (attrs && options.wait) this.attributes = attributes; - - return xhr; - }, - - // Destroy this model on the server if it was already persisted. - // Optimistically removes the model from its collection, if it has one. - // If `wait: true` is passed, waits for the server to respond before removal. - destroy: function(options) { - options = options ? _.clone(options) : {}; - var model = this; - var success = options.success; - - var destroy = function() { - model.trigger('destroy', model, model.collection, options); - }; - - options.success = function(resp) { - if (options.wait || model.isNew()) destroy(); - if (success) success(model, resp, options); - if (!model.isNew()) model.trigger('sync', model, resp, options); - }; - - if (this.isNew()) { - options.success(); - return false; - } - wrapError(this, options); - - var xhr = this.sync('delete', this, options); - if (!options.wait) destroy(); - return xhr; - }, - - // Default URL for the model's representation on the server -- if you're - // using Backbone's restful methods, override this to change the endpoint - // that will be called. - url: function() { - var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); - if (this.isNew()) return base; - return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); - }, - - // **parse** converts a response into the hash of attributes to be `set` on - // the model. The default implementation is just to pass the response along. - parse: function(resp, options) { - return resp; - }, - - // Create a new model with identical attributes to this one. - clone: function() { - return new this.constructor(this.attributes); - }, - - // A model is new if it has never been saved to the server, and lacks an id. - isNew: function() { - return this.id == null; - }, - - // Check if the model is currently in a valid state. - isValid: function(options) { - return this._validate({}, _.extend(options || {}, { validate: true })); - }, - - // Run validation against the next complete set of model attributes, - // returning `true` if all is well. Otherwise, fire an `"invalid"` event. - _validate: function(attrs, options) { - if (!options.validate || !this.validate) return true; - attrs = _.extend({}, this.attributes, attrs); - var error = this.validationError = this.validate(attrs, options) || null; - if (!error) return true; - this.trigger('invalid', this, error, _.extend(options, {validationError: error})); - return false; - } - - }); - - // Underscore methods that we want to implement on the Model. - var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; - - // Mix in each Underscore method as a proxy to `Model#attributes`. - _.each(modelMethods, function(method) { - Model.prototype[method] = function() { - var args = slice.call(arguments); - args.unshift(this.attributes); - return _[method].apply(_, args); - }; - }); - - // Backbone.Collection - // ------------------- - - // If models tend to represent a single row of data, a Backbone Collection is - // more analagous to a table full of data ... or a small slice or page of that - // table, or a collection of rows that belong together for a particular reason - // -- all of the messages in this particular folder, all of the documents - // belonging to this particular author, and so on. Collections maintain - // indexes of their models, both in order, and for lookup by `id`. - - // Create a new **Collection**, perhaps to contain a specific type of `model`. - // If a `comparator` is specified, the Collection will maintain - // its models in sort order, as they're added and removed. - var Collection = Backbone.Collection = function(models, options) { - options || (options = {}); - if (options.model) this.model = options.model; - if (options.comparator !== void 0) this.comparator = options.comparator; - this._reset(); - this.initialize.apply(this, arguments); - if (models) this.reset(models, _.extend({silent: true}, options)); - }; - - // Default options for `Collection#set`. - var setOptions = {add: true, remove: true, merge: true}; - var addOptions = {add: true, remove: false}; - - // Define the Collection's inheritable methods. - _.extend(Collection.prototype, Events, { - - // The default model for a collection is just a **Backbone.Model**. - // This should be overridden in most cases. - model: Model, - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // The JSON representation of a Collection is an array of the - // models' attributes. - toJSON: function(options) { - return this.map(function(model){ return model.toJSON(options); }); - }, - - // Proxy `Backbone.sync` by default. - sync: function() { - return Backbone.sync.apply(this, arguments); - }, - - // Add a model, or list of models to the set. - add: function(models, options) { - return this.set(models, _.extend({merge: false}, options, addOptions)); - }, - - // Remove a model, or a list of models from the set. - remove: function(models, options) { - var singular = !_.isArray(models); - models = singular ? [models] : _.clone(models); - options || (options = {}); - var i, l, index, model; - for (i = 0, l = models.length; i < l; i++) { - model = models[i] = this.get(models[i]); - if (!model) continue; - delete this._byId[model.id]; - delete this._byId[model.cid]; - index = this.indexOf(model); - this.models.splice(index, 1); - this.length--; - if (!options.silent) { - options.index = index; - model.trigger('remove', model, this, options); - } - this._removeReference(model); - } - return singular ? models[0] : models; - }, - - // Update a collection by `set`-ing a new list of models, adding new ones, - // removing models that are no longer present, and merging models that - // already exist in the collection, as necessary. Similar to **Model#set**, - // the core operation for updating the data contained by the collection. - set: function(models, options) { - options = _.defaults({}, options, setOptions); - if (options.parse) models = this.parse(models, options); - var singular = !_.isArray(models); - models = singular ? (models ? [models] : []) : _.clone(models); - var i, l, id, model, attrs, existing, sort; - var at = options.at; - var targetModel = this.model; - var sortable = this.comparator && (at == null) && options.sort !== false; - var sortAttr = _.isString(this.comparator) ? this.comparator : null; - var toAdd = [], toRemove = [], modelMap = {}; - var add = options.add, merge = options.merge, remove = options.remove; - var order = !sortable && add && remove ? [] : false; - - // Turn bare objects into model references, and prevent invalid models - // from being added. - for (i = 0, l = models.length; i < l; i++) { - attrs = models[i]; - if (attrs instanceof Model) { - id = model = attrs; - } else { - id = attrs[targetModel.prototype.idAttribute]; - } - - // If a duplicate is found, prevent it from being added and - // optionally merge it into the existing model. - if (existing = this.get(id)) { - if (remove) modelMap[existing.cid] = true; - if (merge) { - attrs = attrs === model ? model.attributes : attrs; - if (options.parse) attrs = existing.parse(attrs, options); - existing.set(attrs, options); - if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; - } - models[i] = existing; - - // If this is a new, valid model, push it to the `toAdd` list. - } else if (add) { - model = models[i] = this._prepareModel(attrs, options); - if (!model) continue; - toAdd.push(model); - - // Listen to added models' events, and index models for lookup by - // `id` and by `cid`. - model.on('all', this._onModelEvent, this); - this._byId[model.cid] = model; - if (model.id != null) this._byId[model.id] = model; - } - if (order) order.push(existing || model); - } - - // Remove nonexistent models if appropriate. - if (remove) { - for (i = 0, l = this.length; i < l; ++i) { - if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); - } - if (toRemove.length) this.remove(toRemove, options); - } - - // See if sorting is needed, update `length` and splice in new models. - if (toAdd.length || (order && order.length)) { - if (sortable) sort = true; - this.length += toAdd.length; - if (at != null) { - for (i = 0, l = toAdd.length; i < l; i++) { - this.models.splice(at + i, 0, toAdd[i]); - } - } else { - if (order) this.models.length = 0; - var orderedModels = order || toAdd; - for (i = 0, l = orderedModels.length; i < l; i++) { - this.models.push(orderedModels[i]); - } - } - } - - // Silently sort the collection if appropriate. - if (sort) this.sort({silent: true}); - - // Unless silenced, it's time to fire all appropriate add/sort events. - if (!options.silent) { - for (i = 0, l = toAdd.length; i < l; i++) { - (model = toAdd[i]).trigger('add', model, this, options); - } - if (sort || (order && order.length)) this.trigger('sort', this, options); - } - - // Return the added (or merged) model (or models). - return singular ? models[0] : models; - }, - - // When you have more items than you want to add or remove individually, - // you can reset the entire set with a new list of models, without firing - // any granular `add` or `remove` events. Fires `reset` when finished. - // Useful for bulk operations and optimizations. - reset: function(models, options) { - options || (options = {}); - for (var i = 0, l = this.models.length; i < l; i++) { - this._removeReference(this.models[i]); - } - options.previousModels = this.models; - this._reset(); - models = this.add(models, _.extend({silent: true}, options)); - if (!options.silent) this.trigger('reset', this, options); - return models; - }, - - // Add a model to the end of the collection. - push: function(model, options) { - return this.add(model, _.extend({at: this.length}, options)); - }, - - // Remove a model from the end of the collection. - pop: function(options) { - var model = this.at(this.length - 1); - this.remove(model, options); - return model; - }, - - // Add a model to the beginning of the collection. - unshift: function(model, options) { - return this.add(model, _.extend({at: 0}, options)); - }, - - // Remove a model from the beginning of the collection. - shift: function(options) { - var model = this.at(0); - this.remove(model, options); - return model; - }, - - // Slice out a sub-array of models from the collection. - slice: function() { - return slice.apply(this.models, arguments); - }, - - // Get a model from the set by id. - get: function(obj) { - if (obj == null) return void 0; - return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj]; - }, - - // Get the model at the given index. - at: function(index) { - return this.models[index]; - }, - - // Return models with matching attributes. Useful for simple cases of - // `filter`. - where: function(attrs, first) { - if (_.isEmpty(attrs)) return first ? void 0 : []; - return this[first ? 'find' : 'filter'](function(model) { - for (var key in attrs) { - if (attrs[key] !== model.get(key)) return false; - } - return true; - }); - }, - - // Return the first model with matching attributes. Useful for simple cases - // of `find`. - findWhere: function(attrs) { - return this.where(attrs, true); - }, - - // Force the collection to re-sort itself. You don't need to call this under - // normal circumstances, as the set will maintain sort order as each item - // is added. - sort: function(options) { - if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); - options || (options = {}); - - // Run sort based on type of `comparator`. - if (_.isString(this.comparator) || this.comparator.length === 1) { - this.models = this.sortBy(this.comparator, this); - } else { - this.models.sort(_.bind(this.comparator, this)); - } - - if (!options.silent) this.trigger('sort', this, options); - return this; - }, - - // Pluck an attribute from each model in the collection. - pluck: function(attr) { - return _.invoke(this.models, 'get', attr); - }, - - // Fetch the default set of models for this collection, resetting the - // collection when they arrive. If `reset: true` is passed, the response - // data will be passed through the `reset` method instead of `set`. - fetch: function(options) { - options = options ? _.clone(options) : {}; - if (options.parse === void 0) options.parse = true; - var success = options.success; - var collection = this; - options.success = function(resp) { - var method = options.reset ? 'reset' : 'set'; - collection[method](resp, options); - if (success) success(collection, resp, options); - collection.trigger('sync', collection, resp, options); - }; - wrapError(this, options); - return this.sync('read', this, options); - }, - - // Create a new instance of a model in this collection. Add the model to the - // collection immediately, unless `wait: true` is passed, in which case we - // wait for the server to agree. - create: function(model, options) { - options = options ? _.clone(options) : {}; - if (!(model = this._prepareModel(model, options))) return false; - if (!options.wait) this.add(model, options); - var collection = this; - var success = options.success; - options.success = function(model, resp, options) { - if (options.wait) collection.add(model, options); - if (success) success(model, resp, options); - }; - model.save(null, options); - return model; - }, - - // **parse** converts a response into a list of models to be added to the - // collection. The default implementation is just to pass it through. - parse: function(resp, options) { - return resp; - }, - - // Create a new collection with an identical list of models as this one. - clone: function() { - return new this.constructor(this.models); - }, - - // Private method to reset all internal state. Called when the collection - // is first initialized or reset. - _reset: function() { - this.length = 0; - this.models = []; - this._byId = {}; - }, - - // Prepare a hash of attributes (or other model) to be added to this - // collection. - _prepareModel: function(attrs, options) { - if (attrs instanceof Model) { - if (!attrs.collection) attrs.collection = this; - return attrs; - } - options = options ? _.clone(options) : {}; - options.collection = this; - var model = new this.model(attrs, options); - if (!model.validationError) return model; - this.trigger('invalid', this, model.validationError, options); - return false; - }, - - // Internal method to sever a model's ties to a collection. - _removeReference: function(model) { - if (this === model.collection) delete model.collection; - model.off('all', this._onModelEvent, this); - }, - - // Internal method called every time a model in the set fires an event. - // Sets need to update their indexes when models change ids. All other - // events simply proxy through. "add" and "remove" events that originate - // in other collections are ignored. - _onModelEvent: function(event, model, collection, options) { - if ((event === 'add' || event === 'remove') && collection !== this) return; - if (event === 'destroy') this.remove(model, options); - if (model && event === 'change:' + model.idAttribute) { - delete this._byId[model.previous(model.idAttribute)]; - if (model.id != null) this._byId[model.id] = model; - } - this.trigger.apply(this, arguments); - } - - }); - - // Underscore methods that we want to implement on the Collection. - // 90% of the core usefulness of Backbone Collections is actually implemented - // right here: - var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', - 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', - 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', - 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', - 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', - 'lastIndexOf', 'isEmpty', 'chain']; - - // Mix in each Underscore method as a proxy to `Collection#models`. - _.each(methods, function(method) { - Collection.prototype[method] = function() { - var args = slice.call(arguments); - args.unshift(this.models); - return _[method].apply(_, args); - }; - }); - - // Underscore methods that take a property name as an argument. - var attributeMethods = ['groupBy', 'countBy', 'sortBy']; - - // Use attributes instead of properties. - _.each(attributeMethods, function(method) { - Collection.prototype[method] = function(value, context) { - var iterator = _.isFunction(value) ? value : function(model) { - return model.get(value); - }; - return _[method](this.models, iterator, context); - }; - }); - - // Backbone.View - // ------------- - - // Backbone Views are almost more convention than they are actual code. A View - // is simply a JavaScript object that represents a logical chunk of UI in the - // DOM. This might be a single item, an entire list, a sidebar or panel, or - // even the surrounding frame which wraps your whole app. Defining a chunk of - // UI as a **View** allows you to define your DOM events declaratively, without - // having to worry about render order ... and makes it easy for the view to - // react to specific changes in the state of your models. - - // Creating a Backbone.View creates its initial element outside of the DOM, - // if an existing element is not provided... - var View = Backbone.View = function(options) { - this.cid = _.uniqueId('view'); - options || (options = {}); - _.extend(this, _.pick(options, viewOptions)); - this._ensureElement(); - this.initialize.apply(this, arguments); - this.delegateEvents(); - }; - - // Cached regex to split keys for `delegate`. - var delegateEventSplitter = /^(\S+)\s*(.*)$/; - - // List of view options to be merged as properties. - var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; - - // Set up all inheritable **Backbone.View** properties and methods. - _.extend(View.prototype, Events, { - - // The default `tagName` of a View's element is `"div"`. - tagName: 'div', - - // jQuery delegate for element lookup, scoped to DOM elements within the - // current view. This should be preferred to global lookups where possible. - $: function(selector) { - return this.$el.find(selector); - }, - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // **render** is the core function that your view should override, in order - // to populate its element (`this.el`), with the appropriate HTML. The - // convention is for **render** to always return `this`. - render: function() { - return this; - }, - - // Remove this view by taking the element out of the DOM, and removing any - // applicable Backbone.Events listeners. - remove: function() { - this.$el.remove(); - this.stopListening(); - return this; - }, - - // Change the view's element (`this.el` property), including event - // re-delegation. - setElement: function(element, delegate) { - if (this.$el) this.undelegateEvents(); - this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); - this.el = this.$el[0]; - if (delegate !== false) this.delegateEvents(); - return this; - }, - - // Set callbacks, where `this.events` is a hash of - // - // *{"event selector": "callback"}* - // - // { - // 'mousedown .title': 'edit', - // 'click .button': 'save', - // 'click .open': function(e) { ... } - // } - // - // pairs. Callbacks will be bound to the view, with `this` set properly. - // Uses event delegation for efficiency. - // Omitting the selector binds the event to `this.el`. - // This only works for delegate-able events: not `focus`, `blur`, and - // not `change`, `submit`, and `reset` in Internet Explorer. - delegateEvents: function(events) { - if (!(events || (events = _.result(this, 'events')))) return this; - this.undelegateEvents(); - for (var key in events) { - var method = events[key]; - if (!_.isFunction(method)) method = this[events[key]]; - if (!method) continue; - - var match = key.match(delegateEventSplitter); - var eventName = match[1], selector = match[2]; - method = _.bind(method, this); - eventName += '.delegateEvents' + this.cid; - if (selector === '') { - this.$el.on(eventName, method); - } else { - this.$el.on(eventName, selector, method); - } - } - return this; - }, - - // Clears all callbacks previously bound to the view with `delegateEvents`. - // You usually don't need to use this, but may wish to if you have multiple - // Backbone views attached to the same DOM element. - undelegateEvents: function() { - this.$el.off('.delegateEvents' + this.cid); - return this; - }, - - // Ensure that the View has a DOM element to render into. - // If `this.el` is a string, pass it through `$()`, take the first - // matching element, and re-assign it to `el`. Otherwise, create - // an element from the `id`, `className` and `tagName` properties. - _ensureElement: function() { - if (!this.el) { - var attrs = _.extend({}, _.result(this, 'attributes')); - if (this.id) attrs.id = _.result(this, 'id'); - if (this.className) attrs['class'] = _.result(this, 'className'); - var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); - this.setElement($el, false); - } else { - this.setElement(_.result(this, 'el'), false); - } - } - - }); - - // Backbone.sync - // ------------- - - // Override this function to change the manner in which Backbone persists - // models to the server. You will be passed the type of request, and the - // model in question. By default, makes a RESTful Ajax request - // to the model's `url()`. Some possible customizations could be: - // - // * Use `setTimeout` to batch rapid-fire updates into a single request. - // * Send up the models as XML instead of JSON. - // * Persist models via WebSockets instead of Ajax. - // - // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests - // as `POST`, with a `_method` parameter containing the true HTTP method, - // as well as all requests with the body as `application/x-www-form-urlencoded` - // instead of `application/json` with the model in a param named `model`. - // Useful when interfacing with server-side languages like **PHP** that make - // it difficult to read the body of `PUT` requests. - Backbone.sync = function(method, model, options) { - var type = methodMap[method]; - - // Default options, unless specified. - _.defaults(options || (options = {}), { - emulateHTTP: Backbone.emulateHTTP, - emulateJSON: Backbone.emulateJSON - }); - - // Default JSON-request options. - var params = {type: type, dataType: 'json'}; - - // Ensure that we have a URL. - if (!options.url) { - params.url = _.result(model, 'url') || urlError(); - } - - // Ensure that we have the appropriate request data. - if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { - params.contentType = 'application/json'; - params.data = JSON.stringify(options.attrs || model.toJSON(options)); - } - - // For older servers, emulate JSON by encoding the request into an HTML-form. - if (options.emulateJSON) { - params.contentType = 'application/x-www-form-urlencoded'; - params.data = params.data ? {model: params.data} : {}; - } - - // For older servers, emulate HTTP by mimicking the HTTP method with `_method` - // And an `X-HTTP-Method-Override` header. - if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { - params.type = 'POST'; - if (options.emulateJSON) params.data._method = type; - var beforeSend = options.beforeSend; - options.beforeSend = function(xhr) { - xhr.setRequestHeader('X-HTTP-Method-Override', type); - if (beforeSend) return beforeSend.apply(this, arguments); - }; - } - - // Don't process data on a non-GET request. - if (params.type !== 'GET' && !options.emulateJSON) { - params.processData = false; - } - - // If we're sending a `PATCH` request, and we're in an old Internet Explorer - // that still has ActiveX enabled by default, override jQuery to use that - // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. - if (params.type === 'PATCH' && noXhrPatch) { - params.xhr = function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }; - } - - // Make the request, allowing the user to override any Ajax options. - var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); - model.trigger('request', model, xhr, options); - return xhr; - }; - - var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); - - // Map from CRUD to HTTP for our default `Backbone.sync` implementation. - var methodMap = { - 'create': 'POST', - 'update': 'PUT', - 'patch': 'PATCH', - 'delete': 'DELETE', - 'read': 'GET' - }; - - // Set the default implementation of `Backbone.ajax` to proxy through to `$`. - // Override this if you'd like to use a different library. - Backbone.ajax = function() { - return Backbone.$.ajax.apply(Backbone.$, arguments); - }; - - // Backbone.Router - // --------------- - - // Routers map faux-URLs to actions, and fire events when routes are - // matched. Creating a new one sets its `routes` hash, if not set statically. - var Router = Backbone.Router = function(options) { - options || (options = {}); - if (options.routes) this.routes = options.routes; - this._bindRoutes(); - this.initialize.apply(this, arguments); - }; - - // Cached regular expressions for matching named param parts and splatted - // parts of route strings. - var optionalParam = /\((.*?)\)/g; - var namedParam = /(\(\?)?:\w+/g; - var splatParam = /\*\w+/g; - var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; - - // Set up all inheritable **Backbone.Router** properties and methods. - _.extend(Router.prototype, Events, { - - // Initialize is an empty function by default. Override it with your own - // initialization logic. - initialize: function(){}, - - // Manually bind a single named route to a callback. For example: - // - // this.route('search/:query/p:num', 'search', function(query, num) { - // ... - // }); - // - route: function(route, name, callback) { - if (!_.isRegExp(route)) route = this._routeToRegExp(route); - if (_.isFunction(name)) { - callback = name; - name = ''; - } - if (!callback) callback = this[name]; - var router = this; - Backbone.history.route(route, function(fragment) { - var args = router._extractParameters(route, fragment); - callback && callback.apply(router, args); - router.trigger.apply(router, ['route:' + name].concat(args)); - router.trigger('route', name, args); - Backbone.history.trigger('route', router, name, args); - }); - return this; - }, - - // Simple proxy to `Backbone.history` to save a fragment into the history. - navigate: function(fragment, options) { - Backbone.history.navigate(fragment, options); - return this; - }, - - // Bind all defined routes to `Backbone.history`. We have to reverse the - // order of the routes here to support behavior where the most general - // routes can be defined at the bottom of the route map. - _bindRoutes: function() { - if (!this.routes) return; - this.routes = _.result(this, 'routes'); - var route, routes = _.keys(this.routes); - while ((route = routes.pop()) != null) { - this.route(route, this.routes[route]); - } - }, - - // Convert a route string into a regular expression, suitable for matching - // against the current location hash. - _routeToRegExp: function(route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') - .replace(namedParam, function(match, optional) { - return optional ? match : '([^\/]+)'; - }) - .replace(splatParam, '(.*?)'); - return new RegExp('^' + route + '$'); - }, - - // Given a route, and a URL fragment that it matches, return the array of - // extracted decoded parameters. Empty or unmatched parameters will be - // treated as `null` to normalize cross-browser behavior. - _extractParameters: function(route, fragment) { - var params = route.exec(fragment).slice(1); - return _.map(params, function(param) { - return param ? decodeURIComponent(param) : null; - }); - } - - }); - - // Backbone.History - // ---------------- - - // Handles cross-browser history management, based on either - // [pushState](http://diveintohtml5.info/history.html) and real URLs, or - // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) - // and URL fragments. If the browser supports neither (old IE, natch), - // falls back to polling. - var History = Backbone.History = function() { - this.handlers = []; - _.bindAll(this, 'checkUrl'); - - // Ensure that `History` can be used outside of the browser. - if (typeof window !== 'undefined') { - this.location = window.location; - this.history = window.history; - } - }; - - // Cached regex for stripping a leading hash/slash and trailing space. - var routeStripper = /^[#\/]|\s+$/g; - - // Cached regex for stripping leading and trailing slashes. - var rootStripper = /^\/+|\/+$/g; - - // Cached regex for detecting MSIE. - var isExplorer = /msie [\w.]+/; - - // Cached regex for removing a trailing slash. - var trailingSlash = /\/$/; - - // Cached regex for stripping urls of hash and query. - var pathStripper = /[?#].*$/; - - // Has the history handling already been started? - History.started = false; - - // Set up all inheritable **Backbone.History** properties and methods. - _.extend(History.prototype, Events, { - - // The default interval to poll for hash changes, if necessary, is - // twenty times a second. - interval: 50, - - // Gets the true hash value. Cannot use location.hash directly due to bug - // in Firefox where location.hash will always be decoded. - getHash: function(window) { - var match = (window || this).location.href.match(/#(.*)$/); - return match ? match[1] : ''; - }, - - // Get the cross-browser normalized URL fragment, either from the URL, - // the hash, or the override. - getFragment: function(fragment, forcePushState) { - if (fragment == null) { - if (this._hasPushState || !this._wantsHashChange || forcePushState) { - fragment = this.location.pathname; - var root = this.root.replace(trailingSlash, ''); - if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); - } else { - fragment = this.getHash(); - } - } - return fragment.replace(routeStripper, ''); - }, - - // Start the hash change handling, returning `true` if the current URL matches - // an existing route, and `false` otherwise. - start: function(options) { - if (History.started) throw new Error("Backbone.history has already been started"); - History.started = true; - - // Figure out the initial configuration. Do we need an iframe? - // Is pushState desired ... is it available? - this.options = _.extend({root: '/'}, this.options, options); - this.root = this.options.root; - this._wantsHashChange = this.options.hashChange !== false; - this._wantsPushState = !!this.options.pushState; - this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); - var fragment = this.getFragment(); - var docMode = document.documentMode; - var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); - - // Normalize root to always include a leading and trailing slash. - this.root = ('/' + this.root + '/').replace(rootStripper, '/'); - - if (oldIE && this._wantsHashChange) { - this.iframe = Backbone.$('