actions.js 12 KB

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