|
| 1 | +import logging |
| 2 | + |
| 3 | +from odoo import SUPERUSER_ID, api |
| 4 | + |
| 5 | +_logger = logging.getLogger(__name__) |
| 6 | + |
| 7 | + |
| 8 | +def migrate(cr, version): |
| 9 | + env = api.Environment(cr, SUPERUSER_ID, {}) |
| 10 | + sol_model = env["sale.order.line"] |
| 11 | + field_definition = env["ir.model.fields"].search( |
| 12 | + [("name", "=", "sale_qty_to_reinvoice"), ("model", "=", "account.move.line")], |
| 13 | + limit=1, |
| 14 | + ) |
| 15 | + if field_definition: |
| 16 | + reference_date = field_definition.create_date or field_definition.write_date |
| 17 | + env.cr.execute( |
| 18 | + """ |
| 19 | + update account_move_line set sale_qty_to_reinvoice = True |
| 20 | + where create_date <= %s and |
| 21 | + (sale_qty_to_reinvoice = False or sale_qty_to_reinvoice is null) |
| 22 | + """, |
| 23 | + (reference_date,), |
| 24 | + ) |
| 25 | + env.cr.commit() |
| 26 | + query = """ |
| 27 | + with invoice_lines as ( |
| 28 | + select rel.order_line_id, sum(coalesce(aml.quantity, 0)) as quantity |
| 29 | + from account_move_line as aml |
| 30 | + inner join account_move as am on am.id = aml.move_id |
| 31 | + inner join sale_order_line_invoice_rel as rel on rel.invoice_line_id = aml.id |
| 32 | + where am.state = 'posted' and am.move_type = 'out_invoice' |
| 33 | + group by rel.order_line_id |
| 34 | + ), credit_lines as ( |
| 35 | + select rel.order_line_id, sum(coalesce(aml.quantity, 0)) as quantity |
| 36 | + from account_move_line as aml |
| 37 | + inner join account_move as am on am.id = aml.move_id |
| 38 | + inner join sale_order_line_invoice_rel as rel on rel.invoice_line_id = aml.id |
| 39 | + where am.state = 'posted' and am.move_type = 'out_refund' |
| 40 | + and aml.sale_qty_to_reinvoice = true |
| 41 | + group by rel.order_line_id |
| 42 | + ) |
| 43 | + select |
| 44 | + sol.id |
| 45 | + from sale_order_line as sol |
| 46 | + inner join sale_order as so on so.id = sol.order_id and so.state in ('sale', 'done') |
| 47 | + left join invoice_lines as il on sol.id = il.order_line_id |
| 48 | + left join credit_lines as cl on sol.id = cl.order_line_id |
| 49 | + where (coalesce(il.quantity, 0) - coalesce(cl.quantity, 0)) != sol.qty_invoiced |
| 50 | + and (sol.create_date >= %s or sol.write_date >= %s) |
| 51 | +
|
| 52 | + """ |
| 53 | + env.cr.execute(query, (reference_date, reference_date)) |
| 54 | + lines_with_problems = [data[0] for data in env.cr.fetchall()] |
| 55 | + if lines_with_problems: |
| 56 | + sol_lines = sol_model.search( |
| 57 | + [ |
| 58 | + ("id", "in", lines_with_problems), |
| 59 | + ("product_id.type", "!=", "service"), |
| 60 | + ] |
| 61 | + ) |
| 62 | + _logger.debug("total lines to reprocess: %s", str(len(sol_lines))) |
| 63 | + sol_lines._get_invoice_qty() |
0 commit comments