Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1257 lines
55KB

  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();
  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) {
  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: 'blue',
  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. });
  266. },
  267. initCountActiveProducts: function () {
  268. this.countActiveProducts = 0;
  269. for (var i = 0; i < this.products.length; i++) {
  270. if (this.products[i].productDistribution && this.products[i].productDistribution[0].active == 1) {
  271. this.countActiveProducts++;
  272. }
  273. }
  274. },
  275. initPointsSale: function (idActivePointSale) {
  276. this.countActivePointsSale = 0;
  277. this.setIdActivePointSale(0);
  278. for (var i = 0; i < this.pointsSale.length; i++) {
  279. if (this.pointsSale[i].pointSaleDistribution[0].delivery == 1) {
  280. this.countActivePointsSale++;
  281. this.setIdActivePointSale(this.pointsSale[i].id);
  282. }
  283. }
  284. if (this.countActivePointsSale > 1) {
  285. this.setIdActivePointSale(0);
  286. }
  287. if (idActivePointSale) {
  288. this.setIdActivePointSale(idActivePointSale);
  289. }
  290. this.countOrdersByPointSale = [];
  291. for (var i = 0; i < this.pointsSale.length; i++) {
  292. this.countOrdersByPointSale[this.pointsSale[i].id] = 0;
  293. }
  294. for (var i = 0; i < this.orders.length; i++) {
  295. this.countOrdersByPointSale[this.orders[i].id_point_sale]++;
  296. }
  297. },
  298. dayClicked: function (day) {
  299. this.date = day.date;
  300. this.dateFormat = ('0' + this.date.getDate()).slice(-2) + '/'
  301. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '/'
  302. + this.date.getFullYear();
  303. this.init();
  304. },
  305. productQuantityMaxChange: function (event) {
  306. var quantityMax = event.currentTarget.value;
  307. axios.get("ajax-process-product-quantity-max", {
  308. params: {
  309. idDistribution: this.distribution.id,
  310. idProduct: event.currentTarget.getAttribute('data-id-product'),
  311. quantityMax: (!quantityMax || quantityMax.length === 0) ? -1 : quantityMax
  312. }
  313. })
  314. .then(function (response) {
  315. });
  316. },
  317. productActiveClick: function (event) {
  318. var idProduct = event.currentTarget.getAttribute('data-id-product');
  319. var activeProduct = event.currentTarget.getAttribute('data-active-product');
  320. axios.get("ajax-process-active-product", {
  321. params: {
  322. idDistribution: this.distribution.id,
  323. idProduct: idProduct,
  324. active: activeProduct
  325. }
  326. })
  327. .then(function (response) {
  328. });
  329. for (i = 0; i < this.products.length; i++) {
  330. if (this.products[i].productDistribution && this.products[i].id == idProduct) {
  331. this.products[i].productDistribution[0].active = activeProduct;
  332. }
  333. }
  334. this.initCountActiveProducts();
  335. },
  336. isOneProductMaximumQuantityExceeded: function () {
  337. for (var i = 0; i < this.products.length; i++) {
  338. if (this.isProductMaximumQuantityExceeded(this.products[i])) {
  339. return true;
  340. }
  341. }
  342. return false;
  343. },
  344. isProductMaximumQuantityExceeded: function (product) {
  345. return
  346. this.getProductDistribution(product)
  347. && this.getProductDistribution(product).quantity_max
  348. && product.quantity_ordered
  349. && product.quantity_ordered > this.getProductDistribution(product).quantity_max;
  350. },
  351. pointSaleActiveClick: function (event) {
  352. var idPointSale = event.currentTarget.getAttribute('data-id-point-sale');
  353. var deliveryPointSale = event.currentTarget.getAttribute('data-delivery-point-sale');
  354. axios.get("ajax-process-active-point-sale", {
  355. params: {
  356. idDistribution: this.distribution.id,
  357. idPointSale: idPointSale,
  358. delivery: deliveryPointSale
  359. }
  360. })
  361. .then(function (response) {
  362. });
  363. for (i = 0; i < this.pointsSale.length; i++) {
  364. if (this.pointsSale[i].id == idPointSale) {
  365. this.pointsSale[i].pointSaleDistribution[0].delivery = deliveryPointSale;
  366. }
  367. }
  368. this.initPointsSale();
  369. },
  370. activeDistribution: function (event) {
  371. var app = this;
  372. var active = parseInt(event.currentTarget.getAttribute('data-active'));
  373. axios.get("ajax-process-active-distribution", {
  374. params: {
  375. idDistribution: this.distribution.id,
  376. active: active
  377. }
  378. })
  379. .then(function (response) {
  380. app.init();
  381. app.alertsActiveDistribution(active, 'Distribution');
  382. });
  383. },
  384. activeWeekDistribution: function (event) {
  385. var app = this;
  386. var active = parseInt(event.currentTarget.getAttribute('data-active'));
  387. axios.get("ajax-process-active-week-distribution", {
  388. params: {
  389. date: this.date.getFullYear() + '-'
  390. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  391. + ('0' + this.date.getDate()).slice(-2),
  392. active: active
  393. }
  394. })
  395. .then(function (response) {
  396. app.init();
  397. app.alertsActiveDistribution(active, 'Semaine de distribution');
  398. });
  399. },
  400. alertsActiveDistribution: function (active, label) {
  401. if (!active) {
  402. appAlerts.alert(
  403. 'success',
  404. label + ' désactivée.',
  405. );
  406. appAlerts.alert(
  407. 'info',
  408. 'Pensez à bien rembourser les clients qui auraient passé commande en utilisant leur cagnotte.',
  409. 6000
  410. );
  411. } else {
  412. appAlerts.alert(
  413. 'success',
  414. label + ' activée.',
  415. );
  416. }
  417. },
  418. pointSaleClick: function (event) {
  419. this.setIdActivePointSale(event.currentTarget.getAttribute('data-id-point-sale'));
  420. },
  421. setIdActivePointSale: function (id) {
  422. this.idActivePointSale = id;
  423. for (key in this.pointsSale) {
  424. if (this.pointsSale[key].id == id) {
  425. this.pointSaleActive = this.pointsSale[key];
  426. }
  427. }
  428. if (!id) {
  429. this.orderCreate.id_point_sale = this.idDefaultPointSale;
  430. } else {
  431. this.orderCreate.id_point_sale = id;
  432. }
  433. setTimeout("opendistrib_popover(); opendistrib_dropdown_tooltip();", 500);
  434. },
  435. orderCreatedUpdated: function () {
  436. this.showModalFormOrderCreate = false;
  437. this.showModalFormOrderUpdate = false;
  438. this.init(this.idActivePointSale);
  439. },
  440. deleteOrderClick: function (event) {
  441. var app = this;
  442. var idOrder = event.currentTarget.getAttribute('data-id-order');
  443. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-delete", {
  444. params: {
  445. idOrder: idOrder
  446. }
  447. })
  448. .then(function (response) {
  449. app.init(app.idActivePointSale);
  450. });
  451. },
  452. updateOrderFromUrl: function () {
  453. this.initModalFormOrder();
  454. this.updateProductOrderPrices(false);
  455. },
  456. updateOrderClick: function (event) {
  457. var idOrder = event.currentTarget.getAttribute('data-id-order');
  458. this.idOrderUpdate = idOrder;
  459. this.showModalFormOrderUpdate = true;
  460. this.initModalFormOrder();
  461. this.updateProductOrderPrices(false);
  462. },
  463. openModalFormOrderCreate: function () {
  464. this.showModalFormOrderCreate = true;
  465. this.initModalFormOrder();
  466. this.updateProductOrderPrices(false);
  467. },
  468. initModalFormOrder: function () {
  469. var app = this;
  470. setTimeout(function () {
  471. $('.modal-body').css('height', $(window).height());
  472. $('.modal-body').css('maxHeight', 'unset');
  473. $('.select2-order-form').select2({
  474. width: 'resolve'
  475. });
  476. $('.select2-order-form').on('select2:select', function (e) {
  477. var idUser = e.params.data.id;
  478. if (app.showModalFormOrderCreate) {
  479. Vue.set(app.orderCreate, 'id_user', idUser);
  480. }
  481. if (app.showModalFormOrderUpdate) {
  482. Vue.set(app.ordersUpdate[app.getOrderUpdateKey()], 'id_user', idUser);
  483. }
  484. });
  485. // Passage à la ligne du dessous quand on appuie sur "Entrée"
  486. $('.modal-form-order .input-quantity').keypress(function (e) {
  487. if (e.which == 13) {
  488. $(this).parent().parent().parent()
  489. .next().find('.input-quantity').focus();
  490. }
  491. });
  492. }, 500);
  493. },
  494. getOrderUpdateKey: function () {
  495. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  496. for (keyOrderUpdate in app.ordersUpdate) {
  497. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  498. return keyOrderUpdate;
  499. }
  500. }
  501. }
  502. },
  503. orderPaymentModalClick: function (event) {
  504. var idOrder = event.currentTarget.getAttribute('data-id-order');
  505. this.idOrderPayment = idOrder;
  506. this.showModalPayment = true;
  507. },
  508. getTypePayment: function (order) {
  509. if (order.amount_paid < order.amount) {
  510. return 'payment';
  511. } else {
  512. return 'refund';
  513. }
  514. },
  515. isTypePayment: function (order) {
  516. return this.getTypePayment(order) == 'payment';
  517. },
  518. getLabelPaymentRefund: function (order, labelPay, labelRefund, labelMeanPayment) {
  519. var str = '';
  520. if (this.isTypePayment(order)) {
  521. str += labelPay;
  522. } else {
  523. str += labelRefund;
  524. }
  525. str += ' ' + labelMeanPayment;
  526. return str;
  527. },
  528. orderPaymentClick: function (event) {
  529. var app = this;
  530. var idOrder = event.currentTarget.getAttribute('data-id-order');
  531. if (!idOrder) {
  532. idOrder = this.idOrderPayment;
  533. }
  534. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-payment", {
  535. params: {
  536. idOrder: idOrder,
  537. type: event.currentTarget.getAttribute('data-type'),
  538. meanPayment: event.currentTarget.getAttribute('data-mean-payment')
  539. //amount: event.currentTarget.getAttribute('data-amount')
  540. }
  541. })
  542. .then(function (response) {
  543. app.init(app.idActivePointSale);
  544. });
  545. },
  546. orderViewClick: function (event) {
  547. var currentIdOrderView = event.currentTarget.getAttribute('data-id-order');
  548. if (this.idOrderView == currentIdOrderView) {
  549. this.showViewProduct = !this.showViewProduct;
  550. } else {
  551. this.showViewProduct = true;
  552. this.idOrderView = currentIdOrderView;
  553. }
  554. },
  555. closeModalProducts: function () {
  556. this.showModalProducts = false;
  557. this.init(this.idActivePointSale);
  558. },
  559. closeModalOrderForm: function (create) {
  560. if (create) {
  561. this.showModalFormOrderCreate = false
  562. } else {
  563. this.showModalFormOrderUpdate = false
  564. }
  565. this.init(this.idActivePointSale);
  566. },
  567. cloneOrder: function (order) {
  568. var clone = Object.assign({}, order);
  569. clone.productOrder = {};
  570. for (var key in order.productOrder) {
  571. clone.productOrder[key] = order.productOrder[key];
  572. }
  573. return clone;
  574. },
  575. addSubscriptions: function () {
  576. var app = this;
  577. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-process-add-subscriptions", {
  578. params: {
  579. date: this.getDate()
  580. }
  581. })
  582. .then(function (response) {
  583. app.init(app.idActivePointSale);
  584. appAlerts.alertResponse(response);
  585. });
  586. },
  587. synchroTiller: function () {
  588. var app = this;
  589. this.showLoading = true;
  590. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-process-synchro-tiller", {
  591. params: {
  592. date: this.getDate()
  593. }
  594. })
  595. .then(function (response) {
  596. app.init(app.idActivePointSale);
  597. });
  598. },
  599. authTiller: function () {
  600. },
  601. totalActivePointSale: function () {
  602. var total = 0;
  603. for (var i = 0; i < this.orders.length; i++) {
  604. if (this.orders[i].id_point_sale == this.idActivePointSale) {
  605. total += parseFloat(this.orders[i].amount);
  606. }
  607. }
  608. return total.toFixed(2);
  609. },
  610. weightActivePointSale: function () {
  611. var weight = 0;
  612. for (var i = 0; i < this.orders.length; i++) {
  613. if (this.orders[i].id_point_sale == this.idActivePointSale) {
  614. weight += parseFloat(this.orders[i].weight);
  615. }
  616. }
  617. return weight.toFixed(2);
  618. },
  619. changeSynchroTiller: function (event) {
  620. var app = this;
  621. var idOrder = event.currentTarget.getAttribute('data-id-order');
  622. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-change-synchro-tiller", {
  623. params: {
  624. idOrder: idOrder,
  625. boolSynchroTiller: event.currentTarget.checked ? 1 : 0
  626. }
  627. })
  628. .then(function (response) {
  629. app.init();
  630. });
  631. },
  632. selectAllOrdersEvent: function (event) {
  633. var bool = event.currentTarget.checked;
  634. this.selectAllOrders(bool);
  635. },
  636. selectAllOrders: function (bool) {
  637. for (var key in this.orders) {
  638. if (this.orders[key].id_point_sale == this.idActivePointSale) {
  639. this.orders[key].selected = bool;
  640. }
  641. }
  642. },
  643. oneOrderSelected: function () {
  644. for (var key in this.orders) {
  645. if (this.orders[key].selected == true) {
  646. return true;
  647. }
  648. }
  649. return false;
  650. },
  651. generateDeliveryNotePointSale: function () {
  652. if (!this.oneOrderSelected()) {
  653. this.selectAllOrders(true);
  654. }
  655. if (this.oneOrderSelected()) {
  656. var app = this;
  657. var idOrders = {};
  658. for (var key in this.orders) {
  659. if (this.orders[key].selected == true) {
  660. idOrders[key] = this.orders[key].id;
  661. }
  662. }
  663. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note-point-sale", {
  664. params: {
  665. idOrders: JSON.stringify(idOrders)
  666. }
  667. })
  668. .then(function (response) {
  669. appAlerts.alertResponse(response);
  670. app.init(app.idActivePointSale);
  671. });
  672. } else {
  673. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour générer un bon de livraison');
  674. }
  675. },
  676. generateDeliveryNoteEachUser: function () {
  677. if (!this.oneOrderSelected()) {
  678. this.selectAllOrders(true);
  679. }
  680. if (this.oneOrderSelected()) {
  681. var app = this;
  682. var idOrders = {};
  683. for (var key in this.orders) {
  684. if (this.orders[key].selected == true) {
  685. idOrders[key] = this.orders[key].id;
  686. }
  687. }
  688. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note-each-user", {
  689. params: {
  690. idOrders: JSON.stringify(idOrders)
  691. }
  692. })
  693. .then(function (response) {
  694. appAlerts.alertResponse(response);
  695. app.init(app.idActivePointSale);
  696. });
  697. } else {
  698. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour générer un bon de livraison');
  699. }
  700. },
  701. validateDeliveryNotes: function () {
  702. if (!this.oneOrderSelected()) {
  703. this.selectAllOrders(true);
  704. }
  705. if (this.oneOrderSelected()) {
  706. var app = this;
  707. var idOrders = {};
  708. for (var key in this.orders) {
  709. if (this.orders[key].selected == true) {
  710. idOrders[key] = this.orders[key].id;
  711. }
  712. }
  713. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-validate-delivery-notes", {
  714. params: {
  715. idOrders: JSON.stringify(idOrders)
  716. }
  717. })
  718. .then(function (response) {
  719. appAlerts.alertResponse(response);
  720. app.init(app.idActivePointSale);
  721. });
  722. } else {
  723. appAlerts.alert('danger', 'Veuillez sélectionner au moins une commande pour valider un bon de livraison');
  724. }
  725. },
  726. generateDeliveryNote: function (event) {
  727. var app = this;
  728. var idOrder = event.currentTarget.getAttribute('data-id-order');
  729. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-generate-delivery-note", {
  730. params: {
  731. idOrder: idOrder
  732. }
  733. })
  734. .then(function (response) {
  735. appAlerts.alertResponse(response);
  736. app.init(app.idActivePointSale);
  737. });
  738. },
  739. sendDeliveryNote: function (event) {
  740. var app = this;
  741. var idOrder = event.currentTarget.getAttribute('data-id-order');
  742. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-send-delivery-note", {
  743. params: {
  744. idOrder: idOrder
  745. }
  746. })
  747. .then(function (response) {
  748. appAlerts.alertResponse(response);
  749. app.init(app.idActivePointSale);
  750. });
  751. },
  752. deliveryNoteExist: function (idPointSale) {
  753. return typeof this.deliveryNotes[this.idActivePointSale] != 'undefined';
  754. },
  755. payOrders: function () {
  756. var app = this;
  757. axios.get(UrlManager.getBaseUrlAbsolute() + "cron/pay-orders", {
  758. params: {
  759. date: app.getDate()
  760. }
  761. })
  762. .then(function (response) {
  763. appAlerts.alertResponse(response);
  764. app.init(app.idActivePointSale);
  765. });
  766. },
  767. updateProductOrderPrices: function (updatePricesOnUpdateOrder) {
  768. var app = this;
  769. app.loadingUpdateProductOrder = true;
  770. var order = null;
  771. if (app.showModalFormOrderCreate) {
  772. order = app.orderCreate;
  773. }
  774. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  775. for (keyOrderUpdate in app.ordersUpdate) {
  776. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  777. order = app.ordersUpdate[keyOrderUpdate];
  778. }
  779. }
  780. }
  781. if (order) {
  782. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-update-product-order", {
  783. params: {
  784. idDistribution: app.distribution.id,
  785. idUser: order.id_user,
  786. idPointSale: order.id_point_sale,
  787. idOrder: order.id
  788. }
  789. })
  790. .then(function (response) {
  791. if (response.data) {
  792. for (idProduct in response.data) {
  793. if (app.showModalFormOrderCreate) {
  794. Vue.set(app.orderCreate.productOrder[idProduct], 'prices', response.data[idProduct].prices);
  795. Vue.set(app.orderCreate.productOrder[idProduct], 'active', response.data[idProduct].active);
  796. Vue.set(app.orderCreate.productOrder[idProduct], 'price', app.getBestProductPrice(app.orderCreate, idProduct, app.orderCreate.productOrder[idProduct].quantity, false));
  797. Vue.set(app.orderCreate.productOrder[idProduct], 'price_with_tax', app.getBestProductPrice(app.orderCreate, idProduct, app.orderCreate.productOrder[idProduct].quantity, true));
  798. }
  799. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  800. for (keyOrderUpdate in app.ordersUpdate) {
  801. if (order.id == app.idOrderUpdate) {
  802. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'prices', response.data[idProduct].prices);
  803. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'active', response.data[idProduct].active);
  804. Vue.set(app.ordersUpdate[keyOrderUpdate].productOrder[idProduct], 'invoice_price', response.data[idProduct].invoice_price);
  805. if (updatePricesOnUpdateOrder) {
  806. Vue.set(
  807. app.ordersUpdate[keyOrderUpdate].productOrder[idProduct],
  808. 'price',
  809. app.getBestProductPrice(app.ordersUpdate[keyOrderUpdate], idProduct, app.ordersUpdate[keyOrderUpdate].productOrder[idProduct].quantity, false));
  810. Vue.set(
  811. app.ordersUpdate[keyOrderUpdate].productOrder[idProduct],
  812. 'price_with_tax',
  813. app.getBestProductPrice(app.ordersUpdate[keyOrderUpdate], idProduct, app.ordersUpdate[keyOrderUpdate].productOrder[idProduct].quantity, true));
  814. }
  815. }
  816. }
  817. }
  818. }
  819. if (updatePricesOnUpdateOrder) {
  820. appAlerts.alert('info', 'Prix rechargés');
  821. }
  822. }
  823. app.loadingUpdateProductOrder = false;
  824. });
  825. }
  826. },
  827. updateInvoicePrices: function () {
  828. var order = null;
  829. if (app.showModalFormOrderUpdate && app.idOrderUpdate) {
  830. for (keyOrderUpdate in app.ordersUpdate) {
  831. if (app.ordersUpdate[keyOrderUpdate].id == app.idOrderUpdate) {
  832. order = app.ordersUpdate[keyOrderUpdate];
  833. }
  834. }
  835. }
  836. if (order) {
  837. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-update-invoice-prices", {
  838. params: {
  839. idOrder: order.id
  840. }
  841. })
  842. .then(function (response) {
  843. app.updateProductOrderPrices(false);
  844. appAlerts.alert('info', 'Prix facturés réinitialisés.');
  845. });
  846. }
  847. },
  848. getBestProductPrice: function (order, idProduct, theQuantity, withTax) {
  849. var product = this.getProduct(idProduct);
  850. var thePrice = 9999;
  851. var pricesArray = order.productOrder[idProduct].prices;
  852. var unitCoefficient = this.getUnitCoefficient(product.unit);
  853. if (theQuantity) {
  854. theQuantity = theQuantity / unitCoefficient;
  855. }
  856. if (pricesArray) {
  857. for (var i = 0; i < pricesArray.length; i++) {
  858. var price = pricesArray[i].price;
  859. if (withTax) {
  860. price = pricesArray[i].price_with_tax
  861. }
  862. var fromQuantity = pricesArray[i].from_quantity;
  863. if (price < thePrice && fromQuantity <= theQuantity) {
  864. thePrice = price;
  865. }
  866. }
  867. } else {
  868. if (withTax) {
  869. thePrice = getPriceWithTax(product.price, product.taxRate.value);
  870. } else {
  871. thePrice = product.price;
  872. }
  873. }
  874. if (thePrice == 9999) {
  875. return 0;
  876. } else {
  877. return thePrice;
  878. }
  879. },
  880. getProduct: function (idProduct) {
  881. for (var i = 0; i < this.products.length; i++) {
  882. if (this.products[i].id == idProduct) {
  883. return this.products[i];
  884. }
  885. }
  886. return false;
  887. },
  888. countDocuments: function (order) {
  889. var count = 0;
  890. if (order.id_delivery_note) {
  891. count++;
  892. }
  893. if (order.id_quotation) {
  894. count++;
  895. }
  896. if (order.id_invoice) {
  897. count++;
  898. }
  899. return count;
  900. },
  901. getUnitCoefficient: function (unit) {
  902. return this.units[unit].coefficient;
  903. },
  904. getProductDistribution: function (product) {
  905. if (typeof product.productDistribution !== 'undefined' && product.productDistribution[0]) {
  906. return product.productDistribution[0];
  907. }
  908. return null;
  909. },
  910. copyLinkOrder: function ($event, urlOrder) {
  911. $event.preventDefault();
  912. navigator.clipboard.writeText(urlOrder);
  913. appAlerts.alert('success', 'Lien vers la page de commande de la distribution copié.');
  914. return false;
  915. }
  916. },
  917. });
  918. Vue.component('order-state-payment', {
  919. props: ['order', 'producer'],
  920. template: '#order-state-payment'
  921. });
  922. Vue.component('modal', {
  923. template: '#modal-template'
  924. });
  925. Vue.component('order-form', {
  926. props: ['distribution', 'date', 'dateFormat', 'pointsSale', 'idActivePointSale', 'meansPayment', 'users', 'products', 'order', 'orders', 'producer', 'loadingUpdateProductOrder', 'create', 'units'],
  927. emits: ['updateProductPrice', 'updateInvoicePrices'],
  928. data: function () {
  929. return {
  930. errors: [],
  931. idPointSale: 0,
  932. idUser: 0,
  933. username: '',
  934. comment: '',
  935. baseUrl: $('meta[name=baseurl]').attr('content'),
  936. vatMode: 'all' // 'with_tax'
  937. };
  938. },
  939. template: '#order-form-template',
  940. watch: {
  941. 'order.id_user': function () {
  942. this.userChange();
  943. }
  944. },
  945. methods: {
  946. checkForm: function () {
  947. this.errors = [];
  948. var countProducts = 0;
  949. for (var key in this.order.productOrder) {
  950. if (this.order.productOrder[key].quantity > 0) {
  951. countProducts++;
  952. }
  953. }
  954. if (this.order.id_point_sale
  955. && (this.order.id_user > 0 || (this.order.username && this.order.username.length))
  956. && countProducts > 0) {
  957. return true;
  958. }
  959. if (!this.order.id_point_sale) {
  960. this.errors.push('Veuillez sélectionner un point de vente');
  961. }
  962. if ((!this.order.id_user || this.order.id_user == 0) && !this.order.username.length) {
  963. this.errors.push('Veuillez sélectionner ou saisir un utilisateur');
  964. }
  965. if (!countProducts) {
  966. this.errors.push('Veuillez sélectionner au moins un produit');
  967. }
  968. },
  969. getProductOrderArrayRequest: function () {
  970. var productOrderArrayRequest = {};
  971. for (var key in this.order.productOrder) {
  972. productOrderArrayRequest[key] = {
  973. quantity: this.order.productOrder[key].quantity,
  974. unit: this.order.productOrder[key].unit,
  975. price: this.order.productOrder[key].price,
  976. invoice_price: this.order.productOrder[key].invoice_price
  977. };
  978. }
  979. return JSON.stringify(productOrderArrayRequest);
  980. },
  981. getPointSale: function (idPointSale) {
  982. for (key in this.pointsSale) {
  983. if (this.pointsSale[key].id == idPointSale) {
  984. return this.pointsSale[key];
  985. }
  986. }
  987. return false;
  988. },
  989. isPointSaleCreditFunctioningOptional: function (idPointSale) {
  990. var pointSale = this.getPointSale(idPointSale);
  991. if (pointSale && pointSale.credit_functioning == 'optional') {
  992. return true;
  993. }
  994. return false;
  995. },
  996. submitFormCreate: function (event) {
  997. var app = this;
  998. if (this.checkForm()) {
  999. axios.get(UrlManager.getBaseUrlAbsolute() + "order/ajax-create", {
  1000. params: {
  1001. date: this.date.getFullYear() + '-'
  1002. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  1003. + ('0' + this.date.getDate()).slice(-2),
  1004. idPointSale: this.order.id_point_sale,
  1005. idUser: this.order.id_user,
  1006. username: this.order.username,
  1007. meanPayment: this.order.mean_payment,
  1008. products: app.getProductOrderArrayRequest(),
  1009. comment: this.order.comment,
  1010. debitCredit: this.order.debitCredit
  1011. }
  1012. })
  1013. .then(function (response) {
  1014. app.order.id_point_sale = 0;
  1015. app.order.id_user = 0;
  1016. app.order.username = '';
  1017. app.order.comment = '';
  1018. for (i = 0; i < app.order.productOrder.length; i++) {
  1019. app.order.productOrder[i] = 0;
  1020. }
  1021. app.$emit('ordercreatedupdated');
  1022. });
  1023. }
  1024. },
  1025. submitFormUpdate: function (event) {
  1026. var app = this;
  1027. if (this.checkForm()) {
  1028. var data = new FormData();
  1029. data.append('date', this.date.getFullYear() + '-'
  1030. + ('0' + (this.date.getMonth() + 1)).slice(-2) + '-'
  1031. + ('0' + this.date.getDate()).slice(-2));
  1032. data.append('idOrder', this.order.id);
  1033. data.append('idPointSale', this.order.id_point_sale);
  1034. data.append('meanPayment', this.order.mean_payment);
  1035. data.append('idUser', this.order.id_user);
  1036. data.append('username', '' + this.order.username);
  1037. data.append('products', app.getProductOrderArrayRequest());
  1038. data.append('comment', this.order.comment && this.order.comment.length ? this.order.comment : '');
  1039. data.append('debitCredit', this.order.debitCredit ? this.order.debitCredit : 0);
  1040. axios.post(UrlManager.getBaseUrlAbsolute() + "order/ajax-update", data)
  1041. .then(function (response) {
  1042. app.$emit('ordercreatedupdated');
  1043. });
  1044. }
  1045. },
  1046. productQuantityClick: function (id_product, quantity) {
  1047. if (!this.order.productOrder[id_product].quantity) {
  1048. this.order.productOrder[id_product].quantity = 0;
  1049. }
  1050. if (parseFloat(this.order.productOrder[id_product].quantity) + quantity >= 0) {
  1051. var theQuantity = (parseFloat(this.order.productOrder[id_product].quantity) + parseFloat(quantity)).toFixed(2);
  1052. var theQuantityDecimal = theQuantity % 1;
  1053. if (theQuantityDecimal == 0) {
  1054. theQuantity = parseInt(theQuantity);
  1055. }
  1056. Vue.set(this.order.productOrder[id_product], 'quantity', theQuantity);
  1057. Vue.set(this.order.productOrder[id_product], 'price', app.getBestProductPrice(this.order, id_product, theQuantity, false));
  1058. Vue.set(this.order.productOrder[id_product], 'price_with_tax', app.getBestProductPrice(this.order, id_product, theQuantity, true));
  1059. }
  1060. },
  1061. getProduct: function (idProduct) {
  1062. for (var i = 0; i < this.products.length; i++) {
  1063. if (this.products[i].id == idProduct) {
  1064. return this.products[i];
  1065. }
  1066. }
  1067. return false;
  1068. },
  1069. productPriceChange: function (event) {
  1070. var idProduct = event.currentTarget.getAttribute('data-id-product');
  1071. var product = this.getProduct(idProduct);
  1072. if (product) {
  1073. var taxRateValue = parseFloat(product.taxRate.value);
  1074. var withTax = event.currentTarget.getAttribute('data-with-tax');
  1075. var price = 0;
  1076. var priceWithTax = 0;
  1077. var priceValue = parseFloat(event.currentTarget.value.replace(',', '.'));
  1078. if (withTax) {
  1079. priceWithTax = priceValue.toFixed(2);
  1080. price = getPrice(priceWithTax, taxRateValue);
  1081. } else {
  1082. price = priceValue.toFixed(5);
  1083. priceWithTax = getPriceWithTax(price, taxRateValue);
  1084. }
  1085. if (isNaN(price)) {
  1086. price = 0;
  1087. }
  1088. if (isNaN(priceWithTax)) {
  1089. priceWithTax = 0;
  1090. }
  1091. Vue.set(this.order.productOrder, idProduct, {
  1092. active: this.order.productOrder[idProduct].active,
  1093. quantity: this.order.productOrder[idProduct].quantity,
  1094. unit: this.order.productOrder[idProduct].unit,
  1095. price: price,
  1096. price_with_tax: priceWithTax
  1097. });
  1098. }
  1099. },
  1100. userChange: function (event) {
  1101. var app = this;
  1102. axios.get(UrlManager.getBaseUrlAbsolute() + "distribution/ajax-point-sale-favorite", {
  1103. params: {
  1104. idUser: app.order.id_user,
  1105. idDistribution: app.distribution.id
  1106. }
  1107. })
  1108. .then(function (response) {
  1109. if (app.idActivePointSale == 0) {
  1110. app.order.id_point_sale = response.data.id_favorite_point_sale;
  1111. }
  1112. app.updateProductOrderPrices(true);
  1113. });
  1114. },
  1115. pointSaleChange: function (event) {
  1116. this.updateProductOrderPrices(true);
  1117. },
  1118. updateProductOrderPrices: function (updateProductOrderPrices) {
  1119. this.$emit('updateproductorderprices', updateProductOrderPrices);
  1120. },
  1121. updateInvoicePrices: function () {
  1122. this.$emit('updateinvoiceprices');
  1123. },
  1124. toggleVatMode: function () {
  1125. if (this.vatMode == 'all') {
  1126. this.vatMode = 'with_tax';
  1127. } else {
  1128. this.vatMode = 'all';
  1129. }
  1130. },
  1131. getProductQuantityRemaining: function (product) {
  1132. var quantityRemaining = 0;
  1133. var productQuantityOrder = 0;
  1134. var unit = product.unit;
  1135. for (key in this.orders) {
  1136. productQuantityOrder += this.getProductQuantityProductOrder(this.orders[key], product);
  1137. }
  1138. if (this.create == 1) {
  1139. productQuantityOrder += this.getProductQuantityProductOrder(this.order, product);
  1140. }
  1141. quantityRemaining = this.getProductDistribution(product).quantity_max - productQuantityOrder;
  1142. if (unit != 'piece') {
  1143. quantityRemaining = quantityRemaining.toFixed(2);
  1144. }
  1145. return quantityRemaining;
  1146. },
  1147. getProductQuantityProductOrder: function (order, product) {
  1148. var productOrder = order.productOrder[product.id];
  1149. var unit = productOrder.unit;
  1150. var unitCoefficient = this.getUnitCoefficient(unit);
  1151. return parseFloat(productOrder.quantity / unitCoefficient);
  1152. },
  1153. getUnitCoefficient: function (unit) {
  1154. return this.units[unit].coefficient;
  1155. },
  1156. getProductDistribution: function (product) {
  1157. if (typeof product.productDistribution !== 'undefined' && product.productDistribution[0]) {
  1158. return product.productDistribution[0];
  1159. }
  1160. }
  1161. }
  1162. });
  1163. }