You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1309 lines
57KB

  1. /**
  2. Copyright Souke (2018)
  3. contact@souke.fr
  4. Ce logiciel est un programme informatique servant à aider les producteurs
  5. à distribuer leur production en circuits courts.
  6. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  7. respectant les principes de diffusion des logiciels libres. Vous pouvez
  8. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  9. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  10. sur le site "http://www.cecill.info".
  11. En contrepartie de l'accessibilité au code source et des droits de copie,
  12. de modification et de redistribution accordés par cette licence, il n'est
  13. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  14. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  15. titulaire des droits patrimoniaux et les concédants successifs.
  16. A cet égard l'attention de l'utilisateur est attirée sur les risques
  17. associés au chargement, à l'utilisation, à la modification et/ou au
  18. développement et à la reproduction du logiciel par l'utilisateur étant
  19. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  20. manipuler et qui le réserve donc à des développeurs et des professionnels
  21. avertis possédant des connaissances informatiques approfondies. Les
  22. utilisateurs sont donc invités à charger et tester l'adéquation du
  23. logiciel à leurs besoins dans des conditions permettant d'assurer la
  24. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  25. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  26. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  27. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  28. termes.
  29. */
  30. var selector = '#app-distribution-index';
  31. if($(selector).length) {
  32. var app = new Vue({
  33. el: selector,
  34. data() {
  35. return Object.assign(
  36. {
  37. UrlManager: UrlManager,
  38. baseUrl: $('meta[name=baseurl]').attr('content'),
  39. date: null,
  40. dateFormat: null,
  41. loading: true,
  42. distribution: {
  43. active: false
  44. },
  45. producer: null,
  46. oneDistributionWeekActive: false,
  47. products: [],
  48. countActiveProducts: 0,
  49. pointsSale: [],
  50. meansPayment: [],
  51. idActivePointSale: 0,
  52. pointSaleActive: null,
  53. idDefaultPointSale: 0,
  54. countActivePointsSale: 0,
  55. countOrdersByPointSale: [],
  56. orders: [],
  57. ordersUpdate: [],
  58. countOrders: 0,
  59. users: [],
  60. deliveryNotes: [],
  61. showModalProducts: false,
  62. showModalPointsSale: false,
  63. showModalFormOrderCreate: false,
  64. orderCreate: null,
  65. showModalFormOrderUpdate: false,
  66. idOrderUpdate: 0,
  67. showViewProduct: false,
  68. idOrderView: 0,
  69. showModalPayment: false,
  70. idOrderPayment: 0,
  71. showLoading: false,
  72. tillerIsAuthenticated: false,
  73. tillerUrlAuthorizeCode: '#',
  74. tillerIsSynchro: false,
  75. checkboxSelectAllOrders: false,
  76. messageGenerateDeliveryNoteDisplayed: false,
  77. missingSubscriptions: false,
  78. loadingUpdateProductOrder: false,
  79. units: [],
  80. calendar: {
  81. mode: 'single',
  82. attrs: [],
  83. themeStyles: {
  84. wrapper: {
  85. background: '#F7F7F7',
  86. color: '#333',
  87. border: 'solid 1px #e0e0e0'
  88. },
  89. header: {
  90. padding: '10px 10px',
  91. },
  92. headerHorizontalDivider: {
  93. borderTop: 'solid rgba(255, 255, 255, 0.2) 1px',
  94. width: '80%',
  95. },
  96. weekdays: {
  97. color: '#e0e0e0',
  98. fontWeight: '600',
  99. padding: '10px 10px',
  100. fontSize: '2rem'
  101. },
  102. weeks: {
  103. padding: '0 15px 15px 15px',
  104. },
  105. dayContent: function (object) {
  106. var style = {
  107. fontSize: '2rem',
  108. padding: '16px',
  109. };
  110. if (object.isHovered || object.isFocus) {
  111. style.backgroundColor = '#F39C12';
  112. }
  113. return style;
  114. },
  115. },
  116. formats: {
  117. dayPopover: 'DD/MM/YYYY'
  118. }
  119. },
  120. }, window.vueValues);
  121. },
  122. mounted: function () {
  123. if ($('#distribution-date').size()) {
  124. this.date = new Date($('#distribution-date').html());
  125. this.dateFormat = ('0' + this.date.getDate()).slice(-2) + '/'
  126. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '/'
  127. + this.date.getFullYear();
  128. }
  129. this.init(false, true);
  130. this.loading = false;
  131. },
  132. methods: {
  133. getDate: function () {
  134. return this.formatDate(this.date);
  135. },
  136. formatDate: function (date) {
  137. if (date) {
  138. return date.getFullYear() + '-'
  139. + ('0' + (date.getMonth() + 1)).slice(-2) + '-'
  140. + ('0' + date.getDate()).slice(-2);
  141. }
  142. return false;
  143. },
  144. isDistributionToday: function () {
  145. var today = new Date();
  146. return this.date
  147. && today.getFullYear() == this.date.getFullYear()
  148. && today.getMonth() == this.date.getMonth()
  149. && today.getDay() == this.date.getDay();
  150. },
  151. init: function (idActivePointSale, displayFormOrderCreate) {
  152. var app = this;
  153. this.showLoading = true;
  154. axios.get("ajax-infos", {params: {date: this.getDate()}})
  155. .then(function (response) {
  156. app.calendar.attrs = [];
  157. app.units = response.data.units;
  158. app.distribution = response.data.distribution;
  159. app.producer = response.data.producer;
  160. app.products = response.data.products;
  161. app.initCountActiveProducts();
  162. app.meansPayment = response.data.means_payment;
  163. app.oneDistributionWeekActive = response.data.one_distribution_week_active;
  164. app.missingSubscriptions = response.data.missing_subscriptions;
  165. app.countOrders = 0;
  166. if (response.data.orders) {
  167. app.orders = JSON.parse(JSON.stringify(response.data.orders));
  168. app.ordersUpdate = JSON.parse(JSON.stringify(response.data.orders));
  169. for (i = 0; i < app.orders.length; i++) {
  170. if (app.orders[i].order_status_alias == 'ordered' || app.orders[i].order_status_alias == 'updated') {
  171. app.countOrders++;
  172. }
  173. }
  174. } else {
  175. app.orders = [];
  176. }
  177. if (response.data.order_create) {
  178. app.orderCreate = response.data.order_create;
  179. app.idDefaultPointSale = app.orderCreate.id_point_sale;
  180. }
  181. if (response.data.points_sale) {
  182. app.pointsSale = response.data.points_sale;
  183. app.initPointsSale(idActivePointSale);
  184. } else {
  185. app.pointsSale = [];
  186. }
  187. if (response.data.users) {
  188. app.users = response.data.users;
  189. }
  190. if (response.data.delivery_notes) {
  191. app.deliveryNotes = response.data.delivery_notes;
  192. }
  193. app.tillerUrlAuthorizeCode = response.data.tiller_url_authorize_code;
  194. app.tillerIsAuthenticated = response.data.tiller_is_authenticated;
  195. app.tillerIsSynchro = response.data.tiller_is_synchro;
  196. app.calendar.attrs = [];
  197. var distributions = response.data.distributions;
  198. var leave_period_dates = response.data.leave_period_dates;
  199. var dayCurrentIsDistributionActive = false;
  200. var dateFormatCompare = false;
  201. if (app.date) {
  202. dateFormatCompare = app.date.getFullYear() + '-'
  203. + ('0' + (app.date.getMonth() + 1)).slice(-2) + '-'
  204. + ('0' + app.date.getDate()).slice(-2);
  205. }
  206. if (distributions.length) {
  207. var fillMode = 'solid';
  208. var dayToday = app.formatDate(new Date());
  209. for (var i = 0; i < distributions.length; i++) {
  210. if (distributions[i].date < dayToday) {
  211. fillMode = 'outline';
  212. } else {
  213. fillMode = 'solid';
  214. }
  215. app.calendar.attrs.push({
  216. key: distributions[i].date,
  217. dates: distributions[i].date,
  218. highlight: {
  219. color: 'green',
  220. fillMode: fillMode
  221. }
  222. });
  223. if (distributions[i].date == dateFormatCompare) {
  224. dayCurrentIsDistributionActive = true;
  225. }
  226. }
  227. }
  228. // leave period
  229. if (leave_period_dates.length) {
  230. app.calendar.attrs.push({
  231. key: 'leave_period',
  232. dates: leave_period_dates,
  233. highlight: {
  234. color: 'gray',
  235. fillMode: 'solid'
  236. }
  237. });
  238. }
  239. app.showLoading = false;
  240. app.checkboxSelectAllOrders = false;
  241. let searchParams = new URLSearchParams(window.location.search);
  242. if (searchParams.has('message_generate_bl') && !app.messageGenerateDeliveryNoteDisplayed) {
  243. appAlerts.alert('info', 'Pour générer un bon de livraison, sélectionnez tout d\'abord un jour et un lieu de distribution.', 6000);
  244. app.messageGenerateDeliveryNoteDisplayed = true;
  245. }
  246. if (app.idOrderUpdate) {
  247. app.updateOrderFromUrl();
  248. }
  249. setTimeout("opendistrib_popover(); opendistrib_dropdown_tooltip();", 500);
  250. var highlightStyle = {
  251. color: 'black',
  252. fillMode: 'light'
  253. }
  254. if (dayCurrentIsDistributionActive) {
  255. highlightStyle = {
  256. color: 'orange',
  257. fillMode: 'solid'
  258. }
  259. }
  260. app.calendar.attrs.push({
  261. key: 'current',
  262. highlight: highlightStyle,
  263. dates: app.date
  264. });
  265. if(displayFormOrderCreate && searchParams.has('displayFormOrderCreate')) {
  266. app.openModalFormOrderCreate();
  267. }
  268. });
  269. },
  270. labelUnitReference: function(unit) {
  271. return label_unit_reference(unit);
  272. },
  273. getProductQuantityRemainingGlobal: function(product) {
  274. var app = this;
  275. var productQuantityRemaining = product.quantity_remaining;
  276. // format
  277. if (productQuantityRemaining && product.unit != 'piece') {
  278. productQuantityRemaining = productQuantityRemaining.toFixed(2);
  279. }
  280. return productQuantityRemaining;
  281. },
  282. initCountActiveProducts: function () {
  283. this.countActiveProducts = 0;
  284. for (var i = 0; i < this.products.length; i++) {
  285. if (this.products[i].productDistribution && this.products[i].productDistribution[0].active == 1) {
  286. this.countActiveProducts++;
  287. }
  288. }
  289. },
  290. initPointsSale: function (idActivePointSale) {
  291. this.countActivePointsSale = 0;
  292. this.setIdActivePointSale(0);
  293. for (var i = 0; i < this.pointsSale.length; i++) {
  294. if (this.pointsSale[i].pointSaleDistribution[0].delivery == 1) {
  295. this.countActivePointsSale++;
  296. this.setIdActivePointSale(this.pointsSale[i].id);
  297. }
  298. }
  299. if (this.countActivePointsSale > 1) {
  300. this.setIdActivePointSale(0);
  301. }
  302. if (idActivePointSale) {
  303. this.setIdActivePointSale(idActivePointSale);
  304. }
  305. this.countOrdersByPointSale = [];
  306. for (var i = 0; i < this.pointsSale.length; i++) {
  307. this.countOrdersByPointSale[this.pointsSale[i].id] = 0;
  308. }
  309. for (var i = 0; i < this.orders.length; i++) {
  310. this.countOrdersByPointSale[this.orders[i].id_point_sale]++;
  311. }
  312. },
  313. dayClicked: function (day) {
  314. this.date = day.date;
  315. this.dateFormat = ('0' + this.date.getDate()).slice(-2) + '/'
  316. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '/'
  317. + this.date.getFullYear();
  318. this.init();
  319. },
  320. productQuantityMaxChange: function (event) {
  321. var app = this;
  322. var quantityMax = event.currentTarget.value;
  323. axios.get("ajax-process-product-quantity-max", {
  324. params: {
  325. idDistribution: this.distribution.id,
  326. idProduct: event.currentTarget.getAttribute('data-id-product'),
  327. quantityMax: (!quantityMax || quantityMax.length === 0) ? -1 : quantityMax
  328. }
  329. })
  330. .then(function (response) {
  331. app.init(app.idActivePointSale);
  332. });
  333. },
  334. productActiveClick: function (event) {
  335. var idProduct = event.currentTarget.getAttribute('data-id-product');
  336. var activeProduct = event.currentTarget.getAttribute('data-active-product');
  337. axios.get("ajax-process-active-product", {
  338. params: {
  339. idDistribution: this.distribution.id,
  340. idProduct: idProduct,
  341. active: activeProduct
  342. }
  343. })
  344. .then(function (response) {
  345. });
  346. for (i = 0; i < this.products.length; i++) {
  347. if (this.products[i].productDistribution && this.products[i].id == idProduct) {
  348. this.products[i].productDistribution[0].active = activeProduct;
  349. }
  350. }
  351. this.initCountActiveProducts();
  352. },
  353. isOneProductMaximumQuantityExceeded: function () {
  354. for (var i = 0; i < this.products.length; i++) {
  355. if (this.isProductMaximumQuantityExceeded(this.products[i])) {
  356. return true;
  357. }
  358. }
  359. return false;
  360. },
  361. isProductMaximumQuantityExceeded: function (product) {
  362. return product.quantity_remaining
  363. && product.quantity_remaining < 0;
  364. },
  365. pointSaleActiveClick: function (event) {
  366. var idPointSale = event.currentTarget.getAttribute('data-id-point-sale');
  367. var deliveryPointSale = event.currentTarget.getAttribute('data-delivery-point-sale');
  368. axios.get("ajax-process-active-point-sale", {
  369. params: {
  370. idDistribution: this.distribution.id,
  371. idPointSale: idPointSale,
  372. delivery: deliveryPointSale
  373. }
  374. })
  375. .then(function (response) {
  376. });
  377. for (i = 0; i < this.pointsSale.length; i++) {
  378. if (this.pointsSale[i].id == idPointSale) {
  379. this.pointsSale[i].pointSaleDistribution[0].delivery = deliveryPointSale;
  380. }
  381. }
  382. this.initPointsSale();
  383. },
  384. activeDistribution: function (event) {
  385. var app = this;
  386. var active = parseInt(event.currentTarget.getAttribute('data-active'));
  387. axios.get("ajax-process-active-distribution", {
  388. params: {
  389. idDistribution: this.distribution.id,
  390. active: active
  391. }
  392. })
  393. .then(function (response) {
  394. app.init();
  395. app.alertsActiveDistribution(active, 'Distribution');
  396. });
  397. },
  398. activeWeekDistribution: function (event) {
  399. var app = this;
  400. var active = parseInt(event.currentTarget.getAttribute('data-active'));
  401. axios.get("ajax-process-active-week-distribution", {
  402. params: {
  403. date: this.date.getFullYear() + '-'
  404. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  405. + ('0' + this.date.getDate()).slice(-2),
  406. active: active
  407. }
  408. })
  409. .then(function (response) {
  410. app.init();
  411. app.alertsActiveDistribution(active, 'Semaine de distribution');
  412. });
  413. },
  414. alertsActiveDistribution: function (active, label) {
  415. if (!active) {
  416. appAlerts.alert(
  417. 'success',
  418. label + ' désactivée.',
  419. );
  420. appAlerts.alert(
  421. 'info',
  422. 'Pensez à bien rembourser les clients qui auraient passé commande en utilisant leur cagnotte.',
  423. 6000
  424. );
  425. } else {
  426. appAlerts.alert(
  427. 'success',
  428. label + ' activée.',
  429. );
  430. }
  431. },
  432. pointSaleClick: function (event) {
  433. this.setIdActivePointSale(event.currentTarget.getAttribute('data-id-point-sale'));
  434. },
  435. setIdActivePointSale: function (id) {
  436. this.idActivePointSale = id;
  437. for (key in this.pointsSale) {
  438. if (this.pointsSale[key].id == id) {
  439. this.pointSaleActive = this.pointsSale[key];
  440. }
  441. }
  442. if (!id) {
  443. this.orderCreate.id_point_sale = this.idDefaultPointSale;
  444. } else {
  445. this.orderCreate.id_point_sale = id;
  446. }
  447. setTimeout("opendistrib_popover(); opendistrib_dropdown_tooltip();", 500);
  448. },
  449. orderCreatedUpdated: function () {
  450. this.showModalFormOrderCreate = false;
  451. this.showModalFormOrderUpdate = false;
  452. this.init(this.idActivePointSale);
  453. },
  454. deleteOrderClick: function (event) {
  455. var app = this;
  456. var idOrder = event.currentTarget.getAttribute('data-id-order');
  457. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-delete", {
  458. params: {
  459. idOrder: idOrder
  460. }
  461. })
  462. .then(function (response) {
  463. app.init(app.idActivePointSale);
  464. });
  465. },
  466. updateOrderFromUrl: function () {
  467. this.initModalFormOrder();
  468. this.updateProductOrders(false);
  469. },
  470. updateOrderClick: function (event) {
  471. var idOrder = event.currentTarget.getAttribute('data-id-order');
  472. this.idOrderUpdate = idOrder;
  473. this.showModalFormOrderUpdate = true;
  474. this.initModalFormOrder();
  475. this.updateProductOrders(false);
  476. },
  477. openModalFormOrderCreate: function () {
  478. this.showModalFormOrderCreate = true;
  479. this.initModalFormOrder();
  480. this.updateProductOrders(false);
  481. },
  482. initModalFormOrder: function () {
  483. var app = this;
  484. setTimeout(function () {
  485. $('.modal-body').css('height', $(window).height());
  486. $('.modal-body').css('maxHeight', 'unset');
  487. $('.select2-order-form').select2({
  488. width: 'resolve'
  489. });
  490. $('.select2-order-form').on('select2:select', function (e) {
  491. var idUser = e.params.data.id;
  492. if (app.showModalFormOrderCreate) {
  493. Vue.set(app.orderCreate, 'id_user', idUser);
  494. }
  495. if (app.showModalFormOrderUpdate) {
  496. Vue.set(app.ordersUpdate[app.getOrderUpdateKey()], 'id_user', idUser);
  497. }
  498. });
  499. // Passage à la ligne du dessous quand on appuie sur "Entrée"
  500. $('.modal-form-order .input-quantity').keypress(function (e) {
  501. if (e.which == 13) {
  502. $(this).parent().parent().parent()
  503. .next().find('.input-quantity').focus();
  504. }
  505. });
  506. }, 500);
  507. },
  508. getOrderUpdateKey: function () {
  509. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  510. for (keyOrderUpdate in app.ordersUpdate) {
  511. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  512. return keyOrderUpdate;
  513. }
  514. }
  515. }
  516. },
  517. orderPaymentModalClick: function (event) {
  518. var idOrder = event.currentTarget.getAttribute('data-id-order');
  519. this.idOrderPayment = idOrder;
  520. this.showModalPayment = true;
  521. },
  522. getTypePayment: function (order) {
  523. if (order.amount_paid < order.amount) {
  524. return 'payment';
  525. } else {
  526. return 'refund';
  527. }
  528. },
  529. isTypePayment: function (order) {
  530. return this.getTypePayment(order) == 'payment';
  531. },
  532. getLabelPaymentRefund: function (order, labelPay, labelRefund, labelMeanPayment) {
  533. var str = '';
  534. if (this.isTypePayment(order)) {
  535. str += labelPay;
  536. } else {
  537. str += labelRefund;
  538. }
  539. str += ' ' + labelMeanPayment;
  540. return str;
  541. },
  542. orderPaymentClick: function (event) {
  543. var app = this;
  544. var idOrder = event.currentTarget.getAttribute('data-id-order');
  545. if (!idOrder) {
  546. idOrder = this.idOrderPayment;
  547. }
  548. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-payment", {
  549. params: {
  550. idOrder: idOrder,
  551. type: event.currentTarget.getAttribute('data-type'),
  552. meanPayment: event.currentTarget.getAttribute('data-mean-payment')
  553. //amount: event.currentTarget.getAttribute('data-amount')
  554. }
  555. })
  556. .then(function (response) {
  557. app.init(app.idActivePointSale);
  558. });
  559. },
  560. orderViewClick: function (event) {
  561. var currentIdOrderView = event.currentTarget.getAttribute('data-id-order');
  562. if (this.idOrderView == currentIdOrderView) {
  563. this.showViewProduct = !this.showViewProduct;
  564. } else {
  565. this.showViewProduct = true;
  566. this.idOrderView = currentIdOrderView;
  567. }
  568. },
  569. closeModalProducts: function () {
  570. this.showModalProducts = false;
  571. this.init(this.idActivePointSale);
  572. },
  573. closeModalOrderForm: function (create) {
  574. if (create) {
  575. this.showModalFormOrderCreate = false
  576. } else {
  577. this.showModalFormOrderUpdate = false
  578. }
  579. this.init(this.idActivePointSale);
  580. },
  581. cloneOrder: function (order) {
  582. var clone = Object.assign({}, order);
  583. clone.productOrder = {};
  584. for (var key in order.productOrder) {
  585. clone.productOrder[key] = order.productOrder[key];
  586. }
  587. return clone;
  588. },
  589. addSubscriptions: function () {
  590. var app = this;
  591. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-process-add-subscriptions", {
  592. params: {
  593. date: this.getDate()
  594. }
  595. })
  596. .then(function (response) {
  597. app.init(app.idActivePointSale);
  598. appAlerts.alertResponse(response);
  599. });
  600. },
  601. synchroTiller: function () {
  602. var app = this;
  603. this.showLoading = true;
  604. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-process-synchro-tiller", {
  605. params: {
  606. date: this.getDate()
  607. }
  608. })
  609. .then(function (response) {
  610. app.init(app.idActivePointSale);
  611. });
  612. },
  613. forceSynchronizeOrderTiller: function(idOrder) {
  614. var app = this;
  615. this.showLoading = true;
  616. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-force-synchronize-order-tiller", {
  617. params: {
  618. idOrder: idOrder
  619. }
  620. })
  621. .then(function (response) {
  622. app.init(app.idActivePointSale);
  623. });
  624. },
  625. authTiller: function () {
  626. },
  627. totalActivePointSale: function () {
  628. var total = 0;
  629. for (var i = 0; i < this.orders.length; i++) {
  630. if (this.orders[i].id_point_sale == this.idActivePointSale) {
  631. total += parseFloat(this.orders[i].amount);
  632. }
  633. }
  634. return total.toFixed(2);
  635. },
  636. weightActivePointSale: function () {
  637. var weight = 0;
  638. for (var i = 0; i < this.orders.length; i++) {
  639. if (this.orders[i].id_point_sale == this.idActivePointSale) {
  640. weight += parseFloat(this.orders[i].weight);
  641. }
  642. }
  643. return weight.toFixed(2);
  644. },
  645. changeSynchroTiller: function (event) {
  646. var app = this;
  647. var idOrder = event.currentTarget.getAttribute('data-id-order');
  648. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-change-synchro-tiller", {
  649. params: {
  650. idOrder: idOrder,
  651. boolSynchroTiller: event.currentTarget.checked ? 1 : 0
  652. }
  653. })
  654. .then(function (response) {
  655. app.init();
  656. });
  657. },
  658. selectAllOrdersEvent: function (event) {
  659. var bool = event.currentTarget.checked;
  660. this.selectAllOrders(bool);
  661. },
  662. selectAllOrders: function (bool) {
  663. for (var key in this.orders) {
  664. if (this.orders[key].id_point_sale == this.idActivePointSale) {
  665. this.orders[key].selected = bool;
  666. }
  667. }
  668. },
  669. oneOrderSelected: function () {
  670. for (var key in this.orders) {
  671. if (this.orders[key].selected == true) {
  672. return true;
  673. }
  674. }
  675. return false;
  676. },
  677. generateDeliveryNotePointSale: function () {
  678. if (!this.oneOrderSelected()) {
  679. this.selectAllOrders(true);
  680. }
  681. if (this.oneOrderSelected()) {
  682. var app = this;
  683. var idOrders = {};
  684. for (var key in this.orders) {
  685. if (this.orders[key].selected == true) {
  686. idOrders[key] = this.orders[key].id;
  687. }
  688. }
  689. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note-point-sale", {
  690. params: {
  691. idOrders: JSON.stringify(idOrders)
  692. }
  693. })
  694. .then(function (response) {
  695. appAlerts.alertResponse(response);
  696. app.init(app.idActivePointSale);
  697. });
  698. } else {
  699. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour générer un bon de livraison');
  700. }
  701. },
  702. generateDeliveryNoteEachUser: function () {
  703. if (!this.oneOrderSelected()) {
  704. this.selectAllOrders(true);
  705. }
  706. if (this.oneOrderSelected()) {
  707. var app = this;
  708. var idOrders = {};
  709. for (var key in this.orders) {
  710. if (this.orders[key].selected == true) {
  711. idOrders[key] = this.orders[key].id;
  712. }
  713. }
  714. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note-each-user", {
  715. params: {
  716. idOrders: JSON.stringify(idOrders)
  717. }
  718. })
  719. .then(function (response) {
  720. appAlerts.alertResponse(response);
  721. app.init(app.idActivePointSale);
  722. });
  723. } else {
  724. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour générer un bon de livraison');
  725. }
  726. },
  727. validateDeliveryNotes: function () {
  728. if (!this.oneOrderSelected()) {
  729. this.selectAllOrders(true);
  730. }
  731. if (this.oneOrderSelected()) {
  732. var app = this;
  733. var idOrders = {};
  734. for (var key in this.orders) {
  735. if (this.orders[key].selected == true) {
  736. idOrders[key] = this.orders[key].id;
  737. }
  738. }
  739. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-validate-delivery-notes", {
  740. params: {
  741. idOrders: JSON.stringify(idOrders)
  742. }
  743. })
  744. .then(function (response) {
  745. appAlerts.alertResponse(response);
  746. app.init(app.idActivePointSale);
  747. });
  748. } else {
  749. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour valider un bon de livraison');
  750. }
  751. },
  752. generateDeliveryNote: function (event) {
  753. var app = this;
  754. var idOrder = event.currentTarget.getAttribute('data-id-order');
  755. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note", {
  756. params: {
  757. idOrder: idOrder
  758. }
  759. })
  760. .then(function (response) {
  761. appAlerts.alertResponse(response);
  762. app.init(app.idActivePointSale);
  763. });
  764. },
  765. sendDeliveryNote: function (event) {
  766. var app = this;
  767. var idOrder = event.currentTarget.getAttribute('data-id-order');
  768. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-send-delivery-note", {
  769. params: {
  770. idOrder: idOrder
  771. }
  772. })
  773. .then(function (response) {
  774. appAlerts.alertResponse(response);
  775. app.init(app.idActivePointSale);
  776. });
  777. },
  778. deliveryNoteExist: function (idPointSale) {
  779. return typeof this.deliveryNotes[this.idActivePointSale] != 'undefined';
  780. },
  781. payOrders: function () {
  782. var app = this;
  783. axios.get(UrlManager.getBaseUrlAbsolute() + "cron/pay-orders", {
  784. params: {
  785. date: app.getDate()
  786. }
  787. })
  788. .then(function (response) {
  789. appAlerts.alertResponse(response);
  790. app.init(app.idActivePointSale);
  791. });
  792. },
  793. getProductOrderArrayRequest: function (order) {
  794. var productOrderArrayRequest = {};
  795. for (var key in order.productOrder) {
  796. productOrderArrayRequest[key] = {
  797. quantity: order.productOrder[key].quantity,
  798. unit: order.productOrder[key].unit,
  799. price: order.productOrder[key].price,
  800. invoice_price: order.productOrder[key].invoice_price
  801. };
  802. }
  803. return JSON.stringify(productOrderArrayRequest);
  804. },
  805. updateProductOrders: function (updatePricesOnUpdateOrder) {
  806. var app = this;
  807. app.loadingUpdateProductOrder = true;
  808. var order = null;
  809. if (app.showModalFormOrderCreate) {
  810. order = app.orderCreate;
  811. }
  812. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  813. for (keyOrderUpdate in app.ordersUpdate) {
  814. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  815. order = app.ordersUpdate[keyOrderUpdate];
  816. }
  817. }
  818. }
  819. if (order) {
  820. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-update-product-order", {
  821. params: {
  822. idDistribution: app.distribution.id,
  823. idUser: order.id_user,
  824. idPointSale: order.id_point_sale,
  825. idOrder: order.id,
  826. productOrderFormArray: app.getProductOrderArrayRequest(order)
  827. }
  828. })
  829. .then(function (response) {
  830. if (response.data) {
  831. for (idProduct in response.data) {
  832. if (app.showModalFormOrderCreate) {
  833. Vue.set(app.orderCreate.productOrder[idProduct], 'quantity_remaining', response.data[idProduct].quantity_remaining);
  834. Vue.set(app.orderCreate.productOrder[idProduct], 'prices', response.data[idProduct].prices);
  835. Vue.set(app.orderCreate.productOrder[idProduct], 'active', response.data[idProduct].active);
  836. Vue.set(app.orderCreate.productOrder[idProduct], 'price', app.getBestProductPrice(app.orderCreate, idProduct, app.orderCreate.productOrder[idProduct].quantity, false));
  837. Vue.set(app.orderCreate.productOrder[idProduct], 'price_with_tax', app.getBestProductPrice(app.orderCreate, idProduct, app.orderCreate.productOrder[idProduct].quantity, true));
  838. }
  839. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  840. for (keyOrderUpdate in app.ordersUpdate) {
  841. if (order.id == app.idOrderUpdate) {
  842. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'quantity_remaining', response.data[idProduct].quantity_remaining);
  843. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'prices', response.data[idProduct].prices);
  844. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'active', response.data[idProduct].active);
  845. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'invoice_price', response.data[idProduct].invoice_price);
  846. if (updatePricesOnUpdateOrder) {
  847. Vue.set(
  848. app.ordersUpdate[keyOrderUpdate].productOrder[idProduct],
  849. 'price',
  850. app.getBestProductPrice(app.ordersUpdate[keyOrderUpdate], idProduct, app.ordersUpdate[keyOrderUpdate].productOrder[idProduct].quantity, false));
  851. Vue.set(
  852. app.ordersUpdate[keyOrderUpdate].productOrder[idProduct],
  853. 'price_with_tax',
  854. app.getBestProductPrice(app.ordersUpdate[keyOrderUpdate], idProduct, app.ordersUpdate[keyOrderUpdate].productOrder[idProduct].quantity, true));
  855. }
  856. }
  857. }
  858. }
  859. }
  860. if (updatePricesOnUpdateOrder) {
  861. appAlerts.alert('info', 'Prix rechargés');
  862. }
  863. }
  864. app.loadingUpdateProductOrder = false;
  865. });
  866. }
  867. },
  868. updateInvoicePrices: function () {
  869. var order = null;
  870. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  871. for (keyOrderUpdate in app.ordersUpdate) {
  872. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  873. order = app.ordersUpdate[keyOrderUpdate];
  874. }
  875. }
  876. }
  877. if (order) {
  878. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-update-invoice-prices", {
  879. params: {
  880. idOrder: order.id
  881. }
  882. })
  883. .then(function (response) {
  884. app.updateProductOrders(false);
  885. appAlerts.alert('info', 'Prix facturés réinitialisés.');
  886. });
  887. }
  888. },
  889. getBestProductPrice: function (order, idProduct, theQuantity, withTax) {
  890. var product = this.getProduct(idProduct);
  891. var thePrice = 9999;
  892. var pricesArray = order.productOrder[idProduct].prices;
  893. var unitCoefficient = this.getUnitCoefficient(product.unit);
  894. if (theQuantity) {
  895. theQuantity = theQuantity / unitCoefficient;
  896. }
  897. if (pricesArray) {
  898. for (var i = 0; i < pricesArray.length; i++) {
  899. var price = pricesArray[i].price;
  900. if (withTax) {
  901. price = pricesArray[i].price_with_tax
  902. }
  903. var fromQuantity = pricesArray[i].from_quantity;
  904. if (price < thePrice && fromQuantity <= theQuantity) {
  905. thePrice = price;
  906. }
  907. }
  908. } else {
  909. if (withTax) {
  910. thePrice = getPriceWithTax(product.price, product.taxRate.value);
  911. } else {
  912. thePrice = product.price;
  913. }
  914. }
  915. if (thePrice == 9999) {
  916. return 0;
  917. } else {
  918. return thePrice;
  919. }
  920. },
  921. getProduct: function (idProduct) {
  922. for (var i = 0; i < this.products.length; i++) {
  923. if (this.products[i].id == idProduct) {
  924. return this.products[i];
  925. }
  926. }
  927. return false;
  928. },
  929. countDocuments: function (order) {
  930. var count = 0;
  931. if (order.id_delivery_note) {
  932. count++;
  933. }
  934. if (order.id_quotation) {
  935. count++;
  936. }
  937. if (order.id_invoice) {
  938. count++;
  939. }
  940. return count;
  941. },
  942. getUnitCoefficient: function (unit) {
  943. return this.units[unit].coefficient;
  944. },
  945. getProductDistribution: function (product) {
  946. if (typeof product.productDistribution !== 'undefined' && product.productDistribution[0]) {
  947. return product.productDistribution[0];
  948. }
  949. return null;
  950. },
  951. copyLinkOrder: function ($event, urlOrder) {
  952. $event.preventDefault();
  953. navigator.clipboard.writeText(urlOrder);
  954. appAlerts.alert('success', 'Lien vers la page de commande de la distribution copié.');
  955. return false;
  956. }
  957. },
  958. });
  959. Vue.component('order-state-payment', {
  960. props: ['order', 'producer'],
  961. template: '#order-state-payment'
  962. });
  963. Vue.component('modal', {
  964. template: '#modal-template'
  965. });
  966. Vue.component('order-form', {
  967. props: ['distribution', 'date', 'dateFormat', 'pointsSale', 'idActivePointSale', 'meansPayment', 'users', 'products', 'order', 'orders', 'producer', 'loadingUpdateProductOrder', 'create', 'units'],
  968. emits: ['updateProductPrice', 'updateInvoicePrices'],
  969. data: function () {
  970. return {
  971. errors: [],
  972. idPointSale: 0,
  973. idUser: 0,
  974. username: '',
  975. comment: '',
  976. baseUrl: $('meta[name=baseurl]').attr('content'),
  977. vatMode: 'all' // 'with_tax'
  978. };
  979. },
  980. template: '#order-form-template',
  981. watch: {
  982. 'order.id_user': function () {
  983. this.userChange();
  984. }
  985. },
  986. methods: {
  987. labelUnitReference: function(unit) {
  988. return label_unit_reference(unit);
  989. },
  990. checkForm: function () {
  991. this.errors = [];
  992. var countProducts = 0;
  993. for (var key in this.order.productOrder) {
  994. if (this.order.productOrder[key].quantity > 0) {
  995. countProducts++;
  996. }
  997. }
  998. if (this.order.id_point_sale
  999. && (this.order.id_user > 0 || (this.order.username && this.order.username.length))
  1000. && countProducts > 0) {
  1001. return true;
  1002. }
  1003. if (!this.order.id_point_sale) {
  1004. this.errors.push('Veuillez sélectionner un point de vente');
  1005. }
  1006. if ((!this.order.id_user || this.order.id_user == 0) && !this.order.username.length) {
  1007. this.errors.push('Veuillez sélectionner ou saisir un utilisateur');
  1008. }
  1009. if (!countProducts) {
  1010. this.errors.push('Veuillez sélectionner au moins un produit');
  1011. }
  1012. },
  1013. getProductOrderArrayRequest: function () {
  1014. var productOrderArrayRequest = {};
  1015. for (var key in this.order.productOrder) {
  1016. productOrderArrayRequest[key] = {
  1017. quantity: this.order.productOrder[key].quantity,
  1018. unit: this.order.productOrder[key].unit,
  1019. price: this.order.productOrder[key].price,
  1020. invoice_price: this.order.productOrder[key].invoice_price
  1021. };
  1022. }
  1023. return JSON.stringify(productOrderArrayRequest);
  1024. },
  1025. getPointSale: function (idPointSale) {
  1026. for (key in this.pointsSale) {
  1027. if (this.pointsSale[key].id == idPointSale) {
  1028. return this.pointsSale[key];
  1029. }
  1030. }
  1031. return false;
  1032. },
  1033. isPointSaleCreditFunctioningOptional: function (idPointSale) {
  1034. var pointSale = this.getPointSale(idPointSale);
  1035. if (pointSale && pointSale.credit_functioning == 'optional') {
  1036. return true;
  1037. }
  1038. return false;
  1039. },
  1040. submitFormCreate: function (event) {
  1041. var app = this;
  1042. if (this.checkForm()) {
  1043. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-create", {
  1044. params: {
  1045. date: this.date.getFullYear() + '-'
  1046. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  1047. + ('0' + this.date.getDate()).slice(-2),
  1048. idPointSale: this.order.id_point_sale,
  1049. idUser: this.order.id_user,
  1050. username: this.order.username,
  1051. meanPayment: this.order.mean_payment,
  1052. products: app.getProductOrderArrayRequest(),
  1053. comment: this.order.comment,
  1054. debitCredit: this.order.debitCredit
  1055. }
  1056. })
  1057. .then(function (response) {
  1058. app.order.id_point_sale = 0;
  1059. app.order.id_user = 0;
  1060. app.order.username = '';
  1061. app.order.comment = '';
  1062. for (i = 0; i < app.order.productOrder.length; i++) {
  1063. app.order.productOrder[i] = 0;
  1064. }
  1065. app.$emit('ordercreatedupdated');
  1066. });
  1067. }
  1068. },
  1069. submitFormUpdate: function (event) {
  1070. var app = this;
  1071. if (this.checkForm()) {
  1072. var data = new FormData();
  1073. data.append('date', this.date.getFullYear() + '-'
  1074. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  1075. + ('0' + this.date.getDate()).slice(-2));
  1076. data.append('idOrder', this.order.id);
  1077. data.append('idPointSale', this.order.id_point_sale);
  1078. data.append('meanPayment', this.order.mean_payment);
  1079. data.append('idUser', this.order.id_user);
  1080. data.append('username', '' + this.order.username);
  1081. data.append('products', app.getProductOrderArrayRequest());
  1082. data.append('comment', this.order.comment && this.order.comment.length ? this.order.comment : '');
  1083. data.append('debitCredit', this.order.debitCredit ? this.order.debitCredit : 0);
  1084. axios.post(UrlManager.getBaseUrlAbsolute() + "order/ajax-update", data)
  1085. .then(function (response) {
  1086. app.$emit('ordercreatedupdated');
  1087. });
  1088. }
  1089. },
  1090. productQuantityClick: function (id_product, quantity) {
  1091. if (!this.order.productOrder[id_product].quantity) {
  1092. this.order.productOrder[id_product].quantity = 0;
  1093. }
  1094. if (parseFloat(this.order.productOrder[id_product].quantity) + quantity >= 0) {
  1095. var theQuantity = (parseFloat(this.order.productOrder[id_product].quantity) + parseFloat(quantity)).toFixed(2);
  1096. var theQuantityDecimal = theQuantity % 1;
  1097. if (theQuantityDecimal == 0) {
  1098. theQuantity = parseInt(theQuantity);
  1099. }
  1100. Vue.set(this.order.productOrder[id_product], 'quantity', theQuantity);
  1101. Vue.set(this.order.productOrder[id_product], 'price', app.getBestProductPrice(this.order, id_product, theQuantity, false));
  1102. Vue.set(this.order.productOrder[id_product], 'price_with_tax', app.getBestProductPrice(this.order, id_product, theQuantity, true));
  1103. }
  1104. this.updateProductOrders(false);
  1105. },
  1106. getProduct: function (idProduct) {
  1107. for (var i = 0; i < this.products.length; i++) {
  1108. if (this.products[i].id == idProduct) {
  1109. return this.products[i];
  1110. }
  1111. }
  1112. return false;
  1113. },
  1114. productPriceChange: function (event) {
  1115. var idProduct = event.currentTarget.getAttribute('data-id-product');
  1116. var product = this.getProduct(idProduct);
  1117. if (product) {
  1118. var taxRateValue = parseFloat(product.taxRate.value);
  1119. var withTax = event.currentTarget.getAttribute('data-with-tax');
  1120. var price = 0;
  1121. var priceWithTax = 0;
  1122. var priceValue = parseFloat(event.currentTarget.value.replace(',', '.'));
  1123. if (withTax) {
  1124. priceWithTax = priceValue.toFixed(2);
  1125. price = getPrice(priceWithTax, taxRateValue);
  1126. } else {
  1127. price = priceValue.toFixed(5);
  1128. priceWithTax = getPriceWithTax(price, taxRateValue);
  1129. }
  1130. if (isNaN(price)) {
  1131. price = 0;
  1132. }
  1133. if (isNaN(priceWithTax)) {
  1134. priceWithTax = 0;
  1135. }
  1136. Vue.set(this.order.productOrder, idProduct, {
  1137. active: this.order.productOrder[idProduct].active,
  1138. quantity: this.order.productOrder[idProduct].quantity,
  1139. unit: this.order.productOrder[idProduct].unit,
  1140. price: price,
  1141. price_with_tax: priceWithTax
  1142. });
  1143. }
  1144. },
  1145. userChange: function (event) {
  1146. var app = this;
  1147. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-point-sale-favorite", {
  1148. params: {
  1149. idUser: app.order.id_user,
  1150. idDistribution: app.distribution.id
  1151. }
  1152. })
  1153. .then(function (response) {
  1154. if (app.idActivePointSale == 0) {
  1155. app.order.id_point_sale = response.data.id_favorite_point_sale;
  1156. }
  1157. app.updateProductOrders(true);
  1158. });
  1159. },
  1160. pointSaleChange: function (event) {
  1161. this.updateProductOrders(true);
  1162. },
  1163. updateProductOrders: function (updateProductOrders) {
  1164. this.$emit('updateproductorders', updateProductOrders);
  1165. },
  1166. updateInvoicePrices: function () {
  1167. this.$emit('updateinvoiceprices');
  1168. },
  1169. toggleVatMode: function () {
  1170. if (this.vatMode == 'all') {
  1171. this.vatMode = 'with_tax';
  1172. } else {
  1173. this.vatMode = 'all';
  1174. }
  1175. },
  1176. getProductQuantityMax: function(product) {
  1177. return product.quantity_max;
  1178. },
  1179. getProductQuantityOrder: function(product) {
  1180. var productQuantityOrder = 0;
  1181. for (key in this.orders) {
  1182. productQuantityOrder += this.getProductQuantityProductOrder(this.orders[key], product);
  1183. }
  1184. if (this.create == 1) {
  1185. productQuantityOrder += this.getProductQuantityProductOrder(this.order, product);
  1186. }
  1187. return productQuantityOrder;
  1188. },
  1189. getProductQuantityRemaining: function (order, product) {
  1190. var productQuantityRemaining = order.productOrder[product.id].quantity_remaining;
  1191. // format
  1192. if (productQuantityRemaining && product.unit != 'piece') {
  1193. productQuantityRemaining = productQuantityRemaining.toFixed(2);
  1194. }
  1195. return productQuantityRemaining;
  1196. },
  1197. getProductQuantityProductOrder: function (order, product) {
  1198. var productOrder = order.productOrder[product.id];
  1199. var unit = productOrder.unit;
  1200. var unitCoefficient = this.getUnitCoefficient(unit);
  1201. return parseFloat(productOrder.quantity / unitCoefficient);
  1202. },
  1203. getUnitCoefficient: function (unit) {
  1204. return this.units[unit].coefficient;
  1205. },
  1206. getProductDistribution: function (product) {
  1207. if (typeof product.productDistribution !== 'undefined' && product.productDistribution[0]) {
  1208. return product.productDistribution[0];
  1209. }
  1210. }
  1211. }
  1212. });
  1213. }