Hi, try asking ChatGPT. It answered me this, maybe it helps:
You want to automate the creation of a sequence number for an approval.request record. The main goal is to get the last sequence number used and increment it by one.
Here is a refined version of your code. This should work within an Automation Rule in Odoo. The code will search for the last sequence, increment it, and then set it for the new record.
if record.request_status == 'new':
# Search for the last record with similar x_field1-x_field2 combination
last_record = record.env['approval.request'].search(
[('name', 'ilike', record.x_field1 + '-' + record.x_field2 + '-%')],
order="name desc",
limit=1
)
if last_record:
# Extract the number part from the last record's name
last_number_str = last_record.name.split('-')[-1]
last_number = int(last_number_str)
next_number = str(last_number + 1).zfill(5)
else:
next_number = '00001'
# Create the new sequence name
seq = f"{record.x_field1}-{record.x_field2}-{next_number}"
record.write({'name': seq})
Explanation:
- Condition Check: The code first checks if the `request_status` of the record is 'new'.
- Search for Last Record: It searches for the last record with a similar `x_field1-x_field2` combination using the `ilike` operator to perform a case-insensitive search. The search is ordered by the `name` field in descending order to get the latest one.
- Extract and Increment: If a last record is found, it extracts the numerical part from the `name`, converts it to an integer, increments it by one, and then pads it with leading zeros to maintain the format.
- Create New Sequence: If no last record is found, it starts with '00001'. The new sequence is then formatted and written back to the record.
This code assumes that the `name` field always follows the pattern `x_field1-x_field2-00090`. Adjust the padding length (`zfill(5)`) according to the required format.
Shorter:
if record.request_status == 'new':
last_record = record.env['approval.request'].search(
[('name', 'ilike', record.x_field1 + '-' + record.x_field2 + '-%')],
order="name desc", limit=1
)
next_number = str(int(last_record.name.split('-')[-1]) + 1).zfill(5) if last_record else '00001'
record.write({'name': f"{record.x_field1}-{record.x_field2}-{next_number}"})
This version does the same thing but in fewer lines:
- Condition Check: Checks if the request_status is 'new'.
- Search for Last Record: Searches for the last record with the matching pattern.
- Extract, Increment, and Format: If a last record is found, it extracts, increments, and formats the number. If not, it defaults to '00001'.
- Write New Sequence: Writes the new sequence back to the name field.
Make sure to test this thoroughly in a development environment before deploying it in production.