Debian Codegraph @

addons/l10n_tw_edi_ecpay/models/account_move.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import base64
4 import re
5 import uuid
6
7 from urllib.parse import urljoin
8
9 from odoo import api, fields, models
10 from odoo.addons.l10n_tw_edi_ecpay.utils import call_ecpay_api, transfer_time, convert_utc_time_to_tw_time
11 from odoo.exceptions import UserError
12 from odoo.tools import float_round
13
14
15 class AccountMove(models.Model):
16 _inherit = "account.move"
17
18 # ------------------
19 # Fields declaration
20 # ------------------
21
22 l10n_tw_edi_file_id = fields.Many2one(
23 comodel_name="ir.attachment",
24 compute=lambda self: self._compute_linked_attachment_id("l10n_tw_edi_file_id", "l10n_tw_edi_file"),
25 depends=["l10n_tw_edi_file"],
26 copy=False,
27 export_string_translation=False,
28 )
29 l10n_tw_edi_file = fields.Binary(
30 string="Ecpay JSON File",
31 copy=False,
32 readonly=True,
33 export_string_translation=False,
34 )
35 l10n_tw_edi_ecpay_invoice_id = fields.Char(string="Ecpay Invoice Number", readonly=True, copy=False)
36 l10n_tw_edi_related_number = fields.Char(
37 string="Related Number",
38 copy=False,
39 readonly=True,
40 store=True,
41 )
42 # False => Not sent yet.
43 l10n_tw_edi_state = fields.Selection(
44 string="Invoice Status",
45 selection=[
46 ("invoiced", "Invoiced"),
47 ("valid", "Valid"),
48 ("invalid", "Invalid"),
49 ],
50 copy=False,
51 readonly=True,
52 tracking=True,
53 )
54 l10n_tw_edi_love_code = fields.Char(string="Love Code", compute="_compute_love_code", store=True, readonly=False)
55 l10n_tw_edi_is_print = fields.Boolean(
56 string="Get Printed Version",
57 compute="_compute_is_print",
58 store=True,
59 readonly=False,
60 )
61 l10n_tw_edi_carrier_type = fields.Selection(
62 string="Carrier Type",
63 selection=[
64 ("1", "ECpay e-invoice carrier"),
65 ("2", "Citizen Digital Certificate"),
66 ("3", "Mobile Barcode"),
67 ("4", "EasyCard"),
68 ("5", "iPass"),
69 ],
70 copy=False,
71 readonly=False,
72 compute="_compute_carrier_info",
73 store=True,
74 help="""
75 - Citizen Digital Certificate: The carrier number format is 2 capital letters following 14 digits.
76 - Mobile Barcode: The carrier number format is / following 7 alphanumeric or +-. string.
77 - EasyCard or iPass: The carrier number is the card hidden code, the carrier number 2 is the card visible code.
78 """
79 )
80 l10n_tw_edi_carrier_number = fields.Char(
81 string="Carrier Number",
82 compute="_compute_carrier_info",
83 store=True,
84 readonly=False,
85 copy=False,
86 )
87 l10n_tw_edi_carrier_number_2 = fields.Char(
88 string="Carrier Number 2",
89 compute="_compute_carrier_info",
90 store=True,
91 readonly=False,
92 copy=False,
93 )
94 l10n_tw_edi_invoice_type = fields.Selection(
95 string="Ecpay Invoice Type",
96 selection=[
97 ("07", "General Invoice"),
98 ("08", "Special Invoice"),
99 ],
100 compute="_compute_l10n_tw_edi_invoice_type",
101 store=True,
102 readonly=False,
103 copy=False,
104 )
105 l10n_tw_edi_clearance_mark = fields.Selection(
106 string="Clearance Mark",
107 selection=[
108 ("1", "NOT via the customs"),
109 ("2", "Via the customs"),
110 ],
111 copy=False,
112 )
113 l10n_tw_edi_zero_tax_rate_reason = fields.Selection(
114 string="Zero Tax Rate Reason",
115 selection=[
116 ("71", "71: No.1 export goods"),
117 ("72", "72: No.2 Services related to export sales, or services provided domestically but used abroad"),
118 ("73", "73: No.3 Duty-free shops established by law for the sale and transit or departure of passengers"),
119 ("74", "74: No.4 Sale of goods or services for operation by the operator of the FREE Trade Zone"),
120 ("75", "75: No.5 International transportation. However, foreign transport undertakings operating "
121 "international transport business in Taiwan shall be limited to those whose countries shall give equal "
122 "treatment to Taiwan's international transport undertakings or be exempt from similar taxes"),
123 ("76", "76: No.6 Ships, aircraft and distant-water fishing vessels for international transportation"),
124 ("77", "77: No.7 Goods or repair services used by ships, aircraft and distant-water fishing vessels for "
125 "sale and international transport"),
126 ("78", "78: No.8 The bonded area operator sells goods that are not directly exported by the taxable "
127 "area operator and the taxable area operator is not exported to the taxation area"),
128 ("79", "79: No.9 The bonded area operator sells the goods that the taxable area operator deposits into the "
129 "bonded warehouse or logistics center managed by the free port area or customs administration for export"),
130 ],
131 copy=False,
132 )
133 l10n_tw_edi_is_zero_tax_rate = fields.Boolean(
134 string="Is Zero Tax Rate",
135 compute="_compute_l10n_tw_edi_is_zero_tax_rate",
136 copy=False,
137 )
138 l10n_tw_edi_invoice_create_date = fields.Datetime(string="Creation Date", readonly=True, copy=False)
139 l10n_tw_edi_refund_state = fields.Selection(
140 string="Refund State",
141 selection=[
142 ("to_be_agreed", "To be agreed"),
143 ("agreed", "Agreed"),
144 ("disagreed", "Disagreed"),
145 ],
146 readonly=True,
147 copy=False,
148 )
149 l10n_tw_edi_refund_agreement_type = fields.Selection(
150 string="Refund invoice Agreement Type",
151 selection=[
152 ("offline", "Offline Agreement"),
153 ("online", "Online Agreement"),
154 ],
155 copy=False,
156 )
157 l10n_tw_edi_allowance_notify_way = fields.Selection(
158 string="Allowance Notify Way",
159 selection=[
160 ("email", "Email"),
161 ("phone", "Phone"),
162 ],
163 copy=False,
164 )
165 l10n_tw_edi_invalidate_reason = fields.Char(string="Invalidate Reason", readonly=True, copy=False)
166 l10n_tw_edi_refund_invoice_number = fields.Char(string="Refund Invoice Number", readonly=True, copy=False)
167 l10n_tw_edi_is_b2b = fields.Boolean(string="Is B2B", compute="_compute_l10n_tw_edi_is_b2b")
168
169 @api.depends("l10n_tw_edi_state")
170 def _compute_need_cancel_request(self):
171 # EXTENDS 'account'
172 super()._compute_need_cancel_request()
173
174 @api.depends("l10n_tw_edi_state", "l10n_tw_edi_refund_state")
175 def _compute_show_reset_to_draft_button(self):
176 # EXTEND 'account'
177 super()._compute_show_reset_to_draft_button()
178 if self.move_type == "out_invoice":
179 self.filtered(lambda m: m.l10n_tw_edi_state and m.l10n_tw_edi_state != "invalid").show_reset_to_draft_button = False
180 elif self.move_type == "out_refund":
181 self.filtered(lambda m: m.l10n_tw_edi_refund_state).show_reset_to_draft_button = False
182
183 def _need_cancel_request(self):
184 # EXTENDS 'account'
185 return super()._need_cancel_request() or self.l10n_tw_edi_state in ["invoiced", "valid"]
186
187 def button_request_cancel(self):
188 # EXTENDS 'account'
189 if self._need_cancel_request() and self.l10n_tw_edi_state in ["invoiced", "valid"]:
190 return {
191 "name": self.env._("Cancel Ecpay Invoice"),
192 "type": "ir.actions.act_window",
193 "view_type": "form",
194 "view_mode": "form",
195 "res_model": "l10n_tw_edi.invoice.cancel",
196 "target": "new",
197 "context": {
198 "default_invoice_id": self.id,
199 },
200 }
201 return super().button_request_cancel()
202
203 def button_draft(self):
204 # EXTENDS 'account'
205 invoices_to_reset = self.filtered(
206 lambda i: (i.state == "cancel" and i.l10n_tw_edi_state == "invalid")
207 )
208 res = super().button_draft()
209
210 invoices_to_reset.write({
211 "l10n_tw_edi_related_number": False,
212 "l10n_tw_edi_state": False,
213 "l10n_tw_edi_ecpay_invoice_id": False,
214 "l10n_tw_edi_invoice_create_date": False,
215 "l10n_tw_edi_invalidate_reason": False,
216 })
217 invoices_to_reset.l10n_tw_edi_file_id.unlink()
218 return res
219
220 @api.depends("l10n_tw_edi_love_code", "l10n_tw_edi_carrier_type", "partner_id")
221 def _compute_is_print(self):
222 for move in self:
223 if move.l10n_tw_edi_love_code or (move.partner_id.vat and move.l10n_tw_edi_carrier_type in [1, 2]):
224 move.l10n_tw_edi_is_print = False
225
226 @api.depends("l10n_tw_edi_is_print", "l10n_tw_edi_carrier_type", "partner_id")
227 def _compute_love_code(self):
228 for move in self:
229 if move.l10n_tw_edi_is_print or move.l10n_tw_edi_carrier_type or move.partner_id.vat:
230 move.l10n_tw_edi_love_code = False
231
232 @api.depends("l10n_tw_edi_is_print", "l10n_tw_edi_love_code")
233 def _compute_carrier_info(self):
234 for move in self:
235 if move.l10n_tw_edi_is_print or move.l10n_tw_edi_love_code:
236 move.l10n_tw_edi_carrier_type = False
237 move.l10n_tw_edi_carrier_number = False
238 move.l10n_tw_edi_carrier_number_2 = False
239
240 @api.depends("invoice_line_ids.tax_ids")
241 def _compute_l10n_tw_edi_invoice_type(self):
242 for move in self:
243 tax_type, special_tax_type, _ = move._l10n_tw_edi_determine_tax_types()
244 if tax_type == "3":
245 move.l10n_tw_edi_invoice_type = "07" if not special_tax_type else "08"
246 else:
247 move.l10n_tw_edi_invoice_type = "07" if tax_type != "4" else "08"
248
249 @api.depends("invoice_line_ids.tax_ids")
250 def _compute_l10n_tw_edi_is_zero_tax_rate(self):
251 for move in self:
252 _, _, is_zero_tax_rate = move._l10n_tw_edi_determine_tax_types()
253 move.l10n_tw_edi_is_zero_tax_rate = is_zero_tax_rate if move.invoice_line_ids.tax_ids else False
254
255 @api.depends("partner_id")
256 def _compute_l10n_tw_edi_is_b2b(self):
257 for rec in self:
258 rec.l10n_tw_edi_is_b2b = rec.partner_id.commercial_partner_id.is_company
259
260 # ----------------
261 # Business methods
262 # ----------------
263 def _get_mail_thread_data_attachments(self):
264 res = super()._get_mail_thread_data_attachments()
265 return res | self.l10n_tw_edi_file_id
266
267 # API methods
268 def _l10n_tw_edi_check_tax_type_on_invoice_lines(self):
269 """
270 Check the tax type and special tax type on the invoice lines
271 """
272 self.ensure_one()
273 product_lines = self.invoice_line_ids.filtered(lambda line: line.display_type == "product")
274 errors = []
275 # Invoice lines without tax or having multiple taxes are not allowed
276 if product_lines.filtered(lambda line: not line.tax_ids or len(line.tax_ids) > 1):
277 errors.append(self.env._("Invoice lines without taxes or more than one tax are not allowed."))
278
279 if len(set(product_lines.tax_ids.mapped('price_include'))) > 1:
280 errors.append(self.env._("Invoice lines with different tax include/exclude are not allowed."))
281
282 # Create a set of tax types on invoice lines to check if there are multiple tax types or specific tax type on the invoice lines
283 invoice_lines_tax_types = set(product_lines.tax_ids.mapped('l10n_tw_edi_tax_type'))
284
285 if invoice_lines_tax_types:
286 # Tax type "4" is a special tax rate, cannot be mixed with other tax types
287 if "4" in invoice_lines_tax_types and len(invoice_lines_tax_types) > 1:
288 errors.append(self.env._(
289 "Special tax type cannot be mixed with other tax types."
290 ))
291
292 special_tax_types_4 = set(product_lines.tax_ids.filtered(
293 lambda t: t.l10n_tw_edi_tax_type == '4'
294 ).mapped('l10n_tw_edi_special_tax_type'))
295
296 if "4" in invoice_lines_tax_types and len(special_tax_types_4) > 1:
297 errors.append(self.env._(
298 "Special tax type cannot be mixed with other special tax types."
299 ))
300
301 special_tax_types_3 = set(product_lines.tax_ids.filtered(
302 lambda t: t.l10n_tw_edi_tax_type == '3'
303 ).mapped('l10n_tw_edi_special_tax_type'))
304
305 if "3" in invoice_lines_tax_types and len(special_tax_types_3) > 1:
306 errors.append(self.env._(
307 "Duty free with special tax type cannot be mixed with duty free without special tax type or having more than one special tax type."
308 ))
309
310 if "3" in invoice_lines_tax_types and next(iter(special_tax_types_3)) == "8" and len(invoice_lines_tax_types) > 1:
311 errors.append(self.env._(
312 "Duty free with special tax type cannot be mixed with other tax types."
313 ))
314
315 if {"2", "3"}.issubset(invoice_lines_tax_types):
316 errors.append(self.env._(
317 "Tax type 2 (Zero tax rate) and type 3 (Duty free) cannot be used together."
318 ))
319
320 tax_type_1_rates = product_lines.tax_ids.filtered(
321 lambda t: t.l10n_tw_edi_tax_type == '1'
322 ).mapped('amount')
323
324 if "1" in invoice_lines_tax_types and any(rate != 5 for rate in tax_type_1_rates):
325 errors.append(self.env._(
326 "Amount for Taxable tax type must be 5%."
327 ))
328 else:
329 errors.append(self.env._(
330 "Please fill in the tax on the invoice lines and select the Ecpay tax type for taxes."
331 ))
332 return errors
333
334 def _l10n_tw_edi_determine_tax_types(self):
335 """
336 Calculate and return the tax type, special tax type and is zero tax rate included based on
337 the taxes on invoice lines
338
339 :return: A tuple containing the tax type information.
340 - tax_type (str): The tax type ("1", "2", "3", "4") or "9" for mixed taxes.
341 - special_tax_type (int): The special tax type code.
342 - is_zero_tax_rate (bool): True if it is zero tax rate.
343 """
344 self.ensure_one()
345 product_lines = self.invoice_line_ids.filtered(lambda line: line.display_type == "product")
346 # Create a set of tax types on invoice lines to check if there are multiple tax types or specific tax type on the invoice lines
347 invoice_lines_tax_types = set(product_lines.tax_ids.mapped('l10n_tw_edi_tax_type'))
348
349 tax_type = False
350 special_tax_type = False
351 is_zero_tax_rate = False
352
353 if invoice_lines_tax_types:
354 if len(invoice_lines_tax_types) > 1: # mixed tax types
355 tax_type = "9"
356 special_tax_type = 0
357 is_zero_tax_rate = "2" in invoice_lines_tax_types
358 elif "4" in invoice_lines_tax_types: # special tax rate
359 tax_type = "4"
360 special_tax_type = int(product_lines.tax_ids.mapped('l10n_tw_edi_special_tax_type')[0])
361 elif "3" in invoice_lines_tax_types:
362 tax_type = "3"
363 special_tax_type = 8 if product_lines.tax_ids[0].l10n_tw_edi_special_tax_type == "8" else False
364 else:
365 tax_type = next(iter(invoice_lines_tax_types))
366 special_tax_type = 0
367 is_zero_tax_rate = "2" in invoice_lines_tax_types
368 return tax_type, special_tax_type, is_zero_tax_rate
369
370 def _l10n_tw_edi_convert_currency_to_twd(self, amount):
371 """
372 Convert currency to TWD if the currency is not TWD
373 """
374 self.ensure_one()
375 if self.currency_id.name == "TWD":
376 return amount
377 return self.currency_id._convert(amount, self.env.ref("base.TWD"), self.company_id, self.invoice_date or self.date, round=False)
378
379 @api.model
380 def _reformat_phone_number(self, phone):
381 """
382 Cleans and reformats a phone number string by handling different input formats.
383
384 The method first replaces a leading plus sign ('+') with a '0' and removes any
385 following space. It then removes all non-digit characters (including spaces,
386 dashes, and parentheses) to return a clean, continuous number string.
387
388 :param phone: The phone number as a string.
389 :type phone: str
390 :return: A cleaned and reformatted phone number string.
391 :rtype: str
392
393 Example:
394 # Replaces leading '+' with '0' and removes spaces/dashes
395 _reformat_phone_number('+1 555-123-4567') # returns '05551234567'
396
397 # Removes spaces and parentheses
398 _reformat_phone_number('(555) 123 4567') # returns '5551234567'
399 """
400 cleaned_number = phone
401 # Replace leading '+' with '0'
402 if phone.startswith('+'):
403 if ' ' in phone:
404 parts = phone.split(' ', 1)
405 cleaned_number = '0' + parts[1]
406 else:
407 cleaned_number = '0' + phone[1:]
408 # Remove spaces, dashes, parentheses, etc.
409 cleaned_number = re.sub(r'[^\d+]', '', cleaned_number)
410 return cleaned_number
411
412 def _l10n_tw_edi_check_before_generate_invoice_json(self):
413 self.ensure_one()
414 errors = []
415 if not self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id:
416 errors.append(self.env._("Please fill in the ECpay API information in the Setting!"))
417
418 if (self.l10n_tw_edi_is_print or self.partner_id.vat) and not self.partner_id.contact_address:
419 errors.append(self.env._("Please fill in the customer address for printing Ecpay invoice."))
420
421 if not self.partner_id.email and not self.partner_id.phone:
422 errors.append(self.env._("Please fill in the customer email or phone number for Ecpay invoice creation."))
423
424 if self.partner_id.phone:
425 formatted_phone = self._reformat_phone_number(self.partner_id.phone)
426 if not re.fullmatch(r'[\d]+', formatted_phone):
427 errors.append(self.env._("Phone number contains invalid characters! It should be in the format: '+886 0997624293'."))
428
429 if self.l10n_tw_edi_is_b2b and not self.partner_id.vat:
430 errors.append(self.env._("A tax ID is required for company contact or individual contact under a company."))
431
432 if self.l10n_tw_edi_is_b2b and self.partner_id.vat and (not self.partner_id.vat.isdigit() or len(self.partner_id.vat) != 8):
433 errors.append(self.env._("The tax ID is invalid. It should be in the format: '12345678'."))
434
435 errors.extend(self._l10n_tw_edi_check_tax_type_on_invoice_lines())
436
437 tax_type, _, is_zero_tax_rate = self._l10n_tw_edi_determine_tax_types()
438
439 if self.l10n_tw_edi_invoice_type == "07" and tax_type not in ["1", "2", "3", "9"]:
440 errors.append(self.env._(
441 "Invoice type 07 must be used with tax type 1, 2, 3 or 9. Please check the tax type on the invoice lines."
442 ))
443
444 if self.l10n_tw_edi_invoice_type == "08" and tax_type not in ["3", "4"]:
445 errors.append(self.env._(
446 "Invoice type 08 must be used with tax type 3 or 4. Please check the tax type on the invoice lines."
447 ))
448
449 if is_zero_tax_rate:
450 if not self.l10n_tw_edi_clearance_mark or not self.l10n_tw_edi_zero_tax_rate_reason:
451 errors.append(self.env._(
452 "Clearance mark and zero tax rate reason are required for a zero tax rate invoice."
453 ))
454 if errors:
455 if 'website_id' in self._fields and self.website_id:
456 self.message_post(body="Error:\n" + "\n".join(errors))
457 else:
458 raise UserError("Error:\n" + "\n".join(errors))
459
460 def _l10n_tw_edi_prepare_item_list(self, json_data, is_allowance=False):
461 self.ensure_one()
462 item_list = []
463 sale_amount = 0
464 tax_amount = 0
465 AccountTax = self.env['account.tax']
466 tax_type, _, _ = self._l10n_tw_edi_determine_tax_types()
467 for index, line in enumerate(self.invoice_line_ids.filtered(lambda line: line.display_type == "product"), start=1):
468 base_line = self._prepare_product_base_line_for_taxes_computation(line)
469 if is_allowance and self.reversed_entry_id.currency_id == self.currency_id:
470 base_line['rate'] = self.reversed_entry_id.invoice_currency_rate # replace the rate by the original invoice's rate
471 AccountTax._add_tax_details_in_base_line(base_line, self.company_id)
472
473 twd_excluded_amount = base_line['tax_details']['raw_total_excluded']
474 twd_included_amount = base_line['tax_details']['raw_total_included']
475 quantity = abs(line.quantity)
476
477 if self.l10n_tw_edi_is_b2b:
478 item_price = float_round(twd_excluded_amount / quantity, precision_rounding=0.01)
479 item_amount = float_round(twd_excluded_amount, precision_rounding=0.01)
480 else:
481 if not is_allowance and line.tax_ids and not line.tax_ids[0].price_include:
482 item_price = float_round(twd_excluded_amount / quantity, precision_rounding=0.01)
483 item_amount = float_round(twd_excluded_amount, precision_rounding=0.01)
484 else:
485 item_price = float_round(twd_included_amount / quantity, precision_rounding=0.01)
486 item_amount = float_round(twd_included_amount, precision_rounding=0.01)
487
488 item_amount_taxed = float_round(twd_included_amount, precision_rounding=0.01)
489
490 # For special tax, we use twd_included_amount
491 if tax_type == "4":
492 item_price = float_round(twd_included_amount / quantity, precision_rounding=0.01)
493 item_amount = float_round(twd_included_amount, precision_rounding=0.01)
494
495 # Set item sequence for each invoice line, the sequence cannot start from 0
496 if not is_allowance:
497 line.l10n_tw_edi_ecpay_item_sequence = index
498
499 if self.l10n_tw_edi_is_b2b and is_allowance:
500 item_list.append({
501 "OriginalInvoiceNumber": self.l10n_tw_edi_ecpay_invoice_id,
502 "OriginalInvoiceDate": convert_utc_time_to_tw_time(self.l10n_tw_edi_invoice_create_date),
503 "OriginalSequenceNumber": line.l10n_tw_edi_ecpay_item_sequence,
504 "ItemName": line.name[:100],
505 "ItemCount": quantity,
506 "ItemPrice": item_price,
507 "ItemAmount": item_amount,
508 })
509 else:
510 item_list.append({
511 "ItemSeq": line.l10n_tw_edi_ecpay_item_sequence,
512 "ItemName": line.name[:100],
513 "ItemCount": quantity,
514 "ItemWord": line.product_uom_id.name[:6] if line.product_uom_id else False,
515 "ItemPrice": item_price,
516 "ItemTaxType": line.tax_ids[0].l10n_tw_edi_tax_type if tax_type != "4" and line.tax_ids else "",
517 "ItemAmount": item_amount,
518 })
519 if self.l10n_tw_edi_is_b2b:
520 sale_amount += item_amount
521 tax_amount += base_line["tax_details"]["taxes_data"][0]["raw_tax_amount"]
522 else:
523 sale_amount += item_amount_taxed
524
525 # Sale amount adjustment
526 amount_on_invoice = self.amount_untaxed_signed if self.l10n_tw_edi_is_b2b and tax_type != "4" else self.amount_total_signed
527 difference = self.company_id.currency_id.round(sale_amount) - abs(amount_on_invoice)
528 if difference != 0:
529 item_list[-1]["ItemAmount"] -= difference
530 item_list[-1]["ItemAmount"] = float_round(item_list[-1]["ItemAmount"], precision_rounding=0.01)
531 item_list[-1]["ItemPrice"] = float_round(item_list[-1]["ItemAmount"] / item_list[-1]["ItemCount"], precision_rounding=0.01)
532 sale_amount -= difference
533
534 # Credit note adjustment
535 if is_allowance:
536 # Check if the credit note has exchange difference, we need to add it to the sale amount
537 reconciled_partials = self._get_all_reconciled_invoice_partials()
538 exchange_difference = sum(item["amount"] for item in reconciled_partials if item.get("is_exchange"))
539 if exchange_difference and self.l10n_tw_edi_is_b2b and tax_type != "4":
540 tax_rate = abs(self.amount_untaxed_signed) / abs(self.amount_total_signed)
541 exchange_difference = self.company_id.currency_id.round(exchange_difference * tax_rate) # Use untaxed amount for B2B and non special type credit notes
542 if self.reversed_entry_id.invoice_currency_rate > self.invoice_currency_rate:
543 exchange_difference = exchange_difference * -1 # Convert to negative if the exchange rate is lower than the original invoice rate
544 item_list[-1]["ItemAmount"] += exchange_difference
545 item_list[-1]["ItemAmount"] = float_round(item_list[-1]["ItemAmount"], precision_rounding=0.01)
546 item_list[-1]["ItemPrice"] = float_round(item_list[-1]["ItemAmount"] / item_list[-1]["ItemCount"], precision_rounding=0.01)
547 sale_amount += exchange_difference
548
549 if self.l10n_tw_edi_is_b2b and is_allowance:
550 json_data["Details"] = item_list
551 else:
552 json_data["Items"] = item_list
553
554 if not is_allowance:
555 json_data["SalesAmount"] = self.company_id.currency_id.round(sale_amount)
556 else:
557 if self.l10n_tw_edi_is_b2b:
558 json_data["TotalAmount"] = self.company_id.currency_id.round(sale_amount)
559 else:
560 json_data["AllowanceAmount"] = self.company_id.currency_id.round(sale_amount)
561
562 if self.l10n_tw_edi_is_b2b:
563 json_data["TaxAmount"] = self.company_id.currency_id.round(tax_amount) if tax_type != "4" else 0
564
565 def _l10n_tw_edi_generate_invoice_json(self):
566 self.ensure_one()
567 self._l10n_tw_edi_check_before_generate_invoice_json()
568 tax_type, special_tax_type, is_zero_tax_rate = self._l10n_tw_edi_determine_tax_types()
569 self.l10n_tw_edi_related_number = base64.urlsafe_b64encode(uuid.uuid4().bytes)[:20]
570 formatted_phone = self._reformat_phone_number(self.partner_id.phone) if self.partner_id.phone else ""
571 product_lines = self.invoice_line_ids.filtered(lambda line: line.display_type == "product")
572 vat = "1" if product_lines[0].tax_ids and product_lines[0].tax_ids[0].price_include else "0"
573
574 json_data = {
575 "MerchantID": self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
576 "RelateNumber": self.l10n_tw_edi_related_number,
577 "CustomerIdentifier": self.partner_id.vat if self.l10n_tw_edi_is_b2b and self.partner_id.vat else "",
578 "CustomerAddr": self.partner_id._l10n_tw_edi_formatted_address(),
579 "CustomerEmail": self.partner_id.email or "",
580 "CustomerPhone": formatted_phone,
581 "InvType": self.l10n_tw_edi_invoice_type,
582 "TaxType": tax_type,
583 }
584
585 if self.ref:
586 json_data["InvoiceRemark"] = self.ref
587 if special_tax_type:
588 json_data["SpecialTaxType"] = special_tax_type
589
590 self._l10n_tw_edi_prepare_item_list(json_data)
591
592 if self.l10n_tw_edi_is_b2b:
593 json_data["TotalAmount"] = json_data["SalesAmount"] + json_data["TaxAmount"]
594 else:
595 json_data.update({
596 "CustomerName": self.partner_id.name,
597 "Print": "1" if self.l10n_tw_edi_is_print or self.l10n_tw_edi_is_b2b else "0",
598 "Donation": "1" if self.l10n_tw_edi_love_code else "0",
599 "LoveCode": self.l10n_tw_edi_love_code or "",
600 "CarrierType": self.l10n_tw_edi_carrier_type or "",
601 "CarrierNum": self.l10n_tw_edi_carrier_number if self.l10n_tw_edi_carrier_type in ["2", "3", "4", "5"] else "",
602 "CarrierNum2": self.l10n_tw_edi_carrier_number_2 if self.l10n_tw_edi_carrier_type in ["4", "5"] else "",
603 "vat": vat,
604 })
605
606 if is_zero_tax_rate:
607 json_data["ClearanceMark"] = self.l10n_tw_edi_clearance_mark
608 json_data["ZeroTaxRateReason"] = self.l10n_tw_edi_zero_tax_rate_reason
609
610 return json_data
611
612 def _l10n_tw_edi_check_before_generate_issue_allowance_json(self):
613 self.ensure_one()
614 if not self.l10n_tw_edi_ecpay_invoice_id:
615 raise UserError(self.env._(
616 "You cannot issue an allowance for invoice %(invoice_number)s as it was not sent to Ecpay. ",
617 invoice_number=self.name
618 ))
619
620 if (self.l10n_tw_edi_is_b2b or self.l10n_tw_edi_refund_agreement_type == "online") and not self.partner_id.email:
621 raise UserError(self.env._("Customer email is needed for notification"))
622
623 if not self.l10n_tw_edi_is_b2b and \
624 ((self.l10n_tw_edi_allowance_notify_way == "email" and not self.partner_id.email) or (self.l10n_tw_edi_allowance_notify_way == "phone" and not self.partner_id.phone)):
625 raise UserError(self.env._("Customer %(notify_way)s is needed for notification",
626 notify_way=self.l10n_tw_edi_allowance_notify_way))
627
628 def _l10n_tw_edi_generate_issue_allowance_json(self):
629 self.ensure_one()
630 self._l10n_tw_edi_check_before_generate_issue_allowance_json()
631 json_data = {
632 "MerchantID": self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
633 }
634
635 self._l10n_tw_edi_prepare_item_list(json_data, is_allowance=True)
636
637 if not self.l10n_tw_edi_is_b2b:
638 if self.l10n_tw_edi_refund_agreement_type == "online":
639 json_data["ReturnURL"] = urljoin(
640 self.get_base_url(),
641 f"/invoice/ecpay/agreed_invoice_allowance/{self.id}?access_token={self._portal_ensure_token()}")
642 if self.l10n_tw_edi_allowance_notify_way == "email" and self.partner_id.email:
643 json_data["AllowanceNotify"] = "E"
644 json_data["NotifyMail"] = self.partner_id.email
645 elif self.l10n_tw_edi_allowance_notify_way == "phone" and self.partner_id.phone:
646 json_data["AllowanceNotify"] = "S"
647 json_data["NotifyPhone"] = self.partner_id.phone.replace("+", "").replace(" ", "")
648
649 json_data.update({
650 "InvoiceNo": self.l10n_tw_edi_ecpay_invoice_id,
651 "InvoiceDate": convert_utc_time_to_tw_time(self.l10n_tw_edi_invoice_create_date),
652 })
653 else:
654 json_data.update({
655 "CustomerEmail": self.partner_id.email,
656 })
657
658 return json_data
659
660 def _l10n_tw_edi_send_create_buyer(self):
661 """
662 Create a buyer before issuing B2B invoices
663 """
664 buyer_json_data = {
665 "MerchantID": self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
666 "Action": "Add",
667 "Type": "1",
668 "Identifier": self.partner_id.commercial_partner_id.vat,
669 "CompanyName": self.partner_id.commercial_partner_id.name,
670 "TradingSlang": self.partner_id.commercial_partner_id.vat,
671 "ExchangeMode": "0",
672 "EmailAddress": self.partner_id.commercial_partner_id.email,
673 }
674
675 if partner := self.partner_id.commercial_partner_id:
676 buyer_json_data["Address"] = partner._l10n_tw_edi_formatted_address()
677 if number := self.partner_id.commercial_partner_id.phone:
678 buyer_json_data["TelephoneNumber"] = self._reformat_phone_number(number)
679
680 return call_ecpay_api("/MaintainMerchantCustomerData", buyer_json_data, self.company_id,
681 self.l10n_tw_edi_is_b2b)
682
683 def _l10n_tw_edi_send(self, json_content):
684 """
685 Issuing an e-invoice by calling the Ecpay API and update the invoicing result in Odoo
686 """
687 self.ensure_one()
688 # Ensure to lock the records that will be sent, to avoid risking sending them twice.
689 self.env["res.company"]._with_locked_records(self)
690
691 if self.l10n_tw_edi_is_b2b:
692 response_data = self._l10n_tw_edi_send_create_buyer()
693 # 1: New buyer successfully created - can continue with invoicing
694 # 6160052: Buyer already exists - can continue with invoicing
695 # Other codes: Indicate error - don't proceed with invoicing
696 if int(response_data.get("RtnCode")) not in (1, 6160052):
697 return response_data.get("RtnMsg").split("\r\n")
698
699 response_data = call_ecpay_api("/Issue", json_content, self.company_id, self.l10n_tw_edi_is_b2b)
700 if int(response_data.get("RtnCode")) != 1:
701 return response_data.get("RtnMsg").split("\r\n")
702 invoice_number = response_data.get("InvoiceNumber") if self.l10n_tw_edi_is_b2b else response_data.get("InvoiceNo")
703 self.write({
704 "l10n_tw_edi_ecpay_invoice_id": invoice_number,
705 # The date return from Ecpay API used "+" instead of " "
706 "l10n_tw_edi_invoice_create_date": fields.Datetime.now() if self.l10n_tw_edi_is_b2b else transfer_time(
707 response_data.get("InvoiceDate").replace("+", " ")),
708 "l10n_tw_edi_state": "invoiced",
709 })
710 self._message_log(body=self.env._(
711 "The invoice has been successfully sent to Ecpay with Ecpay invoice number %(invoice_number)s.",
712 invoice_number=invoice_number
713 ))
714
715 def _l10n_tw_edi_update_ecpay_invoice_info(self):
716 """
717 Searching the e-invoice information from Ecpay API and update the invoice information in Odoo
718 """
719 self.ensure_one()
720 # Ensure to lock the records that will be sent, to avoid risking sending them twice.
721 self.env["res.company"]._with_locked_records(self)
722
723 if not self.l10n_tw_edi_related_number:
724 raise UserError(self.env._("The invoice: %(invoice_name)s has no related number", invoice_name=self.name))
725
726 json_data = {
727 "MerchantID": self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
728 "RelateNumber": self.l10n_tw_edi_related_number,
729 }
730
731 if self.l10n_tw_edi_is_b2b:
732 json_data.update({
733 "InvoiceCategory": 0,
734 "InvoiceNumber": self.l10n_tw_edi_ecpay_invoice_id,
735 "InvoiceDate": convert_utc_time_to_tw_time(self.l10n_tw_edi_invoice_create_date),
736 })
737
738 response_data = call_ecpay_api("/GetIssue", json_data, self.company_id, self.l10n_tw_edi_is_b2b)
739 if int(response_data.get("RtnCode")) != 1:
740 return response_data.get("RtnMsg").split("\r\n")
741
742 invalid_status = int(response_data.get("RtnData").get("Invalid_Status")) if self.l10n_tw_edi_is_b2b else int(response_data.get("IIS_Invalid_Status"))
743 self.l10n_tw_edi_state = "valid" if invalid_status == 0 else "invalid"
744
745 def _l10n_tw_edi_run_invoice_invalid(self):
746 """
747 Cancelling the e-invoice by calling the Ecpay API and update the invoice information in Odoo
748 """
749 self.ensure_one()
750
751 # Ensure to lock the records that will be sent, to avoid risking sending them twice.
752 self.env["res.company"]._with_locked_records(self)
753
754 if not self.l10n_tw_edi_ecpay_invoice_id:
755 raise UserError(self.env._("You cannot invalidate an invoice that was not sent to Ecpay."))
756 if self.l10n_tw_edi_state == "invalid":
757 raise UserError(self.env._("The invoice: %(invoice_id)s has already been invalidated",
758 invoice_id=self.l10n_tw_edi_ecpay_invoice_id))
759
760 json_data = {
761 "MerchantID": self.company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
762 "InvoiceDate": convert_utc_time_to_tw_time(self.l10n_tw_edi_invoice_create_date),
763 "Reason": self.l10n_tw_edi_invalidate_reason
764 }
765
766 if self.l10n_tw_edi_is_b2b:
767 json_data["InvoiceNumber"] = self.l10n_tw_edi_ecpay_invoice_id
768 else:
769 json_data["InvoiceNo"] = self.l10n_tw_edi_ecpay_invoice_id
770
771 response_data = call_ecpay_api("/Invalid", json_data, self.company_id, self.l10n_tw_edi_is_b2b)
772
773 if int(response_data.get("RtnCode")) != 1:
774 raise UserError(self.env._("Fail to invalidate invoice. Error message: %(error_message)s",
775 error_message=response_data.get("RtnMsg")))
776
777 # update the invoice information in Odoo
778 self._l10n_tw_edi_update_ecpay_invoice_info()
779
780 self._message_log(
781 body=self.env._("Ecpay invoice number %(invoice_number)s has been invalidated successfully.",
782 invoice_number=self.l10n_tw_edi_ecpay_invoice_id),
783 )
784
785 def _l10n_tw_edi_issue_allowance(self, json_content):
786 """
787 Issuing an allowance by calling the Ecpay API and update the refund invoice information in Odoo
788 Two methods to issue the allowance
789 1. Endpoint: /Allowance
790 General allowance, which requires merchants or sellers to get the agreement from the customer first
791 (not by using ECPay system)
792 and then to send an API request to ECPay to issue an allowance.
793 2. Endpoint: /AllowanceByCollegiate
794 Sending an API request to ECPay and ECPay will send an e-mail notification with a link to the customer to
795 get his/her agreement
796 ONce the customer clicks the link, an allowance will be issued instantly
797 """
798 self.ensure_one()
799
800 # Ensure to lock the records that will be sent, to avoid risking sending them twice.
801 self.env["res.company"]._with_locked_records(self)
802
803 query_param = "/AllowanceByCollegiate" if not self.l10n_tw_edi_is_b2b and self.l10n_tw_edi_refund_agreement_type == "online" else "/Allowance"
804
805 response_data = call_ecpay_api(query_param, json_content, self.company_id, self.l10n_tw_edi_is_b2b)
806
807 if int(response_data.get("RtnCode")) != 1:
808 raise UserError(self.env._("Fail to issue allowance for ECpay invoice. Error message: %(error_message)s",
809 error_message=response_data.get("RtnMsg")))
810
811 if self.l10n_tw_edi_is_b2b:
812 self.l10n_tw_edi_refund_invoice_number = response_data.get("AllowanceNo")
813 else:
814 self.write({
815 "l10n_tw_edi_refund_invoice_number": response_data.get("IA_Allow_No"),
816 "l10n_tw_edi_refund_state": "to_be_agreed" if self.l10n_tw_edi_refund_agreement_type == "online" else "agreed",
817 })
818
819 self._message_log(
820 body=self.env._("Ecpay invoice number %(invoice_number)s has been issued allowance successfully.",
821 invoice_number=self.l10n_tw_edi_ecpay_invoice_id),
822 )
823
824 def _l10n_tw_edi_print_invoice(self):
825 self.ensure_one()
826 if self.l10n_tw_edi_state not in ['invoiced', 'valid'] or not self.l10n_tw_edi_ecpay_invoice_id or not (self.l10n_tw_edi_is_print or self.l10n_tw_edi_is_b2b):
827 raise UserError(self.env._(
828 "You cannot print an invoice that was not sent to Ecpay, without the print flag, "
829 "or that is invalid."
830 ))
831 return {
832 "name": self.env._("Print Ecpay Invoice"),
833 "type": "ir.actions.act_window",
834 "view_type": "form",
835 "view_mode": "form",
836 "res_model": "l10n_tw_edi.invoice.print",
837 "target": "new",
838 "context": {
839 "default_invoice_id": self.id,
840 },
841 }