summaryrefslogtreecommitdiff
path: root/fixco_custom/models/account_move.py
blob: 58c94f758f2606971de905386ca1145b21064247 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
from cmath import e
from odoo import models, api, fields, _
from odoo.exceptions import AccessError, UserError, ValidationError
from datetime import timedelta, date, datetime
from pytz import timezone, utc
import logging
import base64
import PyPDF2
import os
import re

_logger = logging.getLogger(__name__)


class AccountMove(models.Model):
    _inherit = 'account.move'

    invoice_marketplace = fields.Char('Invoice Marketplace')
    address = fields.Char('Address')
    sale_id = fields.Many2one('sale.order', string='Sale Order')
    picking_id = fields.Many2one('stock.picking', string='Picking')
    transaction_type = fields.Selection(
        [('digunggung', 'Digunggung'),
         ('difaktur', 'Faktur Pajak')],
        string='Transaction Type'
    )
    purchase_vendor_bill_ids = fields.Many2many(
        'purchase.bill.union',
        string='Auto-complete',
        store=False,
        readonly=True,
        states={'draft': [('readonly', False)]},
        help="Auto-complete from multiple past bills / purchase orders.",
    )
    faktur_pajak = fields.Char('Faktur Pajak')
    count_payment = fields.Integer('Count Payment', compute='_compute_count_payment')
    reklas_misc_id = fields.Many2one('account.move', string='Journal Entries Reklas')
    purchase_order_id = fields.Many2one('purchase.order', string='Purchase Order')
    bill_id = fields.Many2one('account.move', string='Vendor Bill', domain=[('move_type', '=', 'in_invoice')], help='Bill asal dari proses reklas ini')
    count_reverse = fields.Integer('Count Reverse', compute='_compute_count_reverse')
    uangmuka = fields.Boolean('Uang Muka?')
    reklas = fields.Boolean('Reklas?')
    reklas_used = fields.Boolean('Reklas Used?', compute='_compute_reklas_used', store=True)
    reklas_used_by = fields.Many2one('account.move', string='Reklas Used By', compute='_compute_reklas_used', store=True)
    need_refund = fields.Boolean(
        string="Need Refund",
        compute="_compute_need_refund",
        help="Flag otomatis kalau invoice sudah paid dan picking terkait di-return."
    )

    def _compute_need_refund(self):
        for move in self:
            flag = False
            if move.move_type == 'out_invoice' and move.payment_state == 'paid' and move.invoice_origin:
                refund_exists = bool(self.env['account.move'].search([('reversed_entry_id', '=', move.id), ('payment_state', '=', 'paid')]))
                if not refund_exists:
                    sale_orders = self.env['sale.order'].search([('name', '=', move.invoice_origin)])
                    if sale_orders:
                        pickings = sale_orders.picking_ids.filtered(lambda p: p.state == 'done' and p.is_return)
                        if pickings:
                            flag = True
            move.need_refund = flag


    def export_faktur_to_xml(self):
        valid_invoices = self

        coretax_faktur = self.env['coretax.faktur'].create({})

        response = coretax_faktur.export_to_download(
            invoices=valid_invoices
        )

        valid_invoices.write({
            'is_efaktur_exported': True,
            'date_efaktur_exported': datetime.utcnow(),
        })

        return response

    @api.depends('line_ids.reconciled', 'line_ids.matching_number')
    def _compute_reklas_used(self):
        for move in self:
            move.reklas_used = False
            move.reklas_used_by = None

            if move.move_type != 'entry':
                continue

            matching_numbers = move.line_ids.filtered(lambda l: l.reconciled and l.matching_number).mapped('matching_number')

            if not matching_numbers:
                continue

            invoice_lines = self.env['account.move.line'].search([
                ('reconciled', '=', True),
                ('matching_number', 'in', matching_numbers),
                ('move_id.move_type', '=', 'out_invoice'),
            ], limit=1)

            if invoice_lines:
                move.reklas_used = True
                move.reklas_used_by = invoice_lines.move_id

    def _compute_count_reverse(self):
        for move in self:
            accountMove = self.env['account.move']

            reverse = accountMove.search([]).filtered(
                lambda p: move.id in p.reversed_entry_id.ids
            )

            move.count_reverse = len(reverse)

    def action_view_related_reverse(self):
        self.ensure_one()

        accountMove = self.env['account.move']

        reverse = accountMove.search([]).filtered(
            lambda p: self.id in p.reversed_entry_id.ids
        )

        reverses = reverse

        return {
            'name': 'Refund',
            'type': 'ir.actions.act_window',
            'res_model': 'account.move',
            'view_mode': 'tree,form',
            'target': 'current',
            'domain': [('id', 'in', list(reverses.ids))],
        }


    def action_reverse(self):
        action = self.env["ir.actions.actions"]._for_xml_id("account.action_view_account_move_reversal")

        if self.is_invoice():
            action['name'] = _('Credit Note')

        if len(self) == 1:
            action['context'] = {
                'default_journal_id': self.journal_id.id,
            }

        return action

    def open_form_multi_create_reklas_penjualan(self):
        action = self.env['ir.actions.act_window']._for_xml_id('fixco_custom.action_view_invoice_reklas_penjualan')
        invoice = self.env['invoice.reklas.penjualan'].create([{
            'name': '-',
        }])
        for move in self:
            sale_id = move.sale_id.id
            self.env['invoice.reklas.penjualan.line'].create([{
                'invoice_reklas_id': invoice.id,
                'name': move.name,
                'partner_id': move.partner_id.id,
                'sale_id': move.sale_id.id,
                'amount_untaxed_signed': move.amount_untaxed_signed,
                'amount_total_signed': move.amount_total_signed,
            }])
        action['res_id'] = invoice.id
        return action

    def _compute_count_payment(self):
        for move in self:
            accountPayment = self.env['account.payment']

            payment = accountPayment.search([]).filtered(
                lambda p: move.id in p.reconciled_bill_ids.ids
            )


            move.count_payment = len(payment)

    def action_view_related_payment(self):
        self.ensure_one()

        accountPayment = self.env['account.payment']

        payment = accountPayment.search([]).filtered(
            lambda p: self.id in p.reconciled_bill_ids.ids
        )

        payments = payment

        return {
            'name': 'Payments',
            'type': 'ir.actions.act_window',
            'res_model': 'account.payment',
            'view_mode': 'tree,form',
            'target': 'current',
            'domain': [('id', 'in', list(payments.ids))],
        }

    def action_post(self):
        res = super(AccountMove, self).action_post()
        for entry in self:
            if entry.move_type == 'out_invoice':
                if entry.picking_id:
                    entry.invoice_date = entry.picking_id.date_done


        return res

    @api.onchange('purchase_vendor_bill_ids', 'purchase_id')
    def _onchange_purchase_auto_complete(self):
        """ Load from either multiple old purchase orders or vendor bills. """

        vendor_bills = self.purchase_vendor_bill_ids.mapped('vendor_bill_id')
        purchase_orders = self.purchase_vendor_bill_ids.mapped('purchase_order_id')

        for bill in vendor_bills:
            self.invoice_vendor_bill_id = bill
            self._onchange_invoice_vendor_bill()

        for po in purchase_orders:
            self.purchase_id = po

            invoice_vals = po.with_company(po.company_id)._prepare_invoice()
            invoice_vals['currency_id'] = self.line_ids and self.currency_id or invoice_vals.get('currency_id')
            invoice_vals.pop('ref', None)
            self.update(invoice_vals)

            po_lines = po.order_line.filtered(lambda l: l.qty_received != l.qty_invoiced and l.qty_invoiced <= l.qty_received) - self.line_ids.mapped('purchase_line_id')
            new_lines = self.env['account.move.line']
            sequence = max(self.line_ids.mapped('sequence')) + 1 if self.line_ids else 10

            for line in po_lines.filtered(lambda l: not l.display_type):
                line_vals = line._prepare_account_move_line(self)
                line_vals.update({'sequence': sequence})
                new_line = new_lines.new(line_vals)
                sequence += 1
                new_line.account_id = new_line._get_computed_account()
                new_line._onchange_price_subtotal()
                new_lines += new_line

            new_lines._onchange_mark_recompute_taxes()


        # Compute invoice_origin
        origins = set(self.line_ids.mapped('purchase_line_id.order_id.name'))
        self.invoice_origin = ', '.join(origins)

        # Compute ref
        refs = self._get_invoice_reference()
        self.ref = ', '.join(refs)

        # Compute payment_reference
        if len(refs) == 1:
            self.payment_reference = refs[0]

        self.purchase_id = False
        self.purchase_vendor_bill_ids = [(5, 0, 0)]  # clear after use
        self._onchange_currency()