I'm trying to update the 'sequence' value in model 'product.supplierinfo' with an Automated Action, so that when the supplier's price are updated from a purchase order, that supplier is prioritized to calculate the replenishment cost. To achieve that, the new/updated record must get the lowest 'sequence' value for that product.
Automated Action Settings: Model: product.supplierinfo Action: Execute Python code Condition: Create and update
This part of the py resets the sequences starting from 2 successfully:
val = 1
registers = model.search([('product_tmpl_id','=',record.product_tmpl_id.id)], order = "sequence asc")
for reg in registers:
val = val + 1
reg['sequence'] = val
And this other one gives the updated/new line the sequence value 1 successfully:
record.write({'sequence': 1})
However, when put all together, all the lines get sequence 1:
val = 1
registers = model.search([('product_tmpl_id','=',record.product_tmpl_id.id)], order = "sequence asc")
for reg in registers:
val = val + 1
reg['sequence'] = val
record.write({'sequence': 1})
As I'm pretty noob, I even assumed that maybe the loop wouldn't end with the indent and tried this other one to proof I'm missing something (first setting sequence 1 to the aimed record and then dropping that record from the search method). It still gets 1 on all the register's sequence value:
record.write({'sequence': 1})
val = 1
registers = model.search([('product_tmpl_id','=',record.product_tmpl_id.id),('id','!=', record.id)], order = "sequence asc")
for reg in registers:
val = val + 1
reg['sequence'] = val
Any idea why it doesn't set the trigger record's sequence 1 and then the rest from 2 and on?
With the help of @CZoellner we found that my code was creating a loop running through all the records, when editing the sequence value it would trigger the Automated Action again. For some reason it wouldn't throw an error of infinite loop.
However, the solution that did the trick was checking the maximum write.date
of the group of records to verify if the Automated action had already gone through it.
The final working code is:
val = 1
fmt = '%Y-%m-%d %H:%M:%S'
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
d2 = datetime.datetime.strptime(now, fmt)
registers = env['product.supplierinfo'].search([('product_tmpl_id','=',record.product_tmpl_id.id),('id','!=', record.id)], order = "sequence asc")
maxi = max(reg.write_date for reg in registers)
d1 = datetime.datetime.strptime(maxi, fmt)
diff = (d2-d1).seconds
if diff > 1:
for reg in registers:
val = val + 1
reg['sequence'] = val
record.write({'sequence': 1})
Thanks to @CZoellner for collaborating