how to validate NZBN code number of NewZealand? - stripe-payments

I am working on app needs an NZBN Code to register with stripe payments, when a user can enter any NZBN that cause Stripe issues,
i entered the https://api.business.govt.nz/services/v4/nzbn to check it but no obivious api call contain the real check of the NZBN code .
is there any way please ?
EDIT:
i am passing the NZBN number as tax_id to Stripe so Stripe check it with what ever api and tell me that the tax_id is not a valid nzbn , but when i put a valid nzbn it takes it correclty how to prevent entering a not valid NZBN before going to stripe

This is a really old question but it has no answer, so I thought I'd share;
NZBN (different from the NZ GST number) is a plain old GTIN 13. This is my TypeScript for checking for 1) a valid GTIN, and then 2) a GTIN13 specifically
/**
* Boolean function to test code against GTIN published checksum method(s)
*/
export function isGTIN(text: number | string): boolean {
try {
const r = /[\D]/g,
gtin = typeof text === "number" ? text.toString().replace(r, "") : text.replace(r, ""),
paddedValue = gtin.padStart(14, "0")
if (!gtin.match(/^(\d{8}|\d{12,14})$/)) return false
let result = 0
for (let i = 0; i < paddedValue.length - 1; i += 1) {
result += parseInt(paddedValue.charAt(i), 10) * (i % 2 === 0 ? 3 : 1)
}
return (10 - (result % 10)) % 10 === parseInt(paddedValue.charAt(13), 10)
} catch (err) {
console.error(err.message)
return false
}
}
/**
* Boolean function to test NZBN (GTIN13) against published checksum method
*/
export function isNZBN(text: number | string): boolean {
try {
const r = /[\D]/g,
gtin = typeof text === "number" ? text.toString().replace(r, "") : text.replace(r, "")
// NZBN is a GTIN 13
if (gtin.length !== 13) return false
else return isGTIN(gtin)
} catch (err) {
console.error(err.message)
return false
}
}

While you could rely on validation error instead of implementing this yourself, you can also optionally pre-validate the input. This is really up to you.
Validation follows the OECD TIN specifications, such as for NZ IRDs, which looks to be 8 or 9 numeric digits. If the NZBN has a different spec than this, you'd need to implement a validation check before submitting.

Related

Laravel Maatwebsite Excel - All zero values being populated by map() function using fromArray() concern

I am trying to make an excel export using Maatwebsite Excel. This is my second export file and first one is working perfect. When I var_dump() data is okay using postman but the rendered excel has all cells populated with 0s.
class SummaryExport implements FromArray, WithMapping, WithEvents, WithHeadings, WithStyles, WithCustomStartCell, WithStrictNullComparison, ShouldAutoSize
{
use RegistersEventListeners;
private $from_date, $to_date, $fee_type;
public function __construct($from_date, $to_date, $fee_type)
{
$this->from_date = $from_date;
$this->to_date = $to_date;
$this->fee_type = $fee_type;
}
/**
* #return array
*/
public function array(): array
{
$school_id = auth()->user()->school_id;
if($this->fee_type == "all"){
$fee_vouchers = FeeVoucher::where('school_id', $school_id)->where('issue_date','>=',$this->from_date)
->where('issue_date','<=',$this->to_date)->get();
}else{
$fee_vouchers = FeeVoucher::where('school_id', $school_id)->where('issue_date','>=',$this->from_date)
->where('issue_date','<=',$this->to_date)
->where('type', $this->fee_type)->get();
}
$gross = 0;
$concession = 0;
$fines=0;
$net=0;
$received=0;
$percentage=0;
$balance = 0;
$fee_summary = array();
foreach($fee_vouchers as $vchr){
$gross = $gross + $vchr->total_amount + $vchr->fines->sum('amount');
$concession = $concession + $vchr->concessions->sum('applied');
$fines = $fines + $vchr->fines->sum('amount');
if($vchr->is_paid == 1){
$received = $received + $vchr->total_amount + $vchr->fines->sum('amount');
}
}
$net = $gross - $concession;
$balance = $net - $received;
$fee_summary[]= array(
'gross' => intval($gross),
'concession' =>intval($concession),
'fines' => intval($fines),
'net' => intval($net),
'received' => intval($received),
'percentage' => intval($percentage),
'balance' => intval($balance)
);
//var_dump($fee_summary); //values are displayed correct here as well
return $fee_summary;
}
public function map($row): array
{
// When I do var_dump($row) here in post man I can see data but in Excel data is not written but all zeros
return [
$row['gross'],
$row['concession'],
$row['fines'],
$row['net'],
$row['received'],
$row['percentage'],
$row['balance']
//[15023,456,785,4567,865,952,0] // when I give static values the problem is fixed and all values are written in Excel
];
}
}
The weird thing is when I give the fixed static values it gives me proper results. On using var_dump it also shows that data is accurately created. But I am stuck from last night what is causing this problem.
I know this is quite old now, but the intval method will return zero on an unprocessable/incorrect value. As mentioned in the docs here, The integer value of value on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.
echo intval(true) // 1
echo intval(false) // 0
echo intval("'12'") // 0, within the quotes the value is a string still
echo intval("12") // 12
echo intval(5.25) // 5
echo intval('$400') // 0
Without seeing the input data I assume that the values being passed into the intval method on return, aren't valid types. Are there symbols (i.e. $, other currency symbols) within the values?

Why is This string not changing or staying a number?

I must be tired because this is making no sense..
// get user input, if they enter a string,
// set result to 0 and return.
function evalInput(_input) {
// set result default to 0, a number
var result = 0;
// make sure _input is a number
if (typeof(parseInt(_input)) === 'number') {
// It is indeed a number
if (_input == 3) {
launchHelp("./Help.txt");
}
result = _input;
} else { // user entered a string
// make sure its a number!!!
// was already 0, but just to make sure its assigned a number
result = 0;
// surely itll be a number now
result = parseInt(result);
}
// says its a number..
prompt("typeof(typeof(parseInt(result))) = " + typeof(parseInt(result)));
// now its a string again?
prompt("typeof(result) = " + typeof(result));
return result;
}
output:
Choice: d
typeof(typeof(parseInt(result))) = number
typeof(result) = string
I simply need result to be a type number.
i even tried assigning another variable 0 and then assigning result again. Ive tried all this and more without parseInt(). I used it to make sure the string was changed to a number.
var number = 0;
result = number;
My main issue is when you parseInt("0") it should cast 0, not "0" . this is what is happening
Your check to validate if a string is a valid number is all wrong. It will always evaluate to true and your else block will never be reached.
// make sure _input is a number => wrong!
if (typeof(parseInt(_input)) === 'number') { .. }
This will always assert to true because when you parse something to int that is not a valid integer, you get NaN aka Not a Number. typeof(NaN) however, even thoug not a valid number, is still a number!
If you want to check if something is a valid integer, you need to use Number.isInteger().
console.log(typeof(NaN)); // number
console.log(typeof(parseInt("Bogus")) === 'number'); // true
console.log(Number.isInteger("Bogus")); // false
console.log(Number.isNaN(parseInt("Bogus"))); // true

Access #sys.age from fulfillment DialogFlow

I have defined a parameter named age of the type #sys.age
When trying to access it through fulfillment, its showing no output in the first line and falls into the else clause.
function EntryPointHandler(agent) {
const number = agent.parameters.age;
agent.add(`inside fulfilment1`+ number);
if(number < 18 )
{
agent.add(`Sorry, we dont have products for under ages under 18`);
}
else {
agent.add(`Thank you, do you have an ID`);
}
}
To access age value, you should use the following,
const age = agent.parameters.age.amount;

Handsontable numeric cell globalization

I'm relatively new to js and now have to implement a handsontable into our project.
This worked well so far, but I am hitting a roadblock with globalization.
Basically, we use comma as a decimal seperator, but when I try and copy something like "100,2" into a cell designated as 'numeric,' it will show as 1002.
If the same value is entered in a cell designated as 'text' and the type is changed to numeric afterwards, the value will be shown correctly.
For this I already had to add 'de' culture to the table sourcecode.(basically copying 'en' and changing the values currently relevant to me.)
numeral.language('de', {
delimiters: {
thousands: '.',
decimal: ','
},//other non-relevant stuff here
When I copy the values directly from the table and insert them to np++ they show as 100.2 etc. However, when inserting them into handsontable the arguments-array looks as follows:
[Array[1], "paste", undefined, undefined, undefined, undefined]
0: Array[4]
0: 1 //row
1: 1 //column
2: "100.2" //previous value
3: 1002 //new value
Here's what I have tried currently:
hot.addHook("beforeChange", function () {
if (arguments[1] === "paste") {
hot.updateSettings({
cells: function (row, col, prop) {
var cellProperties = {
type: 'numeric',
language: 'en'
};
return cellProperties;
}
});
//hot.updateSettings({
// cells: function (row, col, prop) {
// var cellProperties = {
// type: 'text',
// };
// return cellProperties;
// }
//});
}
}, hot);
hot.addHook("afterChange", function () {
if (arguments[1] === "paste") {
ChangeMatrixSettings(); //reset cell properties of whole table
}
}, hot);
I hope I've made my problem clear enough, not sure if I missed something.
Are there any other ways to get the correct values back into the table? Is this currently not possible?
Thanks in advance.
You asked more than one thing, but let me see if I can help you.
As explained in handsontable numeric documentation, you can define a format of the cell. If you want '100,2' to be shown you would format as follows
format: '0.,'
You can change that to what you really need, like if you are looking for money value you could do something like
format: '0,0.00 $'
The other thing you asked about is not on the latest release, but you can check it out how it would work here
I have since implemented my own validation of input, due to other requirements we have for the table mainly in regards to showing invalid input to user.
function validateInputForNumeric(parameter) {
var value = parameter[3];
var row = parameter[0];
var col = parameter[1];
if (decimalSeperator === '') {
var tmpculture = getCurrCulture();
}
if (value !== null && value !== "") {
if (!value.match('([a-zA-Z])')) {
if (value.indexOf(thousandSeperator) !== -1) {
value = removeAndReplaceLast(value, thousandSeperator, ''); //Thousandseperators will be ignored
}
if (value.indexOf('.') !== -1 && decimalSeperator !== '.') {
//Since numeric variables are handled as '12.3' this will customize the variables to fit with the current culture
value = removeAndReplaceLast(value, '.', decimalSeperator);
}
//Add decimalseperator if string does not contain one
if (numDecimalPlaces > 0 && value.indexOf(decimalSeperator) === -1) {
value += decimalSeperator;
}
var index = value.indexOf(decimalSeperator)
var zerosToAdd = numDecimalPlaces - (value.length - index - 1);
for (var j = 0; j < zerosToAdd; j++) {
//Add zeros until numberOfDecimalPlaces is matched for uniformity in display values
value += '0';
}
if (index !== -1) {
if (numDecimalPlaces === 0) {
//Remove decimalseperator when there are no decimal places
value = value.substring(0, index)
} else {
//Cut values that have to many decimalplaces
value = value.substring(0, index + 1 + numDecimalPlaces);
}
}
if (ErrorsInTable.indexOf([row, col]) !== -1) {
RemoveCellFromErrorList(row, col);
}
} else {
AddCellToErrorList(row, col);
}
}
//console.log("r:" + row + " c:" + col + " v:" + value);
return value;
}
The inputParameter is an array, due to handsontable hooks using arrays for edit-events. parameter[2] is the old value, should this be needed at any point.
This code works reasonably fast even when copying 2k records from Excel (2s-4s).
One of my main hindrances regarding execution speed was me using the handsontable .getDataAtCell and .setDataAtCell methods to check. These don't seem to handle large tables very well ( not a critique, just an observation ). This was fixed by iterating through the data via .getData method.

How i can get latest record by using FirstOrDefault() method

Suppose i have 2 records in data base
1) 2007-12-10 10:35:31.000
2) 2008-12-10 10:35:31.000
FirstOrDefault() method will give me the first record match in sequence like 2007-12-10 10:35:31.000 but i need the latest one which is 2008-12-10 10:35:31.000
if ((from value in _names where value != null select value.ExpiryDate < now).Any())
{
return _names.FirstOrDefault();
}
You can use:
return _names.LastOrDefault();
However, your if just sends another unnecessary query (and it is a wrong query too). If you don't have any record, LastOrDefault and FirstOrDefault will return null. You can use something like this to improve the code:
var name = _names.LastOrDefault();
if(name != null)
{
return name;
}
// other code here
If you really want to use FirstOrDefault, you should order descending, like:
var name = _names.Where(n => n.ExpiryDate < now).OrderByDescending(n => n.ExpiryDate).FirstOrDefault();

Resources