Created
February 14, 2024 14:12
-
-
Save iampato/6f804f66bf7c4fa1cc2c6070e806d78d to your computer and use it in GitHub Desktop.
Function to generate code similar to MPESA transaction codes e.g RCE7QMM2G9, SAO9X7099B
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generate voucher number | |
// using mpesa transaction reference format -> YYMMDDHHmmssNNNN | |
export function generateVoucherNumber(): string { | |
const now = new Date(); | |
const yearMap = { | |
'20': 'A', | |
'21': 'B', | |
'22': 'C', | |
'23': 'D', | |
'24': 'E', | |
'25': 'F', | |
'26': 'G', | |
'27': 'H', | |
'28': 'I', | |
'29': 'J', | |
'30': 'K', | |
// Add more mappings as needed | |
}; | |
const monthMap = { | |
'01': 'A', | |
'02': 'B', | |
'03': 'C', | |
'04': 'D', | |
'05': 'E', | |
'06': 'F', | |
'07': 'G', | |
'08': 'H', | |
'09': 'I', | |
'10': 'J', | |
'11': 'K', | |
'12': 'L', | |
}; | |
const dayMap = { | |
'01': 'A', | |
'02': 'B', | |
'03': 'C', | |
'04': 'D', | |
'05': 'E', | |
'06': 'F', | |
'07': 'G', | |
'08': 'H', | |
'09': 'I', | |
'10': 'J', | |
'11': 'K', | |
'12': 'L', | |
'13': 'M', | |
'14': 'N', | |
'15': 'O', | |
'16': 'P', | |
'17': 'Q', | |
'18': 'R', | |
'19': 'S', | |
'20': 'T', | |
'21': 'U', | |
'22': 'V', | |
'23': 'W', | |
'24': 'X', | |
'25': 'Y', | |
'26': 'Z', | |
'27': 'a', | |
'28': 'b', | |
'29': 'c', | |
'30': 'd', | |
'31': 'e', | |
}; | |
const hourMap = { | |
'00': 'A', | |
'01': 'B', | |
'02': 'C', | |
'03': 'D', | |
'04': 'E', | |
'05': 'F', | |
'06': 'G', | |
'07': 'H', | |
'08': 'I', | |
'09': 'J', | |
'10': 'K', | |
'11': 'L', | |
'12': 'M', | |
'13': 'N', | |
'14': 'O', | |
'15': 'P', | |
'16': 'Q', | |
'17': 'R', | |
'18': 'S', | |
'19': 'T', | |
'20': 'U', | |
'21': 'V', | |
'22': 'W', | |
'23': 'X', | |
}; | |
const year = now.getFullYear().toString().slice(-2); | |
const month = String(now.getMonth() + 1).padStart(2, '0'); | |
const day = String(now.getDate()).padStart(2, '0'); | |
const hour = String(now.getHours()).padStart(2, '0'); | |
const minute = String(now.getSeconds()).padStart(2, '0'); | |
const randomNum = Math.floor(1000 + Math.random() * 9000); | |
const yearLetter = yearMap[year] || year; | |
const monthLetter = monthMap[month] || month; | |
const dayLetter = dayMap[day] || day; | |
const hourLetter = hourMap[hour] || hour; | |
const transactionRef = `${yearLetter}${monthLetter}${dayLetter}${hourLetter}${minute}${randomNum}`; | |
return transactionRef.toUpperCase(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment