Debian Codegraph @

addons/l10n_my_edi/models/account_move.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 from odoo import Command, api, fields, models
3 from odoo.exceptions import UserError
4
5
6 class AccountMove(models.Model):
7 _inherit = "account.move"
8
9 # ------------------
10 # Fields declaration
11 # ------------------
12
13 l10n_my_edi_document_ids = fields.Many2many(
14 name="MyInvois Documents",
15 comodel_name="myinvois.document",
16 relation="myinvois_document_invoice_rel",
17 column1="invoice_id",
18 column2="document_id",
19 copy=False,
20 )
21 l10n_my_edi_display_tax_exemption_reason = fields.Boolean(
22 compute='_compute_l10n_my_edi_display_tax_exemption_reason',
23 string="Display Tax Exemption Reason",
24 export_string_translation=False,
25 )
26 l10n_my_invoice_need_edi = fields.Boolean(
27 compute='_compute_l10n_my_invoice_need_edi',
28 export_string_translation=False,
29 )
30 l10n_my_edi_state = fields.Selection(
31 string='MyInvois State',
32 help='State of this document on the MyInvois portal.\nA document awaiting validation will be automatically updated once the validation status is available.',
33 selection=[
34 ('in_progress', 'Validation In Progress'),
35 ('valid', 'Valid'),
36 ('rejected', 'Rejected'),
37 ('invalid', 'Invalid'),
38 ('cancelled', 'Cancelled'),
39 ],
40 compute='_compute_l10n_my_edi_state',
41 store=True,
42 tracking=True,
43 export_string_translation=False,
44 )
45 # Fields required to be set on the document in some cases.
46 l10n_my_edi_exemption_reason = fields.Char(
47 string="Tax Exemption Reason",
48 help="Buyer’s sales tax exemption certificate number, special exemption as per gazette orders, etc.\n"
49 "Only applicable if you are using a tax with a type 'Exempt'.",
50 )
51 l10n_my_edi_custom_form_reference = fields.Char(
52 string="Customs Form Reference Number",
53 help="Reference Number of Customs Form No.1, 9, etc.",
54 )
55
56 # --------------------------------
57 # Compute, inverse, search methods
58 # --------------------------------
59
60 @api.depends('l10n_my_edi_document_ids.myinvois_state')
61 def _compute_l10n_my_edi_state(self):
62 for move in self:
63 myinvois_document = move._get_active_myinvois_document(including_in_progress=True)
64 if not myinvois_document:
65 move.l10n_my_edi_state = False
66
67 move.l10n_my_edi_state = myinvois_document.myinvois_state
68
69 @api.depends('l10n_my_edi_state')
70 def _compute_need_cancel_request(self):
71 # EXTENDS 'account'
72 super()._compute_need_cancel_request()
73
74 @api.depends('l10n_my_edi_state')
75 def _compute_show_reset_to_draft_button(self):
76 # EXTEND 'account'
77 super()._compute_show_reset_to_draft_button()
78 # If the state is set, it means that we have an active document; and thus we need cancellation.
79 self.filtered(lambda m: m.l10n_my_edi_state).show_reset_to_draft_button = False
80
81 @api.depends('l10n_my_invoice_need_edi', 'l10n_my_edi_state')
82 def _compute_highlight_send_button(self):
83 # EXTENDS 'account' to not highlight the "Send" button when the "Send To MyInvois" button is available to have just one call to action.
84 super()._compute_highlight_send_button()
85 for move in self:
86 if move.l10n_my_invoice_need_edi:
87 move.highlight_send_button &= move.l10n_my_edi_state == 'valid'
88
89 @api.depends('company_id', 'invoice_line_ids.tax_ids')
90 def _compute_l10n_my_edi_display_tax_exemption_reason(self):
91 """ Some users will never use tax-exempt taxes, so it's better to only show the field when necessary. """
92 moves_per_proxy_users = self.grouped(lambda m: m._l10n_my_edi_get_proxy_user())
93 for proxy_user, moves in moves_per_proxy_users.items():
94 for move in moves:
95 should_display = proxy_user and any(tax.l10n_my_tax_type == 'E' for tax in move.invoice_line_ids.tax_ids)
96 move.l10n_my_edi_display_tax_exemption_reason = should_display
97
98 @api.depends('move_type', 'state', 'country_code', 'l10n_my_edi_state', 'company_id')
99 def _compute_l10n_my_invoice_need_edi(self):
100 for move in self:
101 # We return true for malaysian invoices which are not sent yet, sent but awaiting validation or valid.
102 move.l10n_my_invoice_need_edi = bool(
103 move.is_invoice()
104 and move.state == 'posted'
105 and move.country_code == 'MY'
106 and move.l10n_my_edi_state in (False, 'in_progress', 'valid')
107 and move._l10n_my_edi_get_proxy_user(),
108 )
109
110 # -----------------------
111 # CRUD, inherited methods
112 # -----------------------
113
114 def button_request_cancel(self):
115 # EXTENDS 'account'
116 super().button_request_cancel()
117
118 active_myinvois_document = self._get_active_myinvois_document()
119 if self._need_cancel_request() and active_myinvois_document:
120 return active_myinvois_document.action_cancel_submission()
121
122 return super().button_request_cancel()
123
124 def _get_fields_to_detach(self):
125 # EXTENDS account
126 fields_list = super()._get_fields_to_detach()
127 fields_list.append('l10n_my_edi_file')
128 return fields_list
129
130 def _need_cancel_request(self):
131 # EXTENDS 'account'
132 # For the in_progress state, we do not want to allow resetting to draft nor cancelling. We need to wait for the result first.
133 return super()._need_cancel_request() or self._get_active_myinvois_document()
134
135 def _get_name_invoice_report(self):
136 # EXTENDS 'account'
137 # Meaning we are a myinvois invoice, meaning we need to embed the qr code.
138 if self._get_active_myinvois_document():
139 return 'l10n_my_edi.report_invoice_document'
140 return super()._get_name_invoice_report()
141
142 # --------------
143 # Action methods
144 # --------------
145
146 def action_l10n_my_edi_update_status(self):
147 self.ensure_one()
148 self.l10n_my_edi_document_ids._get_active_myinvois_document(including_in_progress=True).action_update_submission_status()
149
150 def action_invoice_sent(self):
151 """ The wizard should not be available for invoices sent to MyInvois but not yet validated.
152 This is because before validation the ID used for the QR code is not available and the user should NOT send the invoice yet.
153 """
154 self.ensure_one()
155
156 if self.l10n_my_edi_state == 'in_progress':
157 raise UserError(self.env._('You cannot send invoices that are currently being validated.\nPlease wait for the validation to complete.'))
158
159 return super().action_invoice_sent()
160
161 def action_l10n_my_edi_send_invoice(self):
162 """
163 This action will create the MyInvois Document for this invoice if it does not already exist.
164 Once done, it will trigger the sending of said document to the platform.
165 """
166 invoice_needing_new_document = self.env['account.move']
167 myinvois_documents = self.env['myinvois.document']
168 for move in self.filtered(lambda m: m.state == 'posted'):
169 # It already has a valid document active on the platform, we don't want to send it again.
170 if move.l10n_my_edi_state:
171 continue
172
173 # On the other hand, if we already have a document in draft, or an invalid document, we allow sending it.
174 if valid_document := move.l10n_my_edi_document_ids.filtered(lambda d: d.myinvois_state in [False, 'invalid']):
175 myinvois_documents |= valid_document
176 else:
177 # If we don't have any valid documents, we'll create a new one.
178 invoice_needing_new_document |= move
179
180 myinvois_documents |= invoice_needing_new_document._create_myinvois_document()
181
182 if myinvois_documents:
183 myinvois_documents._submit_to_myinvois()
184
185 def action_show_myinvois_documents(self):
186 return self.l10n_my_edi_document_ids.action_show_myinvois_documents()
187
188 # ----------------
189 # Business methods
190 # ----------------
191
192 def _create_myinvois_document(self):
193 """ Helper which creates and link one MyInvois Document per invoice in self. """
194 myinvois_documents_vals = []
195 for move in self.filtered(lambda m: m.state == 'posted'):
196 myinvois_documents_vals.append({
197 'name': move.name,
198 'company_id': move.company_id.id,
199 'currency_id': move.currency_id.id,
200 'myinvois_issuance_date': move.invoice_date,
201 'invoice_ids': [Command.link(move.id)],
202 'myinvois_exemption_reason': move.l10n_my_edi_exemption_reason,
203 'myinvois_custom_form_reference': move.l10n_my_edi_custom_form_reference,
204 })
205 return self.env['myinvois.document'].create(myinvois_documents_vals)
206
207 def _l10n_my_edi_get_proxy_user(self):
208 """
209 Helper to retrieve the proxy user related to the company of the record.
210 """
211 self.ensure_one()
212 company = self.company_id or self.env.company
213 return company.sudo().l10n_my_edi_proxy_user_id
214
215 def _l10n_my_edi_cancel_moves(self):
216 """ Try to cancel the moves in self if allowed by the lock date. """
217 for move in self:
218 try:
219 move._check_fiscal_lock_dates()
220 move.line_ids._check_tax_lock_date()
221 move.button_cancel()
222 except UserError as e:
223 move.with_context(no_new_invoice=True).message_post(
224 body=self.env._(
225 'The invoice has been canceled on MyInvois, '
226 'But the cancellation in Odoo failed with error: %(error)s\n'
227 'Please resolve the problem manually, and then cancel the invoice.',
228 error=e,
229 ),
230 )
231
232 def _generate_myinvois_qr_code(self):
233 self.ensure_one()
234
235 myinvois_document = self._get_active_myinvois_document()
236 if not myinvois_document or not myinvois_document.myinvois_document_long_id:
237 return None
238
239 return myinvois_document._generate_myinvois_qr_code()
240
241 def _get_active_myinvois_document(self, including_in_progress=False):
242 """ Shortcut to get the active document of all invoice in self. """
243 return self.env['myinvois.document'].union(*[invoice.l10n_my_edi_document_ids._get_active_myinvois_document(including_in_progress) for invoice in self])