Some background: In Germany (at least) invoice numbers have to follow certain rules:
- The have to be ordered
- They have to be continuous (may not have gaps)
Since a few months they are allowed to contain characters. Some customers want to use that possibility and customers don’t know that or are afraid and they insist on digit-only invoice numbers.
Additionally the customers don’t want to start them at zero.
Is I can think of many ways to generate such a number I wonder: What’s the best way to do this?
In order to avoid starting at 0 – just start at 10000. Forget about the zero-padding.
You have to consider when the number is going to be allocated.
If you allocate the number when the invoice is first opened for edit, for instance the number 10014 is allocated, and the user cancels the invoice then you have a gap, since you have to keep in mind that someone else could already have begun to create an invoice with the id 10015, so you can’t just rollback the number.
If you allocate the number when the invoice has been completely written and is being saved then you’ll avoid the scenario, and you’ll avoid having gaps, but you will not know which invoice number the invoice is going to have before it is saved.
Also, you need to make sure that it is threadsafe, so that two users can’t create the same invoice number.
Also consider backing up the uniqueness by having a UNIQUE INDEX on the invoicenumber column in the SQL database.