Wednesday, June 3, 2015

Generating meaningful invoice numbers

Problem

You want to generate invoice numbers for a customer.

General Approach

Commonly, a global or customer-specific integer counter is maintained for generating invoice numbers. The next number in the counter sequence is used as the invoice number when generating a new invoice.

A Different Approach

We can add more meaning to the invoice number generated for a customer. Here's one such approach that contains the customer identifier and the time an invoice was generated. The invoices numbers increase over time and hence can be sorted in ascending order.

public static String TimeBasedIdentifier(this string customerId)
{
  var now = DateTime.UtcNow;
  string dateStamp = now.ToString("yyMMdd");
  long elapsedSecondsToday = (long)(now - now.Date).TotalSeconds;
  return String.Format("{0}-{1}-{2}",
     customerId, dateStamp, elapsedSecondsToday.ToString("D5"));
}

Sample Output for customer 10000:
10000-20150603-68650

Limitation

This approach generates unique invoice numbers for a given customer as long as we do not generate more than one invoice per second for a given customer. We can use TotalMilliseconds (instead of TotalSeconds) if we want higher precision.