Browse Source

[FIX] currency in sale order

Gogs 7 years ago
parent
commit
7eb95c55b2

+ 40 - 19
models/account_voucher.py

@@ -16,8 +16,21 @@ class AccountVoucher(models.Model):
 
         # Step 1: Select currency based on selected journal
         journal = self.env['account.journal'].browse(int(values['journal_id']))
+        currency_id = journal.default_credit_account_id.currency_id.id or journal.default_credit_account_id.company_currency_id.id
 
-        # Step 2: Create sale order and confirm
+        # Step 2: Check product pricelist
+        pricelist_model = self.env['product.pricelist']
+        pricelist = pricelist_model.search([('active', '=', True), ('type', '=', 'sale')])
+
+        if not len([p.id for p in pricelist if p.currency_id.id == currency_id]):
+            pricelist = pricelist[0].copy()
+            pricelist.write({
+                'currency_id': currency_id
+            })
+        else:
+            pricelist = pricelist[0]
+
+        # Step 3: Create sale order and confirm
         sale_order = self.env['sale.order'].create({
             'partner_id': int(values['customer_id']),
             'order_line': [[0, False, { 
@@ -29,33 +42,37 @@ class AccountVoucher(models.Model):
             'picking_policy': 'direct',
             'state': 'manual',
             'date_confirm': date_now,
+            'currency_id': currency_id,
+            'pricelist_id': pricelist.id,
             'payment_term': int(values['payment_term_id'])
         })
 
-        # Step 3: Create invoice and calculate due date
+        # Step 4: Create invoice and calculate due date
         invoice = self.env['account.invoice'].browse(sale_order.action_invoice_create())
 
         due_date = parse(date_now) + rd(days=max(invoice.payment_term.line_ids.mapped(lambda x: x.days + x.days2)))
 
         invoice.write({
-            'currency_id': journal.default_credit_account_id.currency_id.id or journal.default_credit_account_id.company_currency_id.id,
+            'currency_id': currency_id,
             'date_invoice': date_now,
             'date_due': due_date.strftime(date_format)
         })
 
-        # Step 4: Create invoice move lines
+        # Step 5: Create invoice move lines
         amount_paid = float(values['amount_paid'])
         decimal_precision = self.env['decimal.precision'].precision_get('Account')
 
-        invoice_move_lines = invoice._get_analytic_lines() + self.env['account.invoice.tax'].move_line_get(invoice.id)
+        invoice_move_lines = invoice._get_analytic_lines()
 
         compute_taxes = self.env['account.invoice.tax'].compute(invoice)
         invoice.check_tax_lines(compute_taxes)
+        invoice._recompute_tax_amount()
+
+        invoice_move_lines += self.env['account.invoice.tax'].move_line_get(invoice.id)
 
-        total, total_currency, invoice_move_lines = invoice.compute_invoice_totals(invoice.company_id.currency_id,\
-        invoice.reference, invoice_move_lines)
+        total, total_currency, invoice_move_lines = invoice.compute_invoice_totals(invoice.company_id.currency_id, invoice.reference, invoice_move_lines)
 
-        percent_paid = amount_paid / total
+        percent_paid = amount_paid / round(total, decimal_precision)
         distribute_percent = -(percent_paid / len(invoice.payment_term.line_ids))
 
         total_lines = []
@@ -63,7 +80,7 @@ class AccountVoucher(models.Model):
         for line in invoice.payment_term.line_ids:
             due_date = (parse(date_now) + rd(days=line.days + line.days2)).strftime(date_format)
 
-            if percent_paid:
+            if percent_paid and percent_paid < 1:
                 total_lines.append([date_now, percent_paid])
                 percent_paid = amount_paid = 0
 
@@ -78,27 +95,29 @@ class AccountVoucher(models.Model):
             total_lines.append([due_date, line.value_amount])
 
             for total_line in total_lines:
-                current_price = round(total * total_line[1], decimal_precision) 
+                current_price = round(total * total_line[1], decimal_precision)
+
+                if current_price < 0.0:
+                    continue
+
                 amount_paid += current_price
 
                 invoice_move_lines.append({
                     'type': 'dest',
                     'name': '/',
-                    'price': current_price if total_line[1] else total - amount_paid,
+                    'price': current_price if total_line[1] else round(total - amount_paid, decimal_precision) or total,
                     'account_id': invoice.account_id.id,
                     'date_maturity': total_line[0],            
-                    'amount_currency': invoice.company_id.currency_id.compute(total_line[1], invoice.currency_id) \
-                    if invoice.currency_id != invoice.company_id.currency_id else False,
+                    'amount_currency': invoice.company_id.currency_id.compute(total_line[1], invoice.currency_id) if invoice.currency_id != invoice.company_id.currency_id else False,
                     'currency_id': invoice.currency_id != invoice.company_id.currency_id and invoice.currency_id.id,
                     'ref': invoice.reference
                 })
 
             total_lines = []
 
-        # Step 5: Create account move
+        # Step 6: Create account move
         accounting_partner = self.env['res.partner']._find_accounting_partner(invoice.partner_id)
-        move_line_values = [(0, 0, invoice.line_get_convert(line, accounting_partner.id, invoice.date_invoice)) \
-        for line in invoice_move_lines]
+        move_line_values = [(0, 0, invoice.line_get_convert(line, accounting_partner.id, invoice.date_invoice)) for line in invoice_move_lines]
         move_line_values = invoice.group_lines(invoice_move_lines, move_line_values)
         move_line_values = invoice.finalize_invoice_move_lines(move_line_values)
 
@@ -120,13 +139,13 @@ class AccountVoucher(models.Model):
 
         account_move.post()
 
-        # Step 6: Validate invoice
+        # Step 7: Validate invoice
         invoice.action_number()
         invoice.write({
             'state': 'open'
         })
 
-        # Step 7: Create voucher
+        # Step 8: Create voucher
         account_voucher = self.create({
             'reference': account_move.name,
             'type': 'receipt',
@@ -138,6 +157,7 @@ class AccountVoucher(models.Model):
             'date': account_move.date,
             'partner_id': account_move.partner_id.id,
             'account_id': int(values['account_id']),
+            'currency_id': currency_id,
             'line_cr_ids': [[0, False, {
                 'date_due': l.date_maturity,
                 'account_id': l.account_id.id,
@@ -146,7 +166,8 @@ class AccountVoucher(models.Model):
                 'amount_original': abs(l.credit or l.debit or 0.0),
                 'amount_unreconciled': abs(l.amount_residual),
                 'amount': abs(l.debit) if account_move.date == l.date_maturity else 0.0,
-                'reconcile': account_move.date == l.date_maturity
+                'reconcile': account_move.date == l.date_maturity,
+                'currency_id': currency_id
             }] for l in account_move.line_id]
         })
 

+ 6 - 4
src/components/payment/credit/PaymentCreditAmount.vue

@@ -61,12 +61,12 @@
                 for (let line of this.selectedPaymentTerm.lines) {
                     let dueDate = moment(this.company.today).add(line.days + line.days2, 'days').format('YYYY-MM-DD')
 
-                    if (percentPaid) {
+                    if (percentPaid && percentPaid < 1) {
                         totals.push([this.company.today, percentPaid])
                         percentPaid = 0
 
                         if (dueDate === this.company.today) {
-                            distributePercent = -((this.totals[0] - line.value_amount) / (this.selectedPaymentTerm.lines.length - 1))
+                            distributePercent = -((totals[0][1] - line.value_amount) / (this.selectedPaymentTerm.lines.length - 1))
                             continue
                         }
                     }
@@ -80,8 +80,11 @@
 
                     for (let line of totals) {
                         let currentPrice = (this.total * line[1]).toFixed(2)
-                        residual = residual - currentPrice
 
+                        if (currentPrice < 0) continue
+
+                        residual = residual - currentPrice
+            
                         this.totalLines.push({
                             date: line[0], 
                             total: currentPrice !== parseFloat(0).toFixed(2) ? currentPrice : residual.toFixed(2)
@@ -102,7 +105,6 @@
         },
         mounted() {
             this.changeAmountPaid(0)
-            console.log(this.totalLines)
         }
     }
 </script>

+ 1 - 1
src/components/payment/method/PaymentDetails.vue

@@ -24,7 +24,7 @@
         transition(name="fade")
             .form-item(v-if="payment === 'credit'")
                 select.form-input.input-only(v-model="term")
-                    option(v-for="term in paymentTerms" :value="term" v-if="term.lines.length > 0 && term.lines[0].days !== 0") {{ term.display_name }}
+                    option(v-for="term in paymentTerms" :value="term" v-if="term.lines.length > 0 && (term.lines[0].days !== 0 || term.lines[0].value !== 'balance')") {{ term.display_name }}
             .form-item(v-else)
                 label.form-label Método de Pago
                 select.form-input(v-model="journal")

+ 27 - 30
src/store/actions.js

@@ -31,37 +31,34 @@ const actions = {
         return (getters.payment === 'cash' && getters.amountPaid >= getters.total) || dispatch('notify', 'El monto recibido no puede ser menor al monto a pagar')
     },
     completeSale({ getters, dispatch }) {
-        // return new Promise((resolve, reject) => {
-        //     let AccountVoucher = new openerp.web.Model('account.voucher')
+        return new Promise((resolve, reject) => {
+            let AccountVoucher = new openerp.web.Model('account.voucher')
 
-        //     AccountVoucher.call('create_from_pos', [
-        //         {
-        //             customer_id: getters.selectedCustomer.id,
-        //             payment_term_id: getters.selectedPaymentTerm.id,
-        //             journal_id: getters.selectedJournal.id,
-        //             account_id: getters.selectedJournal.default_credit_account.id,
-        //             cart_items: getters.cartItems.map(item => {
-        //                 return {
-        //                     id: item.id,
-        //                     qty: item.qty,
-        //                     price: item.list_price
-        //                 }
-        //             }),
-        //             cart_total: getters.total,
-        //             amount_paid: getters.amountPaid > getters.total ? getters.total : getters.amountPaid
-        //         }
-        //     ], {
-        //         context: new openerp.web.CompoundContext()
-        //     }).then(response => {
-        //         console.log(response)
-
-        //         resolve(response)
-        //     }).fail(error => {
-        //         reject(error)
-        //     })
-        // })
-
-        dispatch('reset')
+            AccountVoucher.call('create_from_pos', [
+                {
+                    customer_id: getters.selectedCustomer.id,
+                    payment_term_id: getters.selectedPaymentTerm.id,
+                    journal_id: getters.selectedJournal.id,
+                    account_id: getters.selectedJournal.default_credit_account.id,
+                    cart_items: getters.cartItems.map(item => {
+                        return {
+                            id: item.id,
+                            qty: item.qty,
+                            price: item.list_price
+                        }
+                    }),
+                    cart_total: getters.total,
+                    amount_paid: getters.amountPaid > getters.total ? getters.total : getters.amountPaid
+                }
+            ], {
+                context: new openerp.web.CompoundContext()
+            }).then(response => {
+                window.location.reload()
+                resolve(response)
+            }).fail(error => {
+                reject(error)
+            })
+        })
     },
     reset({ state }) {
         console.log(state)

+ 3 - 3
src/store/modules/account.js

@@ -108,11 +108,11 @@ const actions = {
         if (getters.payment === 'cash') {
             commit('setAmountPaid', payload)
         } else {
-            if (payload <= getters.total) {
+            if (payload <= (getters.total * 0.7)) {
                 commit('setAmountPaid', payload)
             } else {
-                commit('setAmountPaid', getters.total)
-                dispatch('notify', 'El monto entregado no puede mayor al total')
+                commit('setAmountPaid', getters.total * 0.7)
+                dispatch('notify', 'El monto entregado no puede sobrepasar el 70% del total')
             }
         }
     }