actions.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import axios from 'axios'
  2. const actions = {
  3. notify(_, message) {
  4. openerp.web.notification.do_warn('Atención', message)
  5. return false
  6. },
  7. initProcess({ getters, commit, dispatch }, mode) {
  8. commit('setMode', mode || getters.mode)
  9. commit('setResult', '')
  10. commit('setLoading', true)
  11. commit('setCompleted', false)
  12. if (!getters.isWired) {
  13. commit('setLoading', false)
  14. return
  15. }
  16. return axios.get('/eiru_sales/init', {
  17. params: {
  18. mode: getters.mode
  19. }
  20. }).then(({ data }) => {
  21. commit('setLoading', false)
  22. commit('toggleFooterButtonsVisibility')
  23. dispatch('explodeData', data)
  24. }).catch(error => {
  25. console.error(error)
  26. })
  27. },
  28. explodeData({ dispatch, commit }, data) {
  29. for (let value in data) {
  30. if (value === 'settings') {
  31. commit('updateSettings', data[value])
  32. continue
  33. }
  34. dispatch(`init${value[0].toUpperCase()}${value.slice(1)}`, data[value])
  35. }
  36. },
  37. createProduct({ dispatch }, payload) {
  38. return axios.post('createProductUrl', {
  39. jsonrpc: '2.0',
  40. method: 'call',
  41. params: {
  42. ...payload
  43. }
  44. }).then(({data}) => {
  45. dispatch('receiveProduct', data.result)
  46. }).catch(error => {
  47. console.error(error)
  48. })
  49. },
  50. createCustomer({ dispatch }, payload) {
  51. return axios.post('/eiru_sales/create_customer', {
  52. jsonrpc: '2.0',
  53. method: 'call',
  54. params: {
  55. ...payload
  56. }
  57. }).then(({ data }) => {
  58. dispatch('receiveCustomer', data.result)
  59. }).catch(error => {
  60. console.error(error)
  61. })
  62. },
  63. checkCart({ getters, dispatch }) {
  64. return !!getters.cartItems.length || dispatch('notify', 'Necesitas agregar productos al carrito para continuar')
  65. },
  66. checkCustomer({ getters, dispatch }) {
  67. if (getters.processing) {
  68. return dispatch('notify', 'Espere mientras se está procesando')
  69. }
  70. return !!getters.selectedCustomer || dispatch('notify', 'Necesitas seleccionar un cliente para continuar')
  71. },
  72. checkSaleOrder({ getters, dispatch }) {
  73. return !!getters.selectedSaleOrder || dispatch('notify', 'Necesitas seleccionar un presupuesto para continuar')
  74. },
  75. checkStockPicking({ getters, dispatch }) {
  76. return !!getters.selectedStockPicking || dispatch('notify', 'Necesitas seleccionar una entrega para confirmar')
  77. },
  78. checkPaymentMethod({ getters }) {
  79. if (getters.processing) {
  80. return dispatch('notify', 'Espere mientras se está procesando')
  81. }
  82. return true
  83. },
  84. checkAmountReceived({ getters, dispatch }) {
  85. if (getters.paymentType === 'cash') {
  86. return getters.initialPayment >= getters.amountToPay || dispatch('notify', 'El monto recibido no puede ser menor al monto a pagar')
  87. } else {
  88. return getters.initialPayment < getters.amountToPay || dispatch('notify', 'El monto recibido no puede ser igual o mayor al monto a pagar')
  89. }
  90. },
  91. toggleSettingsVisibility({ commit }) {
  92. commit('setSettingsVisibility')
  93. },
  94. changeSetting({ dispatch, commit }, setting) {
  95. commit('setLoading', true)
  96. return axios.post('/eiru_sales/save_settings', {
  97. jsonrpc: '2.0',
  98. method: 'call',
  99. params: {
  100. ...setting
  101. }
  102. }).then(({ data }) => {
  103. dispatch('updateImages', data.result)
  104. commit('updateSettings', data.result)
  105. commit('setLoading', false)
  106. }).catch(error => {
  107. console.log(error)
  108. })
  109. },
  110. updateImages({ commit, getters }, data) {
  111. const imageType = getters.settings.imageType ? 'small' : 'big'
  112. if (imageType === data.imageType) {
  113. return
  114. }
  115. return axios.get('/eiru_sales/get_images').then(({ data }) => {
  116. commit('setProducts', data.products)
  117. commit('setCustomers', data.customers)
  118. }).catch(error => {
  119. console.error(error)
  120. })
  121. },
  122. endProcess({ getters, commit, dispatch }) {
  123. const mode = getters.mode
  124. if (mode == 'sale') {
  125. if (getters.paymentType === 'cash' && getters.initialPayment < getters.amountToPay) {
  126. return dispatch('notify', 'El monto recibido no puede ser menor al monto a pagar')
  127. }
  128. if (getters.paymentType !== 'cash' && getters.initialPayment >= getters.amountToPay) {
  129. return dispatch('notify', 'El monto recibido no puede ser igual o mayor al monto a pagar')
  130. }
  131. }
  132. commit('setLoading', true)
  133. let data = {
  134. mode
  135. }
  136. if (['sale', 'budget', 'product_picking'].includes(mode)) {
  137. data = {
  138. ...data,
  139. items: getters.cartItems.map(item => {
  140. return {
  141. id: item.id,
  142. quantity: item.quantity,
  143. price: item.price
  144. }
  145. }),
  146. customerId: getters.selectedCustomer.id,
  147. currencyId: getters.selectedCurrency.id,
  148. warehouseId: getters.selectedWarehouse.id
  149. }
  150. }
  151. if (['sale', 'budget', 'payment'].includes(mode)) {
  152. data = {
  153. ...data,
  154. total: getters.cartTotal,
  155. saleOrderId: (getters.selectedSaleOrder && getters.selectedSaleOrder.id) || null,
  156. paymentTermId: getters.paymentTerm.id,
  157. journalId: getters.selectedJournal.id,
  158. payment: getters.initialPayment > getters.amountToPay ? getters.amountToPay : getters.initialPayment,
  159. paymentMethod: getters.paymentMethod,
  160. customerId: getters.selectedCustomer.id,
  161. currencyId: getters.selectedCurrency.id,
  162. warehouseId: getters.selectedWarehouse.id,
  163. bankPaymentData: {
  164. ...getters.bankPaymentData
  165. }
  166. }
  167. }
  168. if (mode === 'product_delivery') {
  169. data = {
  170. ...data,
  171. stockPickingId: getters.selectedStockPicking.id
  172. }
  173. }
  174. if (['sale', 'budget'].includes(mode)) {
  175. dispatch('storeDataAsync', data)
  176. dispatch('printDocument').then(() => {
  177. commit('setLoading', false)
  178. commit('setCompleted', true)
  179. })
  180. return
  181. }
  182. dispatch('storeDataSync', data)
  183. },
  184. storeDataSync({ dispatch, commit }, data) {
  185. commit('storeData', data)
  186. dispatch('syncData').then(() => {
  187. commit('resetData')
  188. commit('setLoading', false)
  189. commit('setCompleted', true)
  190. })
  191. },
  192. storeDataAsync({ getters, dispatch, commit }, data) {
  193. commit('storeData', data)
  194. if (getters.isWired) {
  195. dispatch('syncData')
  196. commit('resetData')
  197. }
  198. },
  199. syncData({ getters, dispatch }) {
  200. if (getters.data.length == 0) {
  201. return
  202. }
  203. if (getters.isSynchronizable) {
  204. dispatch('notify', 'Estás conectado nuevamente. Sincronizaremos sus datos en segundo plano')
  205. }
  206. return axios.post('/eiru_sales/finish', {
  207. jsonrpc: '2.0',
  208. method: 'call',
  209. params: {
  210. data: getters.data
  211. }
  212. }).then(() => {
  213. if (getters.isSynchronizable) {
  214. dispatch('notify', 'Los datos fueron sincronizados con éxito')
  215. }
  216. }).catch(() => {
  217. if (getters.isSynchronizable) {
  218. dispatch('notify', 'Los datos no fueron sincronizados correctamente')
  219. }
  220. })
  221. },
  222. printDocument({ getters, dispatch }) {
  223. if (getters.mode === 'sale') {
  224. return dispatch('printTicket')
  225. }
  226. },
  227. printTicket({ getters, dispatch }) {
  228. if (!openerp.printer_bridge) {
  229. dispatch('notify', 'Impresión no disponible')
  230. return
  231. }
  232. const data = {
  233. company: getters.companyName,
  234. street: getters.user.company.street,
  235. city: getters.user.company.city,
  236. country: getters.user.company.country,
  237. customer: getters.selectedCustomerName,
  238. date: openerp.web.date_to_str(new Date()),
  239. user: getters.user.name,
  240. items: getters.cartItems.map(item => {
  241. return {
  242. name: item.name.toUpperCase(),
  243. quantity: item.quantity,
  244. price: item.price,
  245. subtotal: item.quantity * item.price
  246. }
  247. }),
  248. paymentMethod: getters.paymentMethod,
  249. total: getters.amountToPay,
  250. received: getters.amountResidual + getters.amountToPay,
  251. residual: getters.amountResidual,
  252. currencyPosition: getters.selectedCurrency.position,
  253. currencyDecimalPlaces: getters.selectedCurrency.decimalPlaces,
  254. currencyDecimalSeparator: getters.selectedCurrency.decimalSeparator,
  255. currencySymbol: getters.currencySymbol
  256. }
  257. const wrapper = document.createElement('div')
  258. wrapper.innerHTML = openerp.web.qweb.render('EiruPosTicket', {...data})
  259. wrapper.setAttribute('id', 'ticket_wrapper')
  260. var childElement = document.body.appendChild(wrapper)
  261. const ticket_el = document.querySelector('.eiru_pos_ticket')
  262. const ticket_width = 70
  263. const measure_factor = 3.7793
  264. const dpi_factor = 3.125
  265. return new Promise(resolve => {
  266. openerp.html2canvas(ticket_el, {
  267. logging: false,
  268. width: ticket_width * measure_factor,
  269. scale: dpi_factor
  270. }).then(function (canvas) {
  271. childElement.remove()
  272. const dataURL = canvas.toDataURL('image/png')
  273. const width = (canvas.width / measure_factor) / dpi_factor
  274. const height = (canvas.height / measure_factor) / dpi_factor
  275. const doc = new jsPDF({
  276. unit: 'mm',
  277. format: [height, ticket_width]
  278. })
  279. doc.addImage(dataURL, 'PNG', 0, 0, width, height)
  280. const data = doc.output('datauristring')
  281. openerp.printer_bridge.print(data)
  282. resolve();
  283. });
  284. })
  285. },
  286. resetSettings() {
  287. // Ignore this
  288. },
  289. resetProcess({ rootState, dispatch }) {
  290. for (let key in rootState) {
  291. if (!(rootState[key] instanceof Object)) {
  292. continue
  293. }
  294. key = key.replace('Module', '')
  295. if (key === 'data') {
  296. continue
  297. }
  298. dispatch(`reset${key[0].toUpperCase()}${key.slice(1)}`)
  299. }
  300. dispatch('initProcess')
  301. },
  302. changeNetStatus({ commit, dispatch }, isWired) {
  303. dispatch('hideTopbar', isWired)
  304. commit('setNetStatus', isWired)
  305. if (isWired) {
  306. dispatch('syncData')
  307. return
  308. }
  309. dispatch('notify', 'Estás sin conexión. Ocultaremos el menú superior mientras sigas trabajando')
  310. },
  311. hideTopbar(_, isWired) {
  312. if (!openerp.eiru_topbar_toggler) {
  313. return
  314. }
  315. setTimeout(() => {
  316. if (isWired) {
  317. openerp.eiru_topbar_toggler.show()
  318. } else {
  319. openerp.eiru_topbar_toggler.hide()
  320. }
  321. }, 3000)
  322. }
  323. }
  324. export default actions