You are on page 1of 30

var taxItemSegmentExtIdPrefix = 'TAXITEM_';

var actuallyCreateGlLine = true;


//var taxCodeCustomSegmentId = 'cseg_delse_pro_rate';
var taxCodeCustomSegmentId = 'cseg_del_prorate_gl';
var folderIdForLogs = -15;
var debitTransactions = ["vendorbill", "expensereport"];
function customizeGlImpact(transactionRecord, standardLines, customLines, book) {

//var supportedCustomSegments = ['department', 'class', 'location'];


var userId = nlapiGetContext().getUser();
var recType = transactionRecord.getRecordType();
var recId = transactionRecord.getId();
var bookId = book.getId();

var keyLog = ' userId: ' + userId + ' recType: ' + recType + ' recId: ' + recId
+ ' bookId: ' + bookId;

try {
var subsidiary = transactionRecord.getFieldValue('subsidiary');
var trandate_str = transactionRecord.getFieldValue('trandate');

nlapiLogExecution('AUDIT', 'customizeGlImpact core ' + keyLog, 'subsidiary:


' + subsidiary + ' trandate_str: ' + trandate_str);

if (trandate_str){
if (subsidiary){
var trandateYear_N =
parseInt(nlapiStringToDate(trandate_str).getFullYear(),10);

var subsidiaryConfigForTheYear = getConfig(subsidiary,


trandateYear_N);
var supportedCustomSegments =
subsidiaryConfigForTheYear.configSupportedSegments;

nlapiLogExecution('DEBUG', 'customizeGlImpact core ' + keyLog,


'subsidiaryConfigForTheYear: ' + JSON.stringify(subsidiaryConfigForTheYear));

if(subsidiaryConfigForTheYear){
var isRCHSupplementaryTaxCalculation = false;

var GLLines = {};


GLLines.allGLLines = [];
GLLines.excludedGLLines = [];
GLLines.VATGLLines = {};
GLLines.baseGLLines = {};
GLLines.standardTaxCodesMap = {};
GLLines.rchTaxCodesMap = {};
GLLines.supplementaryTaxCalculationGLLines = [];
GLLines.VATGLLines.revCH = [];
GLLines.VATGLLines.standard = [];
GLLines.baseGLLines.revCH = [];
GLLines.baseGLLines.standard = [];
GLLines.transactionInfo = {};
GLLines.isRCHSupplementaryTaxCalculation = false;

if (book.isPrimary()){

GLLines.transactionInfo = {
userId: userId,
recType: recType,
recId: recId,
bookId: bookId
};

if (recId){
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' +
keyLog, 'getting additional rch lines for transaction: ' + recId);

GLLines.supplementaryTaxCalculationGLLines =
getSupplementaryTaxLines(recId, recType, supportedCustomSegments);
if (GLLines.supplementaryTaxCalculationGLLines.length >
0){
isRCHSupplementaryTaxCalculation = true;
GLLines.isRCHSupplementaryTaxCalculation =
isRCHSupplementaryTaxCalculation;
}

//_CreateJSONFile('SupplementaryTaxLines' + recId,
GLLines.supplementaryTaxCalculationGLLines, folderIdForLogs);
var SupplementaryTaxLines_GrpByTaxCodeId = {};

for (var iCountSupplementaryLines = 0;


iCountSupplementaryLines < GLLines.supplementaryTaxCalculationGLLines.length;
iCountSupplementaryLines++) {
var supplementaryTaxLine =
GLLines.supplementaryTaxCalculationGLLines[iCountSupplementaryLines];

var UniqueSupplementaryLineKey =
taxItemSegmentExtIdPrefix + '' + supplementaryTaxLine.taxItemId;

if (typeof
SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey] == 'undefined'){

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey] = {};

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey].lines = [];

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey].totalVat = 0;

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey].vatAccount =
supplementaryTaxLine.accountId;
}

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey].lines.push(JSON.pa
rse(JSON.stringify(supplementaryTaxLine)));

SupplementaryTaxLines_GrpByTaxCodeId[UniqueSupplementaryLineKey].totalVat
+=supplementaryTaxLine.taxAmount;
}

//_CreateJSONFile('SupplementaryTaxLines_GrpByTaxCodeId' + recId,
SupplementaryTaxLines_GrpByTaxCodeId, folderIdForLogs);

var standardLinesCount = standardLines.getCount();

var atLeast1LineIsSubJectedToProRate = false;


for (var iCountStandardGLLines = 0;
iCountStandardGLLines < standardLinesCount; iCountStandardGLLines++) {

var currentStandardGLLine =
standardLines.getLine(iCountStandardGLLines);
var mappedGlLine =
_mapGlLine(currentStandardGLLine, iCountStandardGLLines,supportedCustomSegments,
isRCHSupplementaryTaxCalculation, GLLines.supplementaryTaxCalculationGLLines,
recType, subsidiaryConfigForTheYear);
//nlapiLogExecution('AUDIT', 'customizeGlImpact
core ' + keyLog, 'mappedGlLine: ' + JSON.stringify(mappedGlLine));

if (mappedGlLine.lineIsEnabledForCalculation){
atLeast1LineIsSubJectedToProRate = true;

if (mappedGlLine.taxType == 'VAT'){
if
(mappedGlLine.taxItemFoundInCustomGLLines){

GLLines.VATGLLines.revCH.push(mappedGlLine)
} else {

GLLines.VATGLLines.standard.push(mappedGlLine)
}
} else {
if
(mappedGlLine.taxItemFoundInCustomGLLines){

GLLines.baseGLLines.revCH.push(mappedGlLine)
} else {

GLLines.baseGLLines.standard.push(mappedGlLine)
}
}

GLLines.allGLLines.push(mappedGlLine);
} else {
GLLines.excludedGLLines.push(mappedGlLine)
}
}

if (atLeast1LineIsSubJectedToProRate){
nlapiLogExecution('AUDIT', 'customizeGlImpact core
' + keyLog, 'At least 1 line is enabled for calculation: ' + recId);

GLLines.standardVATLinesMap = {};
for (var iCountVATStandardGlLines = 0;
iCountVATStandardGlLines < GLLines.VATGLLines.standard.length;
iCountVATStandardGlLines++){
var currentVatStandardGlLine =
GLLines.VATGLLines.standard[iCountVATStandardGlLines];
var TaxCodeId =
currentVatStandardGlLine.taxItemId;
var taxCodeKey = taxItemSegmentExtIdPrefix + ''
+ TaxCodeId;

if (typeof
GLLines.standardVATLinesMap[taxCodeKey] == 'undefined'){
GLLines.standardVATLinesMap[taxCodeKey] =
{};
GLLines.standardVATLinesMap[taxCodeKey].taxAmount = 0;

GLLines.standardVATLinesMap[taxCodeKey].vatAccount =
currentVatStandardGlLine.ACC_accountId;
}

if ((debitTransactions.indexOf(recType) >= 0))


{
var taxAmountN =
parseFloat(currentVatStandardGlLine.debitAmount);
} else {
var taxAmountN =
(parseFloat(currentVatStandardGlLine.creditAmount)*-1);
}

//Update 21.03.2022 - removed due to bug by


Andrea
//var taxAmountN =
parseFloat(currentVatStandardGlLine.taxAmount);

GLLines.standardVATLinesMap[taxCodeKey].taxAmount += taxAmountN;
}

GLLines.RCHVATLinesMap = {};
for (var iCountVATStandardGlLines = 0;
iCountVATStandardGlLines < GLLines.VATGLLines.revCH.length;
iCountVATStandardGlLines++){
var currentVatRCHGlLine =
GLLines.VATGLLines.revCH[iCountVATStandardGlLines];
var TaxCodeId = currentVatRCHGlLine.taxItemId;
var taxCodeKey = taxItemSegmentExtIdPrefix + ''
+ TaxCodeId;

if (typeof GLLines.RCHVATLinesMap[taxCodeKey]
== 'undefined'){
GLLines.RCHVATLinesMap[taxCodeKey] = {};

GLLines.RCHVATLinesMap[taxCodeKey].taxAmount = 0;
}

var taxAmountN =
parseFloat(currentVatRCHGlLine.taxAmount);
GLLines.RCHVATLinesMap[taxCodeKey].taxAmount +=
taxAmountN;
}

// UNDERSTAND HOW MUCH THE standard line amount is


compared to the total for the tax code
var currentBaseGLLine = null;
GLLines.allStandardTaxCodes = [];
for (var iCountBaseStandardGLLines = 0;
iCountBaseStandardGLLines < GLLines.baseGLLines.standard.length;
iCountBaseStandardGLLines++) {
currentBaseGLLine =
GLLines.baseGLLines.standard[iCountBaseStandardGLLines];

//GLLines.JELines.revCH.standardTaxCodesMap =
{};
var taxCodeKey = taxItemSegmentExtIdPrefix + ''
+ currentBaseGLLine.taxItemId;

//nlapiLogExecution('AUDIT', 'customizeGlImpact
core ' + keyLog, 'taxCodeKey: ' + taxCodeKey);

if (typeof
GLLines.standardTaxCodesMap[taxCodeKey] == 'undefined'){

GLLines.allStandardTaxCodes.push(currentBaseGLLine.taxItemId);
GLLines.standardTaxCodesMap[taxCodeKey] =
{};

GLLines.standardTaxCodesMap[taxCodeKey].total = 0;

GLLines.standardTaxCodesMap[taxCodeKey].PRVAT_TaxCodeName =
currentBaseGLLine.PRVAT_TaxCodeName;

GLLines.standardTaxCodesMap[taxCodeKey].recType = recType;

GLLines.standardTaxCodesMap[taxCodeKey].taxItemId = currentBaseGLLine.taxItemId;

GLLines.standardTaxCodesMap[taxCodeKey].lines = [];
}

var conditionalBaseAmount = 0;

if ((debitTransactions.indexOf(recType) >= 0))


{
conditionalBaseAmount =
currentBaseGLLine.debitAmount;
} else {
conditionalBaseAmount =
currentBaseGLLine.creditAmount;
}

GLLines.standardTaxCodesMap[taxCodeKey].total
+= conditionalBaseAmount;

GLLines.standardTaxCodesMap[taxCodeKey].lines.push({
isRch: false,
recType: recType,
originalExpenseAccount:
currentBaseGLLine.ACC_accountId,
CustomSegmentsValues:
currentBaseGLLine.CustomSegmentsValues,
baseAmount: conditionalBaseAmount,
nonDeductiblePercentage:
currentBaseGLLine.PRVAT_nonDeductiblePercentage,
});
}

if (GLLines.allStandardTaxCodes.length > 0){


GLLines.TaxCodeRates =
getTaxCodeRate(GLLines.allStandardTaxCodes);
}
for (var taxCodeKey in GLLines.standardTaxCodesMap)
{
var taxCode =
GLLines.standardTaxCodesMap[taxCodeKey];
var taxCodeRate =
GLLines.TaxCodeRates[taxCodeKey];

if((debitTransactions.indexOf(recType) >= 0)){


taxCode.RealTotalVAT =
GLLines.standardVATLinesMap[taxCodeKey].taxAmount;
} else {
taxCode.RealTotalVAT =
GLLines.standardVATLinesMap[taxCodeKey].taxAmount * -1;
}

taxCode.TotalVATToPostAsCost = 0;
var currentTotalVAT = 0;

for (var iCountTaxCodeLines = 0;


iCountTaxCodeLines < taxCode.lines.length;iCountTaxCodeLines++){
var taxCodeLine =
taxCode.lines[iCountTaxCodeLines];
taxCodeLine.ratioTotalVSCurrent =
taxCode.total / taxCodeLine.baseAmount;
taxCodeLine.weigthPercentageMaxPrecision =
100 / taxCodeLine.ratioTotalVSCurrent;
taxCodeLine.taxCodeRate = taxCodeRate;
taxCodeLine.vatAccount =
GLLines.standardVATLinesMap[taxCodeKey].vatAccount;

// if its the last calculation then we


subtract instead of calculating it
if (iCountTaxCodeLines ==
taxCode.lines.length-1){
taxCodeLine.reproportionedVATAmount =
taxCode.RealTotalVAT - currentTotalVAT;
} else {
// calculatedVATAmount :
weigthPercentageMaxPrecision = RealTotalVAT : 100
taxCodeLine.reproportionedVATAmount =
Math.round(safeparseFloat(taxCodeLine.weigthPercentageMaxPrecision *
taxCode.RealTotalVAT / 100)*100)/100;;
currentTotalVAT +=
taxCodeLine.reproportionedVATAmount
}

taxCodeLine.amountToPostToCost =
Math.round(safeparseFloat(taxCodeLine.reproportionedVATAmount
*taxCodeLine.nonDeductiblePercentage/100)*100)/100

taxCode.TotalVATToPostAsCost +=
taxCodeLine.amountToPostToCost;

taxCodeLine.calculatedVATAmount =
taxCodeLine.baseAmount * taxCodeRate/100; // START FROM taxCode.RealTotalVAT AND
weigthPercentageMaxPrecision
}
taxCode.TotalVATToPostAsCost =
Math.round(safeparseFloat(taxCode.TotalVATToPostAsCost)*100)/100
}

// UNDERSTAND HOW MUCH THE RCH line amount is


compared to the total for the tax code
var currentBaseRchGLLine = null;
GLLines.allRCHTaxCodes = [];
for (var iCountBaseRCHGLLines = 0;
iCountBaseRCHGLLines < GLLines.baseGLLines.revCH.length; iCountBaseRCHGLLines++) {
currentBaseRchGLLine =
GLLines.baseGLLines.revCH[iCountBaseRCHGLLines];

//GLLines.JELines.revCH.standardTaxCodesMap =
{};
var taxCodeKey = taxItemSegmentExtIdPrefix + ''
+ currentBaseRchGLLine.taxItemId;

//nlapiLogExecution('AUDIT', 'customizeGlImpact
core ' + keyLog, 'taxCodeKey: ' + taxCodeKey);

if (typeof GLLines.rchTaxCodesMap[taxCodeKey]
== 'undefined'){

GLLines.allRCHTaxCodes.push(currentBaseRchGLLine.taxItemId);
GLLines.rchTaxCodesMap[taxCodeKey] = {};
GLLines.rchTaxCodesMap[taxCodeKey].total =
0;

GLLines.rchTaxCodesMap[taxCodeKey].PRVAT_TaxCodeName =
currentBaseRchGLLine.PRVAT_TaxCodeName;
GLLines.rchTaxCodesMap[taxCodeKey].recType
= recType;

GLLines.rchTaxCodesMap[taxCodeKey].taxItemId = currentBaseRchGLLine.taxItemId;
GLLines.rchTaxCodesMap[taxCodeKey].lines =
[];
}

var conditionalBaseAmount = 0;

if ((debitTransactions.indexOf(recType) >= 0))


{
conditionalBaseAmount =
currentBaseRchGLLine.debitAmount;
} else {
conditionalBaseAmount =
currentBaseRchGLLine.creditAmount;
}

GLLines.rchTaxCodesMap[taxCodeKey].total +=
conditionalBaseAmount;

GLLines.rchTaxCodesMap[taxCodeKey].lines.push({
isRch: true,
recType: recType,
originalExpenseAccount:
currentBaseRchGLLine.ACC_accountId,
CustomSegmentsValues:
currentBaseRchGLLine.CustomSegmentsValues,
baseAmount: conditionalBaseAmount,
nonDeductiblePercentage:
currentBaseRchGLLine.PRVAT_nonDeductiblePercentage,
});
}

nlapiLogExecution('AUDIT', '_getTaxCodeIdFromMemo
core segmentation', 'GLLines.allRCHTaxCodes.length: ' +
GLLines.allRCHTaxCodes.length);
if (GLLines.allRCHTaxCodes.length > 0){
GLLines.RchTaxCodeRates =
getTaxCodeParentItemRate(GLLines.allRCHTaxCodes);
}

for (var taxCodeKey in GLLines.rchTaxCodesMap) {


var taxCode =
GLLines.rchTaxCodesMap[taxCodeKey];
var taxCodeRate =
GLLines.RchTaxCodeRates[taxCodeKey];
taxCode.RealTotalVAT =
SupplementaryTaxLines_GrpByTaxCodeId[taxCodeKey].totalVat;
taxCode.TotalVATToPostAsCost = 0;
var currentTotalVAT = 0;

for (var iCountTaxCodeLines = 0;


iCountTaxCodeLines < taxCode.lines.length;iCountTaxCodeLines++){
var taxCodeLine =
taxCode.lines[iCountTaxCodeLines];
taxCodeLine.ratioTotalVSCurrent =
taxCode.total / taxCodeLine.baseAmount;
taxCodeLine.weigthPercentageMaxPrecision =
100 / taxCodeLine.ratioTotalVSCurrent;
taxCodeLine.taxCodeRate = taxCodeRate;
taxCodeLine.vatAccount =
SupplementaryTaxLines_GrpByTaxCodeId[taxCodeKey].vatAccount;

if (iCountTaxCodeLines ==
taxCode.lines.length-1){
taxCodeLine.reproportionedVATAmount =
taxCode.RealTotalVAT - currentTotalVAT;
} else {
// calculatedVATAmount :
weigthPercentageMaxPrecision = RealTotalVAT : 100
taxCodeLine.reproportionedVATAmount =
Math.round(safeparseFloat(taxCodeLine.weigthPercentageMaxPrecision *
taxCode.RealTotalVAT / 100)*100)/100;;
currentTotalVAT +=
taxCodeLine.reproportionedVATAmount
}

taxCodeLine.amountToPostToCost =
Math.round(safeparseFloat(taxCodeLine.reproportionedVATAmount
*taxCodeLine.nonDeductiblePercentage/100)*100)/100

taxCode.TotalVATToPostAsCost +=
taxCodeLine.amountToPostToCost;
taxCodeLine.calculatedVATAmount =
taxCodeLine.baseAmount * taxCodeRate/100;// START FROM taxCode.RealTotalVAT AND
weigthPercentageMaxPrecision
}

taxCode.TotalVATToPostAsCost =
Math.round(safeparseFloat(taxCode.TotalVATToPostAsCost)*100)/100
}

_CreateJSONFile('GLLines' + recId, GLLines,


folderIdForLogs);

var ProRateVATGLLinesExtIDS = [];


for (var taxCodeExtId in
GLLines.standardTaxCodesMap){
ProRateVATGLLinesExtIDS.push(taxCodeExtId);
}

for (var taxCodeExtId in GLLines.rchTaxCodesMap){


ProRateVATGLLinesExtIDS.push(taxCodeExtId);
}

var ProRateVATGLLines_GRPByExtIDS = {};


for (var taxCodeExtId in
GLLines.standardTaxCodesMap){
ProRateVATGLLines_GRPByExtIDS[taxCodeExtId] =
{};

ProRateVATGLLines_GRPByExtIDS[taxCodeExtId].PRVAT_TaxCodeName =
GLLines.standardTaxCodesMap[taxCodeExtId].PRVAT_TaxCodeName;

ProRateVATGLLines_GRPByExtIDS[taxCodeExtId].taxItemId =
GLLines.standardTaxCodesMap[taxCodeExtId].taxItemId;;
};

//name
for (var taxCodeExtId in GLLines.rchTaxCodesMap){

ProRateVATGLLines_GRPByExtIDS[taxCodeExtId] =
{};

ProRateVATGLLines_GRPByExtIDS[taxCodeExtId].PRVAT_TaxCodeName =
GLLines.rchTaxCodesMap[taxCodeExtId].PRVAT_TaxCodeName;

ProRateVATGLLines_GRPByExtIDS[taxCodeExtId].taxItemId =
GLLines.rchTaxCodesMap[taxCodeExtId].taxItemId;
};

var ProRataSegments =
handleCustomTaxCodeSegmentIO(GLLines,
ProRateVATGLLinesExtIDS,ProRateVATGLLines_GRPByExtIDS, keyLog);
var ProRataVATSegmentation_GrpByExtId =
ProRataSegments.ProRataVATSegmentation_GrpByExtId;

nlapiLogExecution('DEBUG', 'customizeGlImpact core


segmentation' + keyLog, 'ProRataSegments: ' + JSON.stringify(ProRataSegments));

// for each tax code line in standardTaxCodesMap


create additional impacts
if (actuallyCreateGlLine){
for (var taxCodeKey in
GLLines.standardTaxCodesMap) {
var taxCode =
GLLines.standardTaxCodesMap[taxCodeKey];
_addCustomGlLineNewMethod(customLines,
taxCode, ProRataVATSegmentation_GrpByExtId)
}
}

if (actuallyCreateGlLine){
for (var taxCodeKey in GLLines.rchTaxCodesMap)
{
var taxCode =
GLLines.rchTaxCodesMap[taxCodeKey];
_addCustomGlLineNewMethod(customLines,
taxCode, ProRataVATSegmentation_GrpByExtId)
}
}

} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core
' + keyLog, 'No lines subjected to calculation: ' + recId);
}

} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' +
keyLog, 'Skipping, no record id: ' + keyLog);
}

} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' +
keyLog, 'Skipping, no primary book: ' + keyLog);
}
} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' + keyLog,
'subsidiary '+subsidiary+' and or year '+trandateYear_N+' not configured');
}

} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' + keyLog, 'No
subsidiary, skipping');
}
} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core ' + keyLog, 'No
transaction date, skipping');
}
} catch(exc){
nlapiLogExecution('SYSTEM', 'customizeGlImpact core ' + keyLog, 'An error
occurred generating the additional lines: ' + exc.toString());
}

if (parseInt(userId,10) == 3){
//throw 'Debugging for employee 3'
}
}

var handleCustomTaxCodeSegmentIO = function (GLLines, ProRateVATGLLinesExtIDS,


ProRateVATGLLines_GRPByExtIDS , keyLog) {

var ProRataVATSegmentation_GrpByExtId = {};

nlapiLogExecution('DEBUG', 'customizeGlImpact core segmentation' + keyLog,


'ProRateVATGLLinesExtIDS: ' + JSON.stringify(ProRateVATGLLinesExtIDS));
nlapiLogExecution('DEBUG', 'customizeGlImpact core segmentation' + keyLog,
'ProRateVATGLLines_GRPByExtIDS: ' + JSON.stringify(ProRateVATGLLines_GRPByExtIDS));

if (ProRateVATGLLinesExtIDS.length > 0){

var TaxCodeSegmentValues_GrpByTaxCodeId =
_getCurrentTaxCodeSegmentValues(ProRateVATGLLinesExtIDS);
nlapiLogExecution('AUDIT', '_handleProRataVATSegmentation core
segmentation' + keyLog, 'TaxCodeSegmentValues_GrpByTaxCodeId: ' +
JSON.stringify(TaxCodeSegmentValues_GrpByTaxCodeId));

for (var iCountTaxCodesSegmentValues = 0;iCountTaxCodesSegmentValues<


ProRateVATGLLinesExtIDS.length;iCountTaxCodesSegmentValues++){

var taxCodeExtId =
ProRateVATGLLinesExtIDS[iCountTaxCodesSegmentValues];
var TaxCodeSegmentID =
TaxCodeSegmentValues_GrpByTaxCodeId[taxCodeExtId];
// I DONT HAVE THE SEGMENT CREATED YET
//nlapiLogExecution('DEBUG', '_handleProRataVATSegmentation core ' +
keyLog, 'Did I find the tax code with ext id?: ' + taxCodeExtId);
// nlapiLogExecution('DEBUG', '_handleProRataVATSegmentation core ' +
keyLog, 'Did I find the tax code with ext id?: ' + TaxCodeSegmentID);

if (typeof TaxCodeSegmentID== 'undefined') {


//nlapiLogExecution('AUDIT', '_handleProRataVATSegmentation core '
+ keyLog, 'NO Creating custom prorate tax code segment for tax code: ' +
taxCodeExtId);
var newTaxCodeSegmentId =
_createTaxCodeSegment(ProRateVATGLLines_GRPByExtIDS[taxCodeExtId]);
nlapiLogExecution('AUDIT', '_handleProRataVATSegmentation core
segmentation' + keyLog, 'CREATED: ' + newTaxCodeSegmentId + 'for extid: ' +
taxCodeExtId);
ProRataVATSegmentation_GrpByExtId[taxCodeExtId] =
newTaxCodeSegmentId;
} else {
// SEGMENT IS ALREADY IN PLACE IN THE SYSTEM
ProRataVATSegmentation_GrpByExtId[taxCodeExtId] = TaxCodeSegmentID;
//nlapiLogExecution('AUDIT', '_handleProRataVATSegmentation core '
+ keyLog, 'YES Skipped segment creation, already in place, ID: ' +
TaxCodeSegmentID);
}
}

} else {
nlapiLogExecution('AUDIT', '_handleProRataVATSegmentation core
segmentation' + keyLog, 'No Tax Codes Segments Found');

}
return {
ProRataVATSegmentation_GrpByExtId: ProRataVATSegmentation_GrpByExtId,
ProRateVATGLLines_GRPByExtIDS: ProRateVATGLLines_GRPByExtIDS,
};

};

var _getMemo = function (ProRateVATGLLine, taxItemId, PRVAT_TaxCodeName) {


var memo = '';
if (ProRateVATGLLine.isRch){
memo +='Reverse Charge - '
}
memo += 'Prorata Notional Tax Posting|Tax Code: ' + taxItemId + '|base Amount:
' + ProRateVATGLLine.baseAmount + '|Vat Rate: ' + ProRateVATGLLine.taxCodeRate +
'%|Prorated percentage: ' + ProRateVATGLLine.nonDeductiblePercentage;

return memo;
};

var getTaxCodeRate = function (taxCodeToSearchId) {

nlapiLogExecution('SYSTEM', '_getTaxCodeIdFromMemo core segmentation',


'filtering by internalid getTaxCodeRate: ' + taxCodeToSearchId);

var Srch = nlapiSearchRecord('salestaxitem', null, [


new nlobjSearchFilter('internalid',null,'anyOf',taxCodeToSearchId)
], [
new nlobjSearchColumn('rate'),
new nlobjSearchColumn('internalid')
]
);

var TaxCodeRatesMap = {};


if (Srch){
if (Srch.length){
for (var iCountSrchResults=0; iCountSrchResults <
Srch.length;iCountSrchResults++){
var internalid = Srch[iCountSrchResults].getValue('internalid');
var rate = Srch[iCountSrchResults].getValue('rate');

TaxCodeRatesMap[taxItemSegmentExtIdPrefix + '' + internalid] =


parseFloat(rate);

}
}
}

return TaxCodeRatesMap;
};

var getTaxCodeParentItemRate = function (taxCodeToSearchId) {

nlapiLogExecution('SYSTEM', '_getTaxCodeIdFromMemo core segmentation',


'filtering by internalid getTaxCodeParentItemRate: ' + taxCodeToSearchId);

var Srch = nlapiSearchRecord('salestaxitem', null, [


new nlobjSearchFilter('internalid',null,'anyOf',taxCodeToSearchId)
], [
new nlobjSearchColumn('internalid') ,
new nlobjSearchColumn('parent')]
);

var TaxCodeRatesMap = {};


if (Srch){
if (Srch.length){
for (var iCountSrchResults=0; iCountSrchResults <
Srch.length;iCountSrchResults++){
var internalid = Srch[iCountSrchResults].getValue('internalid');
var parent = Srch[iCountSrchResults].getValue('parent');

nlapiLogExecution('DEBUG', 'customizeGlImpact core taxcoderate',


'parent: ' + parent);

var taxCodeRateRes = getTaxCodeRate([parent]);

nlapiLogExecution('DEBUG', 'customizeGlImpact core taxcoderate',


'taxCodeRateRes: ' + JSON.stringify(taxCodeRateRes));
nlapiLogExecution('DEBUG', 'customizeGlImpact core taxcoderate',
'taxCodeRateRes value: ' + JSON.stringify(taxCodeRateRes[taxItemSegmentExtIdPrefix
+ '' + parent]));

TaxCodeRatesMap[taxItemSegmentExtIdPrefix + '' + internalid] =


taxCodeRateRes[taxItemSegmentExtIdPrefix + '' + parent];
}
}
}

return TaxCodeRatesMap;
};
var _addCustomGlLineNewMethod = function(customLines, taxCode,
ProRataVATSegmentation_GrpByExtId){
nlapiLogExecution('DEBUG', 'customizeGlImpact core CustomGlLine', 'taxCode: ' +
JSON.stringify(taxCode));
nlapiLogExecution('DEBUG', 'customizeGlImpact core CustomGlLine',
'transactionType: ' + taxCode.recType);

nlapiLogExecution('DEBUG', 'customizeGlImpact core CustomGlLine',


'originalTaxItemId: ' + taxCode.taxItemId);

var taxSegmentationKey = taxItemSegmentExtIdPrefix + taxCode.taxItemId;


var taxCodeSegmentId = ProRataVATSegmentation_GrpByExtId[taxSegmentationKey];

nlapiLogExecution('DEBUG', 'customizeGlImpact core CustomGlLine',


'taxCodeSegmentId: ' + taxCodeSegmentId);

for (var iCountOriginalLines = 0; iCountOriginalLines < taxCode.lines.length;


iCountOriginalLines++) {
var taxCodeLine = taxCode.lines[iCountOriginalLines];
nlapiLogExecution('DEBUG', 'customizeGlImpact core CustomGlLine', 'Creating
custom impact for line: ' + iCountOriginalLines + ' for tax code: ' +
taxCode.PRVAT_TaxCodeName);

var memo = _getMemo(taxCodeLine, taxCode.taxItemId,


taxCode.PRVAT_TaxCodeName);

if (taxCodeLine.amountToPostToCost > 0){


var proRateBookingCostLine = customLines.addNewLine();
nlapiLogExecution('AUDIT', 'customizeGlImpact core CustomGlLine',
'Custom line credit/debit amount: ' + taxCodeLine.amountToPostToCost + ' expense
account: ' + taxCodeLine.originalExpenseAccount);

if ((debitTransactions.indexOf(taxCode.recType) >= 0)){

proRateBookingCostLine.setDebitAmount(taxCodeLine.amountToPostToCost);
} else {

proRateBookingCostLine.setCreditAmount(taxCodeLine.amountToPostToCost);
}

proRateBookingCostLine.setAccountId(parseInt(taxCodeLine.originalExpenseAccount,10)
);
proRateBookingCostLine.setMemo('VAT ' + memo);

if (taxCodeLine.CustomSegmentsValues.department){

proRateBookingCostLine.setDepartmentId(taxCodeLine.CustomSegmentsValues.department)
;
}

if (taxCodeLine.CustomSegmentsValues.class){

proRateBookingCostLine.setClassId(taxCodeLine.CustomSegmentsValues.class);
}

if (taxCodeLine.CustomSegmentsValues.location){

proRateBookingCostLine.setLocationId(taxCodeLine.CustomSegmentsValues.location);
}

if (taxCodeSegmentId){
proRateBookingCostLine.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}

var proRateBookingVatLine = customLines.addNewLine();

nlapiLogExecution('AUDIT', 'customizeGlImpact core CustomGlLine',


'Custom line debit amount: ' + taxCodeLine.amountToPostToCost + ' expense account:
' + taxCodeLine.vatAccount);

if ((debitTransactions.indexOf(taxCode.recType) >= 0)){

proRateBookingVatLine.setCreditAmount(taxCodeLine.amountToPostToCost);
} else {

proRateBookingVatLine.setDebitAmount(taxCodeLine.amountToPostToCost);
}

proRateBookingVatLine.setAccountId(parseInt(taxCodeLine.vatAccount,10));
proRateBookingVatLine.setMemo('VAT ' + memo);

if (taxCodeLine.CustomSegmentsValues.department){

proRateBookingVatLine.setDepartmentId(taxCodeLine.CustomSegmentsValues.department);
}

if (taxCodeLine.CustomSegmentsValues.class){

proRateBookingVatLine.setClassId(taxCodeLine.CustomSegmentsValues.class);
}

if (taxCodeLine.CustomSegmentsValues.location){

proRateBookingVatLine.setLocationId(taxCodeLine.CustomSegmentsValues.location);
}

if (taxCodeSegmentId){
proRateBookingVatLine.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}
} else {
nlapiLogExecution('AUDIT', 'customizeGlImpact core CustomGlLine
SKIPPING', 'SKIPPING Custom line credit/debit amount: ' +
taxCodeLine.amountToPostToCost + ' expense account: ' +
taxCodeLine.originalExpenseAccount);
}

};
var _addCustomGlLine = function(customLines, ProRateVATGLLine,
ProRataVATSegmentation_GrpByExtId){
nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'ProRateVATGLLine: ' +
JSON.stringify(ProRateVATGLLine));

nlapiLogExecution('DEBUG', 'customizeGlImpact core',


'ProRateVATGLLine.PRVAT_transactionType: ' +
ProRateVATGLLine.PRVAT_transactionType);

var originalTaxItemId = ProRateVATGLLine.taxItemId;

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'originalTaxItemId: ' +


originalTaxItemId);

var taxSegmentationKey = taxItemSegmentExtIdPrefix + originalTaxItemId;


var taxCodeSegmentId = ProRataVATSegmentation_GrpByExtId[taxSegmentationKey];

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'taxCodeSegmentId: ' +


taxCodeSegmentId);

if ((debitTransactions.indexOf(ProRateVATGLLine.PRVAT_transactionType) >= 0)){


// CREDIT VAT ON PURCHASE (219), DEBIT COST ACCOUNT
nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Vendor Bill, cost
amount: ' + ProRateVATGLLine.PRVAT_notionalCostAmount);

if (ProRateVATGLLine.PRVAT_notionalCostAmount){

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Adding a new


line: ' + ProRateVATGLLine.PRVAT_notionalCostAmount + ' account: 219');

var proRateNewLine = customLines.addNewLine();


proRateNewLine.setCreditAmount(ProRateVATGLLine.PRVAT_notionalCostAmount);

var OriginalVATaccID = parseInt(ProRateVATGLLine.ACC_VATaccountId,10);


proRateNewLine.setAccountId(OriginalVATaccID);

var memo = _getMemo(ProRateVATGLLine);


proRateNewLine.setMemo('VAT ' + memo);

if (taxCodeSegmentId){
proRateNewLine.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}

var accID =
parseInt(ProRateVATGLLine.PRVAT_ACC_notionalImpact_costaccount,10);

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Adding a new


line: ' + ProRateVATGLLine.PRVAT_notionalCostAmount + ' account:' + accID);

var proRateNewLine_voidTheStandard = customLines.addNewLine();

proRateNewLine_voidTheStandard.setDebitAmount(ProRateVATGLLine.PRVAT_notionalCostAm
ount);
proRateNewLine_voidTheStandard.setAccountId(accID);

if (taxCodeSegmentId){

proRateNewLine_voidTheStandard.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}

proRateNewLine_voidTheStandard.setMemo('COST ' + memo);


}

if (ProRateVATGLLine.isCustomGL == true){
if (ProRateVATGLLine.PRVAT_ACC_notionalImpact_costaccountRCH){
// DEBIT VAT ON SALES (218), CREDIT COST ACCOUNT
}
}
} else {

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Vendor credit, cost


amount: ' + ProRateVATGLLine.PRVAT_notionalCostAmount);

if (ProRateVATGLLine.PRVAT_notionalCostAmount){

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Adding a new


line: ' + ProRateVATGLLine.PRVAT_notionalCostAmount + ' account: 219');

var proRateNewLine = customLines.addNewLine();

proRateNewLine.setCreditAmount(ProRateVATGLLine.PRVAT_notionalCostAmount);
var accID =
parseInt(ProRateVATGLLine.PRVAT_ACC_notionalImpact_costaccount,10);
proRateNewLine.setAccountId(accID);
//proRateNewLine_voidTheStandard.setSegmentValueId(segmentId,
segmentValueId)

var memo = _getMemo(ProRateVATGLLine);

proRateNewLine.setMemo('VAT ' + memo);

if (taxCodeSegmentId){
proRateNewLine.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}

nlapiLogExecution('DEBUG', 'customizeGlImpact core', 'Adding a new


line: ' + ProRateVATGLLine.PRVAT_notionalCostAmount + ' account:' + accID);

var proRateNewLine_voidTheStandard = customLines.addNewLine();

proRateNewLine_voidTheStandard.setDebitAmount(ProRateVATGLLine.PRVAT_notionalCostAm
ount);

var OriginalVATaccID = parseInt(ProRateVATGLLine.ACC_VATaccountId,10);


proRateNewLine_voidTheStandard.setAccountId(OriginalVATaccID);
proRateNewLine_voidTheStandard.setMemo('COST ' + memo);

if (taxCodeSegmentId){

proRateNewLine_voidTheStandard.setSegmentValueId(taxCodeCustomSegmentId,
parseInt(taxCodeSegmentId,10))
}
}

if (ProRateVATGLLine.isCustomGL == true){
// DEBIT VAT ON PURCHASE, CREDIT COST ACCOUNT
if (ProRateVATGLLine.PRVAT_ACC_notionalImpact_costaccountRCH){
// CREDIT VAT ON SALES, DEBIT COST ACCOUNT
}
}
}

};

var _createTaxCodeSegment = function (ProRateVATGLLine) {


var recordID = null;

var TaxCodeSegmentRecord = nlapiCreateRecord('customrecord_' +


taxCodeCustomSegmentId);
TaxCodeSegmentRecord.setFieldValue('externalid', taxItemSegmentExtIdPrefix +
ProRateVATGLLine.taxItemId);
TaxCodeSegmentRecord.setFieldValue('name', ProRateVATGLLine.PRVAT_TaxCodeName +
'_' + ProRateVATGLLine.taxItemId);
recordID = nlapiSubmitRecord(TaxCodeSegmentRecord);

return recordID

var _getCurrentTaxCodeSegmentValues = function (ProRateVATGLLinesExtIDS) {


var CurrentTaxCodeSegmentValues = {};

var SearchColumns = [];


SearchColumns.push(new nlobjSearchColumn('internalid'));
SearchColumns.push(new nlobjSearchColumn('name'));
SearchColumns.push(new nlobjSearchColumn('externalid'));

var searchFilters = [];


searchFilters.push(new nlobjSearchFilter('externalid', null, 'anyof',
ProRateVATGLLinesExtIDS));

var TaxCodeSegmentValuesSRCH = nlapiSearchRecord('customrecord_' +


taxCodeCustomSegmentId, null,searchFilters, SearchColumns);
if (TaxCodeSegmentValuesSRCH){
if(TaxCodeSegmentValuesSRCH.length){

for (var iCountResults = 0; iCountResults<


TaxCodeSegmentValuesSRCH.length; iCountResults++){
var currentTaxCodeSegmentExtId =
TaxCodeSegmentValuesSRCH[iCountResults].getValue('externalid');
if(typeof currentTaxCodeSegmentExtId != 'undefined'){
if (currentTaxCodeSegmentExtId){
if(typeof
CurrentTaxCodeSegmentValues[currentTaxCodeSegmentExtId] == 'undefined'){
CurrentTaxCodeSegmentValues[currentTaxCodeSegmentExtId]
= TaxCodeSegmentValuesSRCH[iCountResults].getValue('internalid');
}
}
}
}
}
}

return CurrentTaxCodeSegmentValues;

};

var getConfig = function (subsidiaryId, trandateYear_N) {

var config = null;


var SearchColumns = [];
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_prorate_taxcode','custrecord_delse_prorate_main
config'));
SearchColumns.push(new nlobjSearchColumn('custrecord_delse_proratevat_year'));
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_proratevat_nondeductibl')); // percentage of
ProRata for the year
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_proratevat_subsidiary'));
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_proratevat_subsidiaries'));
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_proratevat_segments'));
SearchColumns.push(new
nlobjSearchColumn('custrecord_delse_proratevat_folderid'));

var searchFilters = [];


//searchFilters.push(new
nlobjSearchFilter('custrecord_delse_proratevat_subsidiary', null, 'is',
subsidiaryId));
searchFilters.push(new nlobjSearchFilter('isinactive', null, 'is', 'F'));

var ConfigSRCH = nlapiSearchRecord('customrecord_delse_prorate_vat_config',


null,searchFilters, SearchColumns);
if (ConfigSRCH){
if(ConfigSRCH.length){

var validLinesForTheYear = [];


for (var iCountSrchResults = 0; iCountSrchResults < ConfigSRCH.length;
iCountSrchResults++){
var configYear =
ConfigSRCH[iCountSrchResults].getText('custrecord_delse_proratevat_year');
var configSupportedSegmentsString =
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_segments');
var configSupportedSegments =
configSupportedSegmentsString.replace(/[()\[\].'":<>{}]/g, '').split(",");

var isValidForAllYears = false;

if (configYear){

var configYear_N = null;


if (configYear == 'All years'){
isValidForAllYears = true;
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
config', 'Config is valid for all years');
} else {
configYear_N = parseInt(configYear,10);
}

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core ',


'trandateYear_N: ' + trandateYear_N + ' is equal to transaction year
'+configYear_N+', valid line found');

var ConfigMultiSubsidiariesIdsArr = [];


if ((trandateYear_N == configYear_N) || isValidForAllYears){
var ConfigSubsidiaryId =
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_subsidiary');
var ConfigMultiSubsidiariesIds =
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_subsidiaries');

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


config', 'ConfigSubsidiaryId: ' + ConfigSubsidiaryId);
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
config', 'ConfigMultiSubsidiariesIds: ' + ConfigMultiSubsidiariesIds);

var currentSubsidiaryIsIncludedInMultiSubConfig = false;


if (ConfigMultiSubsidiariesIds){
if (ConfigMultiSubsidiariesIds.indexOf(',') > -1) {
ConfigMultiSubsidiariesIdsArr =
ConfigMultiSubsidiariesIds.split(',');
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo
core config', 'ConfigMultiSubsidiariesIdsArr: ' +
JSON.stringify(ConfigMultiSubsidiariesIdsArr));
if (ConfigMultiSubsidiariesIdsArr.length > 0){
if
(ConfigMultiSubsidiariesIdsArr.indexOf(subsidiaryId) > -1){
currentSubsidiaryIsIncludedInMultiSubConfig
= true;
}
}
}
}

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


config', 'currentSubsidiaryIsIncludedInMultiSubConfig: ' +
currentSubsidiaryIsIncludedInMultiSubConfig);

var currentSubsidiaryIsIncludedInSingleSubConfig = false;


if (ConfigSubsidiaryId){
if (parseInt(ConfigSubsidiaryId,10) ===
parseInt(subsidiaryId,10)){
currentSubsidiaryIsIncludedInSingleSubConfig =
true;
}
}

if
(ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_folderid')){
folderIdForLogs =
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_folderid');
}

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


config', 'folderIdForLogs: ' + folderIdForLogs);
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
config', 'currentSubsidiaryIsIncludedInSingleSubConfig: ' +
currentSubsidiaryIsIncludedInSingleSubConfig);
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
config', 'currentSubsidiaryIsIncludedInMultiSubConfig: ' +
currentSubsidiaryIsIncludedInMultiSubConfig);

if (currentSubsidiaryIsIncludedInSingleSubConfig ||
currentSubsidiaryIsIncludedInMultiSubConfig){

var taxCodeName =
ConfigSRCH[iCountSrchResults].getText('custrecord_delse_prorate_taxcode','custrecor
d_delse_prorate_mainconfig');

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


config', 'Pushing tax code as valid: ' + taxCodeName);

validLinesForTheYear.push({
taxCodeId:
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_prorate_taxcode','custreco
rd_delse_prorate_mainconfig'),
taxCodeName: taxCodeName,
costaccountRCH: -1,
costaccount: -1,
nonDeductiblePercentage:
ConfigSRCH[iCountSrchResults].getValue('custrecord_delse_proratevat_nondeductibl'),
configSupportedSegments: configSupportedSegments,
})
}
}
}
};

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core ',


'validLinesForTheYear: ' + JSON.stringify(validLinesForTheYear));

if (validLinesForTheYear.length > 0){

config = {
nonDeductiblePercentage:
validLinesForTheYear[0].nonDeductiblePercentage,
configSupportedSegments:
validLinesForTheYear[0].configSupportedSegments,
taxCodes: {}
};

for (var iCountSrchResults = 0; iCountSrchResults <


validLinesForTheYear.length; iCountSrchResults++){
var tCodeId =
validLinesForTheYear[iCountSrchResults].taxCodeId;

if (typeof config.taxCodes[tCodeId] == 'undefined'){

config.taxCodes[tCodeId] = {
id: tCodeId,
name:
validLinesForTheYear[iCountSrchResults].taxCodeName,
costaccount:
validLinesForTheYear[iCountSrchResults].costaccount,
costaccountRCH:
validLinesForTheYear[iCountSrchResults].costaccountRCH,
};

//nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core ',


'current configuration: ' + JSON.stringify(config));
} else {
nlapiLogExecution('AUDIT', '_getTaxCodeIdFromMemo core ',
'found tax code, duplicated configuration: ' + tCodeId);
}
}
}
}
}

return config;
};

var getSupplementaryTaxLines = function (transactionId, recType,


supportedCustomSegments) {

var SearchColumns = [];


SearchColumns.push(new nlobjSearchColumn('creditfxamount'));
SearchColumns.push(new nlobjSearchColumn('creditamount'));
SearchColumns.push(new nlobjSearchColumn('debitfxamount'));
SearchColumns.push(new nlobjSearchColumn('debitamount'));
SearchColumns.push(new nlobjSearchColumn('memo'));
SearchColumns.push(new nlobjSearchColumn('line'));
SearchColumns.push(new nlobjSearchColumn('account'));
SearchColumns.push(new nlobjSearchColumn('entity'));
SearchColumns.push(new nlobjSearchColumn('class'));
SearchColumns.push(new nlobjSearchColumn('department'));

for (var iCountSupportedCustomSegments=0; iCountSupportedCustomSegments <


supportedCustomSegments.length; iCountSupportedCustomSegments++){

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core segmentation',


'adding column (RCH line) for segment: ' +
supportedCustomSegments[iCountSupportedCustomSegments]);

SearchColumns.push(new
nlobjSearchColumn(supportedCustomSegments[iCountSupportedCustomSegments]));
}

nlapiLogExecution('AUDIT', '_getTaxCodeIdFromMemo core segmentation',


'filtering by internalid getSupplementaryTaxLines: ' + transactionId);

var searchFilters = [];


searchFilters.push(new nlobjSearchFilter('internalid', null, 'is',
transactionId));
var formulaFilter = new nlobjSearchFilter('formulatext', null, 'is',
["Supplementary Tax Calculation"]);
formulaFilter.setFormula('{customscript}');
searchFilters.push(formulaFilter);

var mappedResults = [];


var SRCH = nlapiSearchRecord('transaction', null,searchFilters, SearchColumns);
if (SRCH){
if(SRCH.length){
for (var iCountSrchResults = 0; iCountSrchResults < SRCH.length;
iCountSrchResults++){

var creditfxAmountString =
SRCH[iCountSrchResults].getValue('creditfxamount');
var creditAmountString =
SRCH[iCountSrchResults].getValue('creditamount');
var debitfxAmountString =
SRCH[iCountSrchResults].getValue('debitfxamount');
var debitAmountString =
SRCH[iCountSrchResults].getValue('debitamount');

var debitAmount =
Math.round(safeparseFloat(debitAmountString)*100)/100;
var debitfxAmount =
Math.round(safeparseFloat(debitfxAmountString)*100)/100;
var creditAmount =
Math.round(safeparseFloat(creditAmountString)*100)/100;
var creditfxAmount =
Math.round(safeparseFloat(creditfxAmountString)*100)/100;

var CustomSegmentsValues = {};


for (var iCountSupportedCustomSegments=0;
iCountSupportedCustomSegments < supportedCustomSegments.length;
iCountSupportedCustomSegments++){

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


segmentation', 'getting value (RCH line) for segment: ' +
supportedCustomSegments[iCountSupportedCustomSegments]);
CustomSegmentsValues[supportedCustomSegments[iCountSupportedCustomSegments]] =
SRCH[iCountSrchResults].getValue(supportedCustomSegments[iCountSupportedCustomSegme
nts]);

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


segmentation', 'got value (RCH line) for segment: ' +
SRCH[iCountSrchResults].getValue(supportedCustomSegments[iCountSupportedCustomSegme
nts]));
}

var lineMemo = SRCH[iCountSrchResults].getValue('memo');


var taxItemId = null;
if(lineMemo){
taxItemId = _getTaxCodeIdFromMemo(lineMemo)
}

if (!(debitTransactions.indexOf(recType) >= 0)){


if (creditAmount > 0){
mappedResults.push({
creditfxAmount: creditfxAmount,
creditAmount: creditAmount,
debitfxAmount: debitfxAmount,
debitAmount: debitAmount,
taxAmount: creditAmount,
memoLine: lineMemo,
taxItemId: taxItemId,
lineid: SRCH[iCountSrchResults].getValue('line'),
departmentId:
SRCH[iCountSrchResults].getValue('department'),
classId: SRCH[iCountSrchResults].getValue('class'),
accountId: SRCH[iCountSrchResults].getValue('account'),
entityId: SRCH[iCountSrchResults].getValue('entity'),
CustomSegmentsValues: CustomSegmentsValues
});
}
} else {
if (debitAmount > 0){
mappedResults.push({
creditfxAmount: creditfxAmount,
creditAmount: creditAmount,
debitfxAmount: debitfxAmount,
debitAmount: debitAmount,
taxAmount: debitAmount,
memoLine: lineMemo,
taxItemId: taxItemId,
lineid: SRCH[iCountSrchResults].getValue('line'),
departmentId:
SRCH[iCountSrchResults].getValue('department'),
classId: SRCH[iCountSrchResults].getValue('class'),
accountId: SRCH[iCountSrchResults].getValue('account'),
entityId: SRCH[iCountSrchResults].getValue('entity'),
CustomSegmentsValues: CustomSegmentsValues
});
}
}
}
}
}

return mappedResults
};

var _getTaxCodeIdFromMemo = function (lineMemo) {

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


currentLineTaxCodeReferenceId', 'lineMemo: ' + lineMemo);

var currentLineTaxCodeReferenceId = null;

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


currentLineTaxCodeReferenceId', 'indexOf Reverse Charge Notional Tax Posting|Tax
Code: ' + lineMemo.indexOf('Reverse Charge Notional Tax Posting|Tax Code:'));
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
currentLineTaxCodeReferenceId', 'indexOf Intracommunity Notional Tax Posting|Tax
Code: ' + lineMemo.indexOf('Intracommunity Notional Tax Posting|Tax Code:'));
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
currentLineTaxCodeReferenceId', 'indexOf Notional Tax Posting|Tax Code: ' +
lineMemo.indexOf('Notional Tax Posting|Tax Code:'));

if (lineMemo.indexOf('Reverse Charge Notional Tax Posting|Tax Code:') > -1){


currentLineTaxCodeReferenceId = lineMemo.replace('Reverse Charge Notional
Tax Posting|Tax Code:', '');
}

if (lineMemo.indexOf('Intracommunity Notional Tax Posting|Tax Code:') > -1){


currentLineTaxCodeReferenceId = lineMemo.replace('Intracommunity Notional
Tax Posting|Tax Code:', '');
}

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


currentLineTaxCodeReferenceId', 'currentLineTaxCodeReferenceId: ' +
currentLineTaxCodeReferenceId);

return currentLineTaxCodeReferenceId;
};

var safeparseFloat = function (value) {


if (!value){
return 0;
} else {
return parseFloat(value)
}
};

var _getTaxCodeSupplementaryRCHDetails = function (taxItemId,


lineid ,SupplementaryTaxLines) {
var taxItemFoundInCustomGLLines = false;
var notionalVATCreditAmount = 0;
var notionalVATDebitAmount = 0;
var notionalVATAccount = 0;
nlapiLogExecution('AUDIT', '_getTaxCodeIdFromMemo core
taxItemFoundInCustomGLLines', 'SupplementaryTaxLines.length: ' +
SupplementaryTaxLines.length);
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
taxItemFoundInCustomGLLines', 'SupplementaryTaxLines: ' +
JSON.stringify(SupplementaryTaxLines));

var supplementaryTaxLine = null;


for (var iCountSupplementaryLines = 0; iCountSupplementaryLines <
SupplementaryTaxLines.length; iCountSupplementaryLines++) {
supplementaryTaxLine = SupplementaryTaxLines[iCountSupplementaryLines];

if (parseInt(taxItemId,10) === parseInt(supplementaryTaxLine.taxItemId,10))


{
taxItemFoundInCustomGLLines = true;
notionalVATDebitAmount = supplementaryTaxLine.debitAmount;
notionalVATCreditAmount = supplementaryTaxLine.creditAmount;
notionalVATAccount = supplementaryTaxLine.accountId;
}
}

return {
notionalVATCreditAmount: notionalVATCreditAmount,
notionalVATDebitAmount: notionalVATDebitAmount,
notionalVATAccount: notionalVATAccount,
taxItemFoundInCustomGLLines: taxItemFoundInCustomGLLines
}
};

var _mapProRateVATLines = function (GLLines, taxCodesToConsiderMap) {


var ProRateVATGLLines = [];

for (var iCountCustomGLLines = 0; iCountCustomGLLines <


GLLines.vatLinesToCondider.length; iCountCustomGLLines++) {

var mappedProRataGlLine_current =
_mapGlLineInProRateLine(GLLines.vatLinesToCondider[iCountCustomGLLines]);

ProRateVATGLLines.push(mappedProRataGlLine_current);

return ProRateVATGLLines
};

var _mapGlLineInProRateLine = function (mappedProRataGlLine) {


var ProRateLine = {};
ProRateLine.ACC_VATaccountId = mappedProRataGlLine.ACC_accountId;
ProRateLine.PRVAT_notionalImpact_amount =
mappedProRataGlLine.PRVAT_notionalImpact_amount;
ProRateLine.PRVAT_ACC_notionalImpact_costaccount =
mappedProRataGlLine.PRVAT_ACC_notionalImpact_costaccount;
ProRateLine.PRVAT_ACC_notionalImpact_costaccountRCH =
mappedProRataGlLine.PRVAT_ACC_notionalImpact_costaccountRCH;
ProRateLine.PRVAT_nonDeductiblePercentage =
mappedProRataGlLine.PRVAT_nonDeductiblePercentage;
ProRateLine.PRVAT_TaxCodeName = mappedProRataGlLine.PRVAT_TaxCodeName;
ProRateLine.PRVAT_baseAmount = mappedProRataGlLine.PRVAT_baseAmount;
ProRateLine.PRVAT_notionalCostAmount =
mappedProRataGlLine.PRVAT_notionalCostAmount;
ProRateLine.PRVAT_transactionType = mappedProRataGlLine.PRVAT_transactionType;
ProRateLine.lineid = mappedProRataGlLine.lineid;
ProRateLine.taxItemId = mappedProRataGlLine.taxItemId;
ProRateLine.isCustomGL = mappedProRataGlLine.taxItemFoundInCustomGLLines;
return ProRateLine
};

var _mapGlLine = function (currentStandardGLLine, iCountStandardGLLines,


supportedCustomSegments,isRCHSupplementaryTaxCalculation, SupplementaryTaxLines,
transactionType, subsidiaryConfigForTheYear) {
var entityId = currentStandardGLLine.getEntityId();
var lineid = currentStandardGLLine.getId();
var subsidiaryid = currentStandardGLLine.getSubsidiaryId();
var taxableAmount = currentStandardGLLine.getTaxableAmount();
var taxAmount = currentStandardGLLine.getTaxAmount();
var taxItemId = currentStandardGLLine.getTaxItemId();
var taxItemFoundInCustomGLLines = false;
var lineIsEnabledForCalculation = false;

if (isRCHSupplementaryTaxCalculation){
var taxCodeSupplementaryRCHDetails =
_getTaxCodeSupplementaryRCHDetails(taxItemId, lineid, SupplementaryTaxLines);
taxItemFoundInCustomGLLines =
taxCodeSupplementaryRCHDetails.taxItemFoundInCustomGLLines;

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


taxItemFoundInCustomGLLines', 'taxItemFoundInCustomGLLines: ' +
taxItemFoundInCustomGLLines);
}

var taxType = currentStandardGLLine.getTaxType();


var isPosting = currentStandardGLLine.isPosting();
var isTaxable = currentStandardGLLine.isTaxable();

var accountId = currentStandardGLLine.getAccountId();


var accountType = _getAccountType(accountId);
var classId = currentStandardGLLine.getClassId();
var creditAmountString = currentStandardGLLine.getCreditAmount();
var creditAmount = Math.round(safeparseFloat(creditAmountString)*100)/100;
var debitAmountString = currentStandardGLLine.getDebitAmount();
var debitAmount = Math.round(safeparseFloat(debitAmountString)*100)/100;

var departmentId = currentStandardGLLine.getDepartmentId();


var locationId = currentStandardGLLine.getLocationId();
var memoLine = currentStandardGLLine.getMemo();

var CustomSegmentsValues = {};


var currentSupportedSegmentId =null;
for (var iCountSupportedCustomSegments=0; iCountSupportedCustomSegments <
supportedCustomSegments.length; iCountSupportedCustomSegments++){
currentSupportedSegmentId =
supportedCustomSegments[iCountSupportedCustomSegments];

if (currentSupportedSegmentId == 'class'){
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core segmentation',
'getting value (NO RCH line) for class');
CustomSegmentsValues[currentSupportedSegmentId] =
currentStandardGLLine.getClassId();
} else {

if (currentSupportedSegmentId == 'department'){
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
segmentation', 'getting value (NO RCH line) for department');
CustomSegmentsValues[currentSupportedSegmentId] =
currentStandardGLLine.getDepartmentId();
} else {

if (currentSupportedSegmentId == 'location'){
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
segmentation', 'getting value (NO RCH line) for department');
CustomSegmentsValues[currentSupportedSegmentId] =
currentStandardGLLine.getLocationId();
} else {
nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core
segmentation', 'getting value (NO RCH line) for segment: ' +
currentSupportedSegmentId);
CustomSegmentsValues[currentSupportedSegmentId] =
currentStandardGLLine.getSegmentValueId(currentSupportedSegmentId)
}

//nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core


segmentation', 'getting value (NO RCH line) for segment: ' +
currentSupportedSegmentId);
//CustomSegmentsValues[currentSupportedSegmentId] =
currentStandardGLLine.getSegmentValueId(currentSupportedSegmentId)
}
}

nlapiLogExecution('DEBUG', '_getTaxCodeIdFromMemo core segmentation', 'got


value (NO RCH line) for segment: ' +
CustomSegmentsValues[currentSupportedSegmentId]);

var nonDeductiblePercentageStr =
subsidiaryConfigForTheYear.nonDeductiblePercentage;
var nonDeductiblePercentage = 0;
if(nonDeductiblePercentageStr){
nonDeductiblePercentage = parseFloat(nonDeductiblePercentageStr)
}
var taxCodeConfigKey = ''+taxItemId;
var taxCodeConfig = subsidiaryConfigForTheYear.taxCodes[taxCodeConfigKey];

var PRVAT_TaxCodeName = null;


var PRVAT_nonDeductiblePercentage = nonDeductiblePercentage;
var PRVAT_transactionType = transactionType;

if (typeof taxCodeConfig != "undefined"){


nlapiLogExecution('DEBUG', '_mapGlLine core ', 'found tax code prorata
config for taxcode: ' + taxCodeConfigKey + ' taxCodeConfig: ' +
JSON.stringify(taxCodeConfig));
PRVAT_TaxCodeName = taxCodeConfig.name;
if (nonDeductiblePercentage) {
lineIsEnabledForCalculation = true;
} else {
nlapiLogExecution('AUDIT', '_mapGlLine core ', 'percentage for prorata
is zero, have to skip calculation: ' + nonDeductiblePercentage);
}
} else {
nlapiLogExecution('AUDIT', '_mapGlLine core ', 'did not found tax code
prorata config for taxItemId: ' + taxItemId);
}

return {
lineIsEnabledForCalculation: lineIsEnabledForCalculation,
lineSequence: iCountStandardGLLines,
entityId: entityId,
lineid: lineid,
subsidiaryid: subsidiaryid,
taxableAmount: taxableAmount,
taxAmount: taxAmount,
taxItemId: taxItemId,
taxType: taxType,
taxItemFoundInCustomGLLines: taxItemFoundInCustomGLLines,
creditAmount: creditAmount,
creditAmountString: creditAmountString,
debitAmount: debitAmount,
debitAmountString: debitAmountString,
ACC_accountId: accountId,
ACC_accountType: accountType,
PRVAT_transactionType: PRVAT_transactionType,
PRVAT_TaxCodeName: PRVAT_TaxCodeName,
PRVAT_nonDeductiblePercentage: PRVAT_nonDeductiblePercentage,
isPosting: isPosting,
isTaxable: isTaxable,
classId: classId,
departmentId: departmentId,
locationId: locationId,
memoLine: memoLine,
CustomSegmentsValues: CustomSegmentsValues,
}
};

var AccountTypeMap = {};


var _getAccountType = function (accountId) {
if (typeof AccountTypeMap[accountId] == 'undefined'){
AccountTypeMap[accountId] = nlapiLookupField('account', accountId,
['type'])['type']
}

return AccountTypeMap[accountId];
};

// VENDOR BILLS EXAMPLES


// DOMESTIC
/*{
"standard": [
{
"lineSequence": 0,
"entityId": 2881,
"lineid": 0,
"subsidiaryid": 4,
"taxableAmount": "0",
"taxAmount": "0",
"taxItemId": null,
"taxType": null,
"isPosting": true,
"isTaxable": false,
"classId": null,
"creditAmount": 6048,
"creditAmountString": "6048",
"debitAmount": 0,
"debitAmountString": "0",
"departmentId": null,
"locationId": null,
"memoLine": null,
"accountId": 114,
"CustomSegmentsValues": {}
},
{
"lineSequence": 1,
"entityId": null,
"lineid": 1,
"subsidiaryid": 4,
"taxableAmount": "0",
"taxAmount": "0",
"taxItemId": 6,
"taxType": null,
"isPosting": true,
"isTaxable": false,
"classId": null,
"creditAmount": 0,
"creditAmountString": "0",
"debitAmount": 4838,
"debitAmountString": "4838",
"departmentId": 122,
"locationId": null,
"memoLine": "Dator",
"accountId": 378,
"CustomSegmentsValues": {}
},
{
"lineSequence": 2,
"entityId": null,
"lineid": 2,
"subsidiaryid": 4,
"taxableAmount": "0",
"taxAmount": "0",
"taxItemId": 9,
"taxType": null,
"isPosting": true,
"isTaxable": false,
"classId": 106,
"creditAmount": 0,
"creditAmountString": "0",
"debitAmount": 0.5,
"debitAmountString": "0.5",
"departmentId": null,
"locationId": null,
"memoLine": "Öresavrundning",
"accountId": 769,
"CustomSegmentsValues": {}
},
{
"lineSequence": 3,
"entityId": 9,
"lineid": 13,
"subsidiaryid": 4,
"taxableAmount": "0",
"taxAmount": "1209.5",
"taxItemId": 6,
"taxType": "VAT",
"isPosting": true,
"isTaxable": true,
"classId": null,
"creditAmount": 0,
"creditAmountString": "0",
"debitAmount": 1209.5,
"debitAmountString": "1209.5",
"departmentId": null,
"locationId": null,
"memoLine": "VAT",
"accountId": 631,
"CustomSegmentsValues": {}
},
{
"lineSequence": 4,
"entityId": 9,
"lineid": 14,
"subsidiaryid": 4,
"taxableAmount": "0",
"taxAmount": "0",
"taxItemId": 9,
"taxType": "VAT",
"isPosting": true,
"isTaxable": true,
"classId": null,
"creditAmount": 0,
"creditAmountString": "0",
"debitAmount": 0,
"debitAmountString": "0",
"departmentId": null,
"locationId": null,
"memoLine": "VAT",
"accountId": 631,
"CustomSegmentsValues": {}
}
],
"custom": [],
"transactionInfo": {
"userId": 3,
"recType": "vendorbill",
"recId": "427955",
"bookId": 1
}
}*/

// EU

You might also like