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.

1370 lines
60KB

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