main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. # -*- coding: utf-8 -*-
  2. from openerp import http
  3. from openerp.http import request
  4. from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, float_round
  5. from werkzeug.wrappers import Response
  6. from werkzeug.datastructures import Headers
  7. from datetime import datetime
  8. from dateutil.relativedelta import relativedelta as rd
  9. from dateutil.parser import parse
  10. from pytz import timezone
  11. from gzip import GzipFile
  12. import simplejson as json
  13. import gzip
  14. import logging
  15. try:
  16. from cStringIO import StringIO as IO
  17. except ImportError:
  18. from StringIO import StringIO as IO
  19. LOGGER = logging.getLogger(__name__)
  20. GZIP_COMPRESSION_LEVEL = 9
  21. '''
  22. ___ ___ __ __ __ ___ __ __ ___ __ ___ __ __ __ __ __
  23. |__| | | |__) / ` / \ |\ | | |__) / \ | | |__ |__) |__ / \ |__) |__) / \ /__`
  24. | | | | | \__, \__/ | \| | | \ \__/ |___ |___ |___ | \ | \__/ | \ | \__/ .__/
  25. # Resource paths
  26. - /init: return json response gzip compressed contains values for sale operation
  27. - /create_product: create product on the fly POS and return it
  28. - /create_customer: create customer on the fly and return it
  29. - /process_sale: processing sale and return true if completed
  30. '''
  31. class PosSales(http.Controller):
  32. '''
  33. Make JSON response
  34. '''
  35. def make_json_response(self, data=None, status=200):
  36. return Response(json.dumps(data), status=status, content_type='application/json')
  37. '''
  38. Make GZIP to JSON response
  39. '''
  40. def make_gzip_response(self, data=None, status=200):
  41. gzip_buffer = IO()
  42. with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file:
  43. gzip_file.write(json.dumps(data))
  44. contents = gzip_buffer.getvalue()
  45. gzip_buffer.close()
  46. headers = Headers()
  47. headers.add('Content-Encoding', 'gzip')
  48. headers.add('Vary', 'Accept-Encoding')
  49. headers.add('Content-Length', len(contents))
  50. return Response(contents, status=status, headers=headers, content_type='application/json')
  51. '''
  52. '''
  53. def make_info_log(self, log):
  54. LOGGER.info(log)
  55. '''
  56. Get POS data
  57. '''
  58. def get_pos_data(self):
  59. pos = request.env['eiru.pos'].search([])
  60. return {
  61. 'imageType': pos.image_type,
  62. 'allowCurrencyExchange': pos.allow_currency_exchange,
  63. 'viewCurrencyExchanges': pos.view_currency_exchanges
  64. }
  65. '''
  66. Get timezone
  67. '''
  68. def get_timezone(self):
  69. return timezone(request.context['tz'])
  70. '''
  71. Get server date
  72. '''
  73. def get_server_datetime(self):
  74. return datetime.now(self.get_timezone()).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
  75. '''
  76. Check if module is installed
  77. '''
  78. def is_module_installed(self, module_name):
  79. domain = [('name', '=', module_name), ('state', '=', 'installed')]
  80. module = request.env['ir.module.module'].search(domain)
  81. return len(module) != 0
  82. '''
  83. Get current user information
  84. '''
  85. def get_user(self):
  86. user = request.env.user
  87. return {
  88. 'id': user.id,
  89. 'name': user.display_name,
  90. 'company': {
  91. 'id': user.company_id.id,
  92. 'name': user.company_id.display_name,
  93. 'phone': user.company_id.phone or None,
  94. 'city': user.company_id.city or None
  95. }
  96. }
  97. '''
  98. Get currencies from configured journals
  99. '''
  100. def get_currencies_from_journals(self):
  101. domain = [('type', 'in', ['bank', 'cash']), ('active', '=', True)]
  102. currencies = []
  103. for journal in request.env['account.journal'].search(domain):
  104. currency = journal.currency or journal.company_id.currency_id
  105. currencies.append({
  106. 'id': currency.id,
  107. 'name': currency.display_name,
  108. 'base': currency.base,
  109. 'symbol': currency.symbol,
  110. 'position': currency.position,
  111. 'rateSilent': currency.rate_silent,
  112. 'decimalSeparator': currency.decimal_separator,
  113. 'decimalPlaces': currency.decimal_places,
  114. 'thousandsSeparator': currency.thousands_separator
  115. })
  116. return {c['id']:c for c in currencies}.values()
  117. '''
  118. Get all active journals
  119. '''
  120. def get_journals(self):
  121. domain = [('type', 'in', ['bank', 'cash']), ('active', '=', True)]
  122. has_subtype = self.is_module_installed('eiru_bank_payments_references')
  123. return [{
  124. 'id': journal.id,
  125. 'name': journal.display_name,
  126. 'code': journal.code,
  127. 'type': journal.type,
  128. 'subtype': (has_subtype and journal.subtype) or None,
  129. 'currencyId': journal.currency.id or journal.company_id.currency_id.id
  130. } for journal in request.env['account.journal'].search(domain, order='id')]
  131. '''
  132. Get banks
  133. '''
  134. def get_banks(self):
  135. banks = []
  136. if self.is_module_installed('eiru_bank_payments_references'):
  137. banks = [
  138. {
  139. 'id': bank.id,
  140. 'name': bank.display_name
  141. } for bank in request.env['res.bank'].search([('active', '=', True)])
  142. ]
  143. return banks
  144. '''
  145. Get bank payment types
  146. '''
  147. def get_bank_payment_types(self):
  148. bank_types = []
  149. if self.is_module_installed('eiru_bank_payments_references'):
  150. domain = [('is_receipt', '=', True)]
  151. bank_types = [
  152. {
  153. 'id': type.id,
  154. 'name': type.display_name,
  155. 'isReceipt': type.is_receipt,
  156. 'isPayment': type.is_payment,
  157. 'fieldsAllowed': map(lambda x: x.strip(), (type.fields_allowed or []).split(',')),
  158. 'subtype': type.subtype,
  159. 'defaultState': type.default_state
  160. } for type in request.env['res.bank.payments.type'].search(domain)
  161. ]
  162. return bank_types
  163. '''
  164. Get cheque
  165. '''
  166. def get_cheque_types(self):
  167. cheque_types = []
  168. if self.is_module_installed('eiru_bank_payments_references'):
  169. cheque_types = [
  170. {
  171. 'id': type.id,
  172. 'name': type.display_name,
  173. 'isBank': type.is_bank,
  174. 'isCash': type.is_cash
  175. } for type in request.env['res.bank.check.type'].search([])
  176. ]
  177. return cheque_types
  178. '''
  179. Get all active customers
  180. '''
  181. def get_customers(self, image_type='small'):
  182. domain = [('customer', '=', True), ('active', '=', True)]
  183. return [
  184. {
  185. 'id': customer.id,
  186. 'name': customer.display_name,
  187. 'image': customer.image_small if image_type == 'small' else customer.image_medium,
  188. 'ruc': customer.ruc or None,
  189. 'phone': customer.phone or None,
  190. 'mobile': customer.mobile or None,
  191. 'email': customer.email or None
  192. } for customer in request.env['res.partner'].search(domain)
  193. ]
  194. '''
  195. Get all saleable and active products
  196. '''
  197. def get_products(self, image_type='small'):
  198. domain = [('sale_ok', '=', True), ('list_price', '>', 0), ('active', '=', True)]
  199. return [
  200. {
  201. 'id': product.id,
  202. 'name': product.display_name,
  203. 'ean13': product.ean13,
  204. 'defaultCode': product.default_code,
  205. 'image': product.image_small if image_type == 'small' else product.image_medium,
  206. 'listPrice': product.list_price,
  207. 'variantCount': product.product_variant_count,
  208. 'quantity': 1,
  209. 'price': product.list_price,
  210. 'minimumPrice': product.minimum_price,
  211. 'maximumPrice': product.maximum_price,
  212. 'discount': 0,
  213. 'variants': [{
  214. 'id': variant.id,
  215. 'name': variant.display_name,
  216. 'ean13': variant.ean13,
  217. 'defaultCode': product.default_code,
  218. 'image': variant.image_small if image_type == 'small' else variant.image_medium,
  219. 'listPrice': variant.list_price,
  220. 'quantity': 1,
  221. 'price': variant.list_price,
  222. 'minimumPrice': product.minimum_price,
  223. 'maximumPrice': product.maximum_price,
  224. 'discount': 0,
  225. } for variant in product.product_variant_ids if variant.active]
  226. } for product in request.env['product.template'].search(domain)
  227. ]
  228. '''
  229. Get all active payment terms
  230. '''
  231. def get_payment_terms(self):
  232. domain = [('active', '=', True)]
  233. return [
  234. {
  235. 'id': payment_term.id,
  236. 'name': payment_term.display_name,
  237. 'lines': [{
  238. 'id': line.id,
  239. 'days': line.days,
  240. 'days2': line.days2,
  241. 'value': line.value,
  242. 'valueAmount': line.value_amount
  243. } for line in payment_term.line_ids]
  244. } for payment_term in request.env['account.payment.term'].search(domain)
  245. ]
  246. '''
  247. Get currency from journal
  248. '''
  249. def get_currency(self, journal_id):
  250. journal = request.env['account.journal'].browse(journal_id)
  251. return journal.default_credit_account_id.currency_id.id or journal.default_credit_account_id.company_currency_id.id
  252. '''
  253. Check currency in pricelist and get it
  254. '''
  255. def get_pricelist(self, currency_id):
  256. pricelist = request.env['product.pricelist'].search([('active', '=', True), ('type', '=', 'sale')])
  257. if not True in pricelist.mapped(lambda p: p.currency_id.id == currency_id):
  258. pricelist = pricelist[0].copy()
  259. pricelist.write({
  260. 'currency_id': currency_id
  261. })
  262. else:
  263. pricelist = pricelist.filtered(lambda p: p.currency_id.id == currency_id)
  264. return pricelist
  265. '''
  266. '''
  267. def compute_cart_item_price(self, price, currency_id, partner_id=None):
  268. from_currency = request.env.user.company_id.currency_id
  269. to_currency = request.env['res.currency'].search([('id', '=', currency_id)])
  270. return from_currency.compute(price, to_currency)
  271. '''
  272. '''
  273. def compute_cart_item_discount(self, price, product_id, currency_id):
  274. from_currency = request.env.user.company_id.currency_id
  275. to_currency = request.env['res.currency'].search([('id', '=', currency_id)])
  276. product = request.env['product.product'].search([('id', '=', product_id)])
  277. computed_price = from_currency.compute(price, to_currency)
  278. return 1.0 - (price / product.list_price)
  279. '''
  280. Create sale order from cart items values
  281. '''
  282. def create_sale_from_cart(self, partner_id, cart_items, date_confirm, currency_id, pricelist_id, payment_term_id=None):
  283. values = {
  284. 'partner_id': partner_id,
  285. 'order_line': [[0, False, {
  286. 'product_id': int(line.get('id')),
  287. 'product_uom_qty': float(line.get('quantity')),
  288. 'price_unit': self.compute_cart_item_price(float(line.get('price')), currency_id),
  289. 'discount': self.compute_cart_item_discount(float(line.get('price')), float(line.get('id')), currency_id)
  290. }] for line in cart_items],
  291. 'picking_policy': 'direct',
  292. 'date_confirm': date_confirm,
  293. 'currency_id': currency_id,
  294. 'pricelist_id': pricelist_id,
  295. 'payment_term': payment_term_id,
  296. 'state': 'draft',
  297. }
  298. # import web_pdb; web_pdb.set_trace()
  299. return request.env['sale.order'].create(values)
  300. '''
  301. Confirm sale order
  302. '''
  303. def confirm_sale_order(self, sale_order_id):
  304. sale_order = request.env['sale.order'].browse(sale_order_id)
  305. sale_order.write({
  306. 'state': 'manual'
  307. })
  308. return sale_order.action_button_confirm()
  309. '''
  310. Create invoice from sale order
  311. '''
  312. def create_invoice(self, sale_order_id, currency_id, date_today):
  313. sale_order = request.env['sale.order'].browse(sale_order_id)
  314. invoice_id = sale_order.action_invoice_create()
  315. invoice = request.env['account.invoice'].browse(invoice_id)
  316. for picking in sale_order.picking_ids:
  317. picking.force_assign()
  318. picking.action_done()
  319. date_due = parse(date_today) + rd(days=max(invoice.payment_term.line_ids.mapped(lambda x: x.days + x.days2)))
  320. invoice.write({
  321. 'currency_id': currency_id,
  322. 'date_invoice': date_today,
  323. 'date_due': date_due.strftime(DEFAULT_SERVER_DATE_FORMAT),
  324. 'state': 'open'
  325. })
  326. return invoice
  327. '''
  328. Create move lines
  329. '''
  330. def create_invoice_move_lines(self, invoice_id, paid_amount, date_today):
  331. invoice = request.env['account.invoice'].browse(invoice_id)
  332. context = dict(request.context, lang=invoice.partner_id.lang)
  333. invoice_move_lines = invoice._get_analytic_lines()
  334. decimal_precision = request.env['decimal.precision'].precision_get('Account')
  335. compute_taxes = request.env['account.invoice.tax'].compute(invoice.with_context(context))
  336. invoice.check_tax_lines(compute_taxes)
  337. invoice._recompute_tax_amount()
  338. # import web_pdb; web_pdb.set_trace()
  339. invoice_move_lines += request.env['account.invoice.tax'].move_line_get(invoice.id)
  340. total, total_currency, invoice_move_lines = invoice.with_context(context).compute_invoice_totals(invoice.company_id.currency_id, invoice.reference, invoice_move_lines)
  341. paid_amount = float_round(paid_amount, precision_digits=decimal_precision)
  342. paid_percentage = paid_amount / float_round(total_currency, precision_digits=decimal_precision)
  343. distributed_percentage = -(paid_percentage / len(invoice.payment_term.line_ids))
  344. diff_currency = invoice.currency_id != invoice.company_id.currency_id
  345. if diff_currency:
  346. paid_amount = invoice.currency_id.compute(paid_amount, invoice.company_id.currency_id)
  347. payment_lines = []
  348. for line in invoice.payment_term.line_ids:
  349. date_due = (parse(date_today) + rd(days=line.days + line.days2)).strftime(DEFAULT_SERVER_DATE_FORMAT)
  350. if paid_percentage and paid_percentage < 1.0:
  351. payment_lines.append([date_today, paid_percentage])
  352. paid_percentage = paid_amount = 0
  353. if date_due == date_today and line.value_amount:
  354. distributed_percentage = -((payment_lines[0][1] - line.value_amount) / (len(invoice.payment_term.line_ids) - 1))
  355. continue
  356. if line.value != 'balance':
  357. payment_lines.append([date_due, line.value_amount + distributed_percentage])
  358. continue
  359. payment_lines.append([date_due, line.value_amount])
  360. for payment_line in payment_lines:
  361. current_price = float_round(total * payment_line[1], precision_digits=decimal_precision)
  362. if current_price < 0.0:
  363. continue
  364. paid_amount += current_price
  365. # Compute move line price
  366. if payment_line[1]:
  367. price = current_price
  368. else:
  369. price = float_round(total - paid_amount, precision_digits=decimal_precision) or total
  370. # Compute move line amount in currency
  371. if diff_currency:
  372. amount_currency = invoice.company_id.currency_id.with_context(context).compute(price, invoice.currency_id)
  373. else:
  374. amount_currency = False
  375. # Create invoice move live value
  376. invoice_move_lines.append({
  377. 'type': 'dest',
  378. 'name': '/',
  379. 'price': price,
  380. 'account_id': invoice.account_id.id,
  381. 'date_maturity': payment_line[0],
  382. 'amount_currency': amount_currency,
  383. 'currency_id': diff_currency and invoice.currency_id.id,
  384. 'ref': invoice.reference
  385. })
  386. payment_lines = []
  387. return invoice_move_lines
  388. '''
  389. Create account move
  390. '''
  391. def create_account_move(self, invoice_id, invoice_move_lines):
  392. invoice = request.env['account.invoice'].browse(invoice_id)
  393. accounting_partner = request.env['res.partner']._find_accounting_partner(invoice.partner_id)
  394. move_line_values = [(0, 0, invoice.line_get_convert(line, accounting_partner.id, invoice.date_invoice)) for line in invoice_move_lines]
  395. move_line_values = invoice.group_lines(invoice_move_lines, move_line_values)
  396. move_line_values = invoice.finalize_invoice_move_lines(move_line_values)
  397. ctx = dict(request.context, lang=invoice.partner_id.lang, company_id=invoice.company_id.id)
  398. period = invoice.period_id
  399. if not period:
  400. period = period.with_context(ctx).find(invoice.date_invoice)[:1]
  401. if period:
  402. for line in move_line_values:
  403. line[2]['period_id'] = period.id
  404. ctx['invoice'] = invoice
  405. ctx_nolang = ctx.copy()
  406. ctx_nolang.pop('lang', None)
  407. account_move = request.env['account.move'].with_context(ctx_nolang).create({
  408. 'ref': invoice.reference or invoice.name,
  409. 'line_id': move_line_values,
  410. 'journal_id': invoice.journal_id.id,
  411. 'date': invoice.date_invoice,
  412. 'narration': invoice.comment,
  413. 'company_id': invoice.company_id.id,
  414. 'period_id': period.id
  415. })
  416. invoice.with_context(ctx).write({
  417. 'move_id': account_move.id,
  418. 'period_id': account_move.period_id.id,
  419. 'move_name': account_move.name,
  420. })
  421. account_move.post()
  422. return account_move
  423. '''
  424. Number to invoice
  425. '''
  426. def number_invoice(self, invoice_id):
  427. request.env['account.invoice'].browse(invoice_id).action_number()
  428. '''
  429. Create voucher
  430. '''
  431. def create_account_voucher(self, account_move_id, journal_id, currency_id, paid_amount):
  432. account_move = request.env['account.move'].browse(account_move_id)
  433. account_journal = request.env['account.journal'].browse(journal_id)
  434. account_voucher = request.env['account.voucher'].create({
  435. 'reference': account_move.name,
  436. 'type': 'receipt',
  437. 'journal_id': account_journal.id,
  438. 'company_id': account_move.company_id.id,
  439. 'pre_line': True,
  440. 'amount': paid_amount,
  441. 'period_id': account_move.period_id.id,
  442. 'date': account_move.date,
  443. 'partner_id': account_move.partner_id.id,
  444. 'account_id': account_journal.default_credit_account_id.id,
  445. 'currency_id': currency_id,
  446. 'line_cr_ids': [[0, False, {
  447. 'date_due': l.date_maturity,
  448. 'account_id': l.account_id.id,
  449. 'date_original': l.invoice.date_invoice,
  450. 'move_line_id': l.id,
  451. 'amount_original': abs(l.credit or l.debit or 0.0),
  452. 'amount_unreconciled': abs(l.amount_residual),
  453. 'amount': abs(l.debit) if account_move.date == l.date_maturity else 0.0,
  454. 'reconcile': account_move.date == l.date_maturity,
  455. 'currency_id': currency_id
  456. }] for l in account_move.line_id]
  457. })
  458. account_voucher.action_move_line_create()
  459. return account_voucher
  460. '''
  461. Close a invoice
  462. '''
  463. def close_invoice(self, invoice_id):
  464. invoice = request.env['account.invoice'].browse(invoice_id)
  465. if invoice.residual == 0:
  466. invoice.write({
  467. 'state': 'paid'
  468. })
  469. '''
  470. Create account bank statement lines
  471. '''
  472. def create_bank_statement_lines(self, account_voucher_id, reference=None):
  473. account_voucher = request.env['account.voucher'].browse(account_voucher_id)
  474. return [[0, False, {
  475. 'name': account_voucher.reference,
  476. 'amount': account_voucher.amount,
  477. 'partner_id': account_voucher.partner_id.id,
  478. 'voucher_id': account_voucher.id,
  479. 'journal_id': account_voucher.journal_id.id,
  480. 'account_id': account_voucher.account_id.id,
  481. 'journal_entry_id': account_voucher.move_id.id,
  482. 'currency_id': account_voucher.currency_id.id,
  483. 'ref': 'POS/' + (reference or '')
  484. }]]
  485. '''
  486. Create account bank statement
  487. '''
  488. def create_bank_statement(self, account_voucher_id, account_bank_statement_lines, date_today):
  489. account_voucher = request.env['account.voucher'].browse(account_voucher_id)
  490. account_bank_statement = request.env['account.bank.statement'].search([('journal_id', '=', account_voucher.journal_id.id), ('date', '=', date_today)])
  491. account_bank_statement_values = {
  492. 'date': date_today,
  493. 'user_id': request.env.user.id,
  494. 'journal_id': account_voucher.journal_id.id,
  495. 'period_id': account_voucher.period_id.id,
  496. 'line_ids': account_bank_statement_lines,
  497. 'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft'
  498. }
  499. if account_bank_statement:
  500. size = len(account_bank_statement)
  501. if size == 1:
  502. account_bank_statement.write(account_bank_statement_values)
  503. else:
  504. account_bank_statement[size - 1].write(account_bank_statement_values)
  505. else:
  506. account_bank_statement.create(account_bank_statement_values)
  507. return account_bank_statement
  508. '''
  509. New purchase resource route
  510. '''
  511. @http.route('/eiru_sales/init', auth='user', methods=['GET'], cors='*')
  512. def init_sale(self, **kw):
  513. self.make_info_log('Sending JSON response')
  514. pos_data = self.get_pos_data()
  515. return self.make_gzip_response(
  516. {
  517. 'pos': pos_data,
  518. 'date': self.get_server_datetime(),
  519. 'user': self.get_user(),
  520. 'currencies': self.get_currencies_from_journals(),
  521. 'journals': self.get_journals(),
  522. 'customers': self.get_customers(image_type=pos_data['imageType']),
  523. 'products': self.get_products(image_type=pos_data['imageType']),
  524. 'paymentTerms': self.get_payment_terms(),
  525. 'banks': self.get_banks(),
  526. 'bankPaymentTypes': self.get_bank_payment_types(),
  527. 'chequeTypes': self.get_cheque_types()
  528. }
  529. )
  530. '''
  531. Get products data only
  532. '''
  533. @http.route('/eiru_sales/get_images', auth='user', methods=['GET'], cors='*')
  534. def get_images_only(self, **kw):
  535. pos_data = self.get_pos_data()
  536. image_type = str(pos_data['imageType'])
  537. return self.make_gzip_response(
  538. {
  539. 'customers': self.get_customers(image_type=image_type),
  540. 'products': self.get_products(image_type=image_type)
  541. }
  542. )
  543. '''
  544. Create customer and return data
  545. '''
  546. @http.route('/eiru_sales/create_customer', type='json', auth='user', methods=['POST'], cors='*')
  547. def create_customer(self, **kw):
  548. self.make_info_log('Creating customer')
  549. customer = request.env['res.partner'].create({
  550. 'name': kw.get('name'),
  551. 'ruc': kw.get('ruc'),
  552. 'mobile': kw.get('mobile'),
  553. 'customer': True
  554. })
  555. return {
  556. 'id': customer.id,
  557. 'name': customer.display_name,
  558. 'image': customer.image_small,
  559. 'ruc': customer.ruc or None,
  560. 'phone': customer.phone or None,
  561. 'mobile': customer.mobile or None,
  562. 'email': customer.email or None
  563. }
  564. '''
  565. Save settings
  566. '''
  567. @http.route('/eiru_sales/save_settings', type='json', auth='user', methods=['POST'], cors='*')
  568. def save_settings(self, **kw):
  569. self.make_info_log('save settings')
  570. values = {}
  571. if kw.get('setting') == 'imageType':
  572. values['image_type'] = ('big', 'small')[kw.get('value', False)]
  573. if kw.get('setting') == 'allowCurrencyExchange':
  574. values['allow_currency_exchange'] = kw.get('value', False)
  575. if kw.get('setting') == 'viewCurrencyExchanges':
  576. values['view_currency_exchanges'] = kw.get('value', False)
  577. pos = request.env['eiru.pos'].search([])
  578. pos.write(values)
  579. return self.get_pos_data()
  580. '''
  581. Create product and return data
  582. '''
  583. @http.route('/eiru_sales/create_product', type='json', auth='user', methods=['POST'], cors='*')
  584. def create_product(self, **kw):
  585. self.make_info_log('Creating customer')
  586. product = request.env['product.template'].create({
  587. 'name': kw.get('name'),
  588. 'listPrice': float(kw.get('price')),
  589. 'ean13': kw.get('ean13')
  590. })
  591. return {
  592. 'id': product.id,
  593. 'name': product.display_name,
  594. 'ean13': product.ean13,
  595. 'image': product.image_small,
  596. 'listPrice': product.list_price,
  597. 'variantCount': product.product_variant_count,
  598. 'quantity': 1,
  599. 'price': product.list_price,
  600. 'discount': 0,
  601. 'variants': [{
  602. 'id': variant.id,
  603. 'name': variant.display_name,
  604. 'ean13': variant.ean13,
  605. 'image': variant.image_small,
  606. 'listPrice': variant.list_price,
  607. 'quantity': 1,
  608. 'price': variant.list_price,
  609. 'discount': 0,
  610. } for variant in product.product_variant_ids if variant.active]
  611. }
  612. '''
  613. Process sale
  614. '''
  615. @http.route('/eiru_sales/process_sale', type='json', auth='user', methods=['POST'], cors='*')
  616. def process_sale(self, **kw):
  617. self.make_info_log('Processing sale...')
  618. # Get date
  619. date_now = datetime.now(self.get_timezone()).strftime(DEFAULT_SERVER_DATE_FORMAT)
  620. self.make_info_log('[OK] Getting date')
  621. # Get currency
  622. currency_id = self.get_currency(kw.get('journalId'))
  623. self.make_info_log('[OK] Getting journal')
  624. # Get Pricelist
  625. pricelist = self.get_pricelist(currency_id)
  626. self.make_info_log('[OK] Getting product pricelist')
  627. # Create sale order
  628. sale_order = self.create_sale_from_cart(kw.get('customerId'), kw.get('items'), date_now, currency_id, pricelist.id, kw.get('paymentTermId'))
  629. self.make_info_log('[OK] Creating sale order')
  630. # Check if budget
  631. if kw.get('mode', 'sale') != 'sale':
  632. return {
  633. 'process': True
  634. }
  635. # Confirm sale
  636. self.confirm_sale_order(sale_order.id)
  637. self.make_info_log('[OK] Confirm sale order')
  638. # Create invoice
  639. invoice = self.create_invoice(sale_order.id, currency_id, date_now)
  640. self.make_info_log('[OK] Creating invoice')
  641. # Create invoice move lines
  642. invoice_move_lines = self.create_invoice_move_lines(invoice.id, float(kw.get('payment')), date_now)
  643. self.make_info_log('[OK] Creating invoice move lines')
  644. # Create account move
  645. account_move = self.create_account_move(invoice.id, invoice_move_lines)
  646. self.make_info_log('[OK] Creating account move')
  647. # Number invoice
  648. self.number_invoice(invoice.id)
  649. self.make_info_log('[OK] Number invoice')
  650. # Create account voucher
  651. account_voucher = self.create_account_voucher(account_move.id, kw.get('journalId'), currency_id, float(kw.get('payment')))
  652. self.make_info_log('[OK] Creating account voucher')
  653. # Close invoice
  654. self.close_invoice(invoice.id)
  655. self.make_info_log('[OK] Closing invoice')
  656. # Create account bank statement lines
  657. account_bank_statement_lines = self.create_bank_statement_lines(account_voucher.id)
  658. self.make_info_log('[OK] Creating account bank statement lines')
  659. # Create bank statement
  660. self.create_bank_statement(account_voucher.id, account_bank_statement_lines, date_now)
  661. self.make_info_log('[OK] Creating account bank statement')
  662. return {
  663. 'process': True,
  664. 'name': sale_order.display_name,
  665. 'date': self.get_server_datetime()
  666. }