class CustParameterEventhandler
{
//Enable and Disable field "Extra Calculationday" based on Enum value for the field "CreditCheckType".
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_FINCustCreditCheckType), FormControlEventType::Modified)]
public static void FormGroupControl1_FINCustCreditCheckType_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormComboBoxControl finCreditCheckType = formRun.design(0).controlName("FormGroupControl1_FINCustCreditCheckType");
FormIntControl extraCalculationDays = formRun.design(0).controlName("FormGroupControl1_EQNExtraCalculationDays");
if(finCreditCheckType.valueStr() == enum2str(FINCustCreditCheckType::BasedonExposure))
{
extraCalculationDays.enabled(true);
}
else
{
extraCalculationDays.enabled(false);
}
}
//Lookup for the Sales PoolId
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_EQNExcludeFromExposure), FormControlEventType::Lookup)]
public static void FormGroupControl1_EQNExcludeFromExposure_OnLookup(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl excludeFromExposure = formRun.design(0).controlName("FormGroupControl1_EQNExcludeFromExposure");
Query query = new Query();
QueryBuildDataSource qbds;
SysTableLookup sysTableLookup;
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesPool), sender);
sysTableLookup.addLookupfield(fieldNum(SalesPool,SalesPoolId));
sysTableLookup.addLookupfield(fieldNum(SalesPool, Name));
qbds = query.addDataSource(tableNum(SalesPool));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
//Lookup created for standardDayRateCode using existing Table reference lookup method
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_EQNStandardDayRateCodeint), FormControlEventType::Lookup)]
public static void FormGroupControl1_EQNStandardDayRateCodeint_OnLookup(FormControl sender, FormControlEventArgs e)
{
CustParameterEventhandler::createLookup(sender);
}
private static void createLookup(FormReferenceGroupControl _ctrl)
{
SysReferenceTableLookup sysTableLookup = SysReferenceTableLookup::newParameters(tablenum(UnitOfMeasure), _ctrl);
Query query = new Query();
QueryBuildDataSource unitMeasureDS;
unitMeasureDS = query.addDataSource(tableNum(UnitOfMeasure));
unitMeasureDS.addRange(fieldNum(UnitOfMeasure,UnitOfMeasureClass)).value(SysQuery::value(UnitOfMeasureClass::Time));
sysTableLookup.addLookupfield(fieldNum(UnitOfMeasure,Symbol));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
}
======================================================================
class EQNCreditExposureCalculations
{
Amount openbalance,orderedAmt,totExposure,TotPercentExposure;
static Amount calculateMarkupTrans(SalesId _salesId)
{
AmountCur markupAmount,headermarkupamt,linemarkupamt,totTaxAmountCur,lineamount;
MarkupTrans markupTrans;
CurrencyExchangeHelper curCurrencyExchangeHelper;
SalesTable salesTable = SalesTable::find(_salesId);
SalesLine salesLine;
SalesTotals salestotals;
container cont;
// Code to calculate total tax for sales order inlucing charges tax-->
salesTotals = SalesTotals::construct(salesTable, SalesUpdate::All);
salesTotals.calc();
cont = salesTotals.displayFieldsCurrency(salesTotals.currencyCode());
totTaxAmountCur = conpeek(cont, TradeTotals::posTaxTotal());
// Code to calculate total tax for sales order inlucing charges tax<--
// Code to calculate total Charge for sales order header-->
while select markupTrans
where markupTrans.TransTableId == salesTable.TableId
&&markupTrans.TransRecId == salesTable.RecId
{
markupAmount = markupTrans.Value;
if (markupTrans.CurrencyCode != salesTable.CurrencyCode)
{
// To automatically conver amount Markup::calcMarkupAmount can be used
curCurrencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::primaryLedger(CompanyInfo::findDataArea(markupTrans.company()).RecId), systemDateGet());
markupAmount = curCurrencyExchangeHelper.calculateAccountingToTransaction(salesTable.CurrencyCode, markupAmount, true);
}
headermarkupamt =headermarkupamt+markupAmount;
}
// Code to calculate total Charge for sales order header <--
// Code to calculate total Charge for sales order lines-->
while select salesLine
where salesLine.SalesId == salesTable.SalesId
{
while select markupTrans
where markupTrans.TransTableId == salesLine.TableId
&&markupTrans.TransRecId == salesLine.RecId
{
markupAmount = Markup::calcTrans(markupTrans, salesLine.SalesQty, salesLine.LineAmount);
if (markupTrans.CurrencyCode != salesTable.CurrencyCode)
{
// To automatically conver amount Markup::calcMarkupAmount can be used
curCurrencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::primaryLedger(CompanyInfo::findDataArea(markupTrans.company()).RecId), systemDateGet());
markupAmount = curCurrencyExchangeHelper.calculateAccountingToTransaction(salesTable.CurrencyCode, markupAmount, true);
}
linemarkupamt = linemarkupamt+markupAmount;
}
}
// Code to calculate total Charge for sales order lines<--
markupAmount = linemarkupamt+headermarkupamt;//Sum both line and Header Charges for Sales order
// Calculate Charge lines tax if we get tax > 0 for sales order-->
if(salesTable.InclTax == noyes::No && totTaxAmountCur >0)// Calculate Charge lines tax if we get tax > 0 for sales order
{
TaxGroupHeading taxgroup;
TaxGroupData taxgroupdata;
select * from taxgroupdata
where taxgroupdata.TaxGroup == salesTable.TaxGroup;
real taxpercent =taxgroupdata.ShowTaxValue();
markupAmount =markupAmount+(markupAmount*taxgroupdata.ShowTaxValue())/100;//Add tax amount to Charge lines when Salestable Includetax field is set to no.
}
// Calculate Charge lines tax if we get tax > 0 for sales order-->
return markupAmount;
}
public Amount custorderedbal(CustTable _custTbl)
{
CustCreditLimit custCreditLimit;
SalesTable salesTable;
SalesTotals salesTotals;
salesTable.CustAccount = _custTbl.AccountNum;
salesTable.initFromCustTable();
salesTotals = SalesTotals::construct(salesTable);
salesTotals.calc();
custCreditLimit = CustCreditLimit::construct(salesTable);
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
orderedAmt = EQNFINCustExposureTrans::CustomerExposure(_custTbl.AccountNum);
}
else
orderedAmt = custCreditLimit.balanceEstimate();
return orderedAmt;
}
//Calculates Financial Exposure for the Current Order.
public static client server Amount financalExposurePerOrder(EQNOrderTypes _orderTypes,SalesTable _salesTable)
{
Amount financialriskperorder,financialriskperline;
Query query;
QueryRun qr;
SalesTable salesTable;
SalesLine salesLine;
EQNCreditExposureCalculations fincheckcreditlimit = new EQNCreditExposureCalculations();
while select salesLine
where salesLine.SalesId ==_salesTable.SalesId
{
Amount lineamount=0,TaxAmountCur=0;
financialriskperline =0;
if(salesline.SalesQty-salesline.invoicedInTotal()== 0)
{
financialriskperline =0;
continue;
}
if(salesLine.RORTradeType == RORTradeType::Rental || salesLine.RORTradeType == RORTradeType::SubRental)
{
if(salesLine.INVInvoiceProfileId != CustParameters::find().EQNINVInvoiceProfileSetRate)
financialriskperline = fincheckcreditlimit.rentalTypeCreditExposure(salesLine,_salesTable.CustAccount);//(salesline.SalesQty-salesline.invoicedInTotal()) * fincheckcreditlimit.rentalTypeCreditExposure(salesLine,_salesTable.CustAccount);
else
{
lineamount = salesLine.RORRentalLine::editLineAmount(false,salesLine.LineAmount);
if(SalesTable::find(salesLine.SalesId).InclTax == noyes::No)
{
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
financialriskperline = lineamount;
}
}
else if (salesLine.RORTradeType == RORTradeType::SalesPurch)
{
if(_salesTable.SalesType ==SalesType::RORRental)
{
lineamount = salesLine.RORRentalLine::editLineAmount(false,salesLine.LineAmount);
if(salesline.invoicedInTotal()>0)
{
qty invoicedqty = salesline.invoicedInTotal();
lineamount = (lineamount/salesline.SalesQty)*(salesline.SalesQty-invoicedqty);//Get line amount for only uninvoiced lines
}
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
financialriskperline = lineamount;
}
else
{
qty invoicedqty = salesline.invoicedInTotal();
if(salesline.SalesQty-salesline.invoicedInTotal()>0)
{
if(salesline.lineDisc > 0)
lineamount = salesLine.SalesPrice-salesline.lineDisc;
if(salesLine.LinePercent >0)
lineamount = salesLine.SalesPrice - ((salesLine.SalesPrice*salesLine.LinePercent)/100);
if(salesline.lineDisc == 0 && salesLine.LinePercent == 0)
lineamount = salesLine.SalesPrice;//salesLine.LineAmount;
if(SalesTable::find(salesLine.SalesId).InclTax == noyes::No)
{
//TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, salesLine.LineAmount, TaxModuleType::Sales);
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
financialriskperline = (salesline.SalesQty-salesline.invoicedInTotal()) * lineamount;
}
//financialriskperline = financialriskperline +TaxAmountCur;
}
}
financialriskperorder = financialriskperorder + financialriskperline;
}
//fincheckcreditlimit.insertEQNFINCustExposureTrans(_salesTable,financialExposurePerOrder);
return financialriskperorder;
}
public static void delEqnCustExposureTrans(SalesTable _salesTable)
{
SalesLine salesline;
EQNFINCustExposureTrans finCustExposureTrans = null;
select sum(REMAINSALESPHYSICAL) from salesline where salesline.SALESID == _salesTable.SalesId;
if(salesline.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == _salesTable.SalesId;
}
}
//Insert Financial Exposure for the Current Order in to EQNFINCustExposureTrans.
public static client server void insertEQNFINCustExposureTrans(SalesTable _salesTable,Amount financialriskAmt)
{
EQNFINCustExposureTrans finCustExposureTrans =null;
finCustExposureTrans = EQNFINCustExposureTrans::find(_salesTable.SalesId,true);
if(finCustExposureTrans)
{
ttsbegin;
finCustExposureTrans.EQNExposureValue = financialriskAmt;
finCustExposureTrans.update();
ttscommit;
}
else
{
finCustExposureTrans.EQNCurrency = _salesTable.CurrencyCode;
finCustExposureTrans.EQNExposureValue = financialriskAmt;
finCustExposureTrans.EQNProspectAccount = _salesTable.CustAccount;
finCustExposureTrans.EQNSalesId = _salesTable.SalesId;
if(_salesTable.SalesType == SalesType::Sales)
finCustExposureTrans.EQNSalesType = Eqnordertypes::SalesOrder;
if(_salesTable.SalesType == SalesType::RORRental)
finCustExposureTrans.EQNSalesType = Eqnordertypes::RentalOrder;
finCustExposureTrans.insert();
}
}
public int workingdaysIncalendar(CalendarId _calendarId,int days)
{
WorkCalendarSched workCalendarSched;
date start;
date end;
counter workingdays;
counter totaldays;
CalendarId primCalendar=_calendarId;
start=today();
end= today()+days;
workCalendarSched = new workCalendarSched();
while(start<end)
{
if(workCalendarSched.isdateopen(primCalendar,start)==true)
{
workingdays++;
}
start++;
}
return workingdays;
}
//Calculation of financial exposure for Rental order type
public Amount rentalTypeCreditExposure(SalesLine _salesline, accountNum _custacc)
{
Days creditExposurePeriod,paymentdays,expectedRentalPeriod,rentaldayInExposure;
TransDate estimatedoffrentdate,calDate;
CustParameters custParameters;
Amount rentalLineFinancialRisk=0,ratePerRentalDay=0;
PaymTerm PaymTerm;
RORRentalDateTimes rentalDateTimes;
INVInvoicePeriod invInvoicePeriod;
real chargeableDays=0,unitconversion=0,unitconversionfinal=0,workingdays=0,unitval;
Amount lineamount=0,TaxAmountCur=0;
custParameters = CustParameters::find(false);
rentalDateTimes = RORRentalDateTimes::findReference(_salesline.TableId,_salesline.RecId,false);
paymentdays = PaymTerm::find(SalesTable::find(_salesline.SalesId).payment).NumOfDays;
select * from invInvoicePeriod
where invInvoicePeriod.PeriodStatus == INVPeriodStatus::Uninvoiced
&& invInvoicePeriod.RefRecId == _salesline.RecId
&& invInvoicePeriod.RefTableId == _salesline.TableId;
if(!invInvoicePeriod.RecId)
return 0;
if(DateTimeUtil::date(rentalDateTimes.OffRentDateTime)!= dateNull())
estimatedoffrentdate = DateTimeUtil::date(rentalDateTimes.OffRentDateTime);
else
estimatedoffrentdate = DateTimeUtil::date(rentalDateTimes.ExpectedOffRentDateTime);
select firstonly invInvoicePeriod
order by RecId desc
where invInvoicePeriod.RefRecId == _salesline.RecId
&& invInvoicePeriod.RefTableId == _salesline.TableId
&& (invInvoicePeriod.PeriodStatus == INVPeriodStatus::FullyInvoiced) || (invInvoicePeriod.PeriodStatus == INVPeriodStatus::PartiallyInvoiced);
if(invInvoicePeriod)
{
if(DateTimeUtil::date(invInvoicePeriod.PeriodEndDateTime) > today())
calDate = DateTimeUtil::date(invInvoicePeriod.PeriodEndDateTime);
else
calDate = today();
if(DateTimeUtil::date(rentalDateTimes.OnRentDateTime) > calDate)
calDate = DateTimeUtil::date(rentalDateTimes.OnRentDateTime);
}
else
{
if(DateTimeUtil::date(rentalDateTimes.OnRentDateTime) > today())
calDate = DateTimeUtil::date(rentalDateTimes.OnRentDateTime);
else
calDate = today();
}
expectedRentalPeriod = estimatedoffrentdate-calDate+1;
if(paymentdays+custParameters.EQNExtraCalculationDays > expectedRentalPeriod)
rentaldayInExposure = expectedRentalPeriod;
else
rentaldayInExposure = paymentdays+custParameters.EQNExtraCalculationDays;
UnitOfMeasure unitofmeasure,unitofmeasure1;
select unitofmeasure
where unitofmeasure.RecId == _salesline.RORPriceTimeUnit;
select unitofmeasure1
where unitofmeasure1.RecId == custParameters.EQNStandardDayRateCodeint;
unitconversion = UnitOfMeasureConverter::convert(rentaldayInExposure,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
NoYes::No,
NoYes::No);
unitval = UnitOfMeasureConverter::convert(1.0,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
NoYes::No,
NoYes::No);
workingdays = this.workingdaysIncalendar(_salesline.RORCalendarId,unitconversion);
unitconversionfinal = UnitOfMeasureConverter::convert(workingdays,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
NoYes::No,
NoYes::No);
chargeableDays = unitconversionfinal;
if(SalesTable::find(_salesline.SalesId).InclTax == noyes::No)
{
RORRentalLine rorRentalline;
select rorRentalline
where rorRentalline.InventTransId == _salesline.InventTransId;
lineamount = _salesline.RORRentalLine::editLineAmount(false,_salesline.LineAmount);//_salesline.RORRentalGrossAmount;//RORRentalLine::editLineAmount(false,_salesline.LineAmount);
//lineamount = _salesline.RORRentalLine::ROREditNetAmount(false,_salesline.LineAmount);
TaxAmountCur=Tax::calcTaxAmount(_salesline.TaxGroup, _salesline.TaxItemGroup, Systemdateget(), _salesline.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
Qty invoiced = _salesline.invoicedInTotal();
//lineamount = lineamount*(_salesline.SalesQty-_salesline.invoicedInTotal());//Value will not differ for rental line as salesline
ratePerRentalDay = lineamount/unitval;
rentalLineFinancialRisk = chargeableDays * ratePerRentalDay;
return rentalLineFinancialRisk;
}
//Build Query to calculate
public Query buildQuery(EQNOrderTypes type,SalesId _salesId, SalesId _rentalId, accountNum _custacc)
{
QueryBuildDataSource qdbsSO;
QueryBuildRange qbrsalesType,qbrsalesStatus,qbrsalesId,qbrrentalId,qbrcustAcc,qbrdocumentstatus;
Query query = new Query(queryStr (EQNRecalculateExposureQry));
qdbsSO = query.dataSourceTable(tablenum(SalesTable));
//Apply parameter ranges on query
qbrsalesType = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, SalesType));
qbrsalesStatus = query.dataSourceTable( tablenum (SalesTable)).findRange( fieldNum (SalesTable, SalesStatus));
if(!qbrsalesStatus)
query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, SalesStatus));
qbrdocumentstatus = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, DocumentStatus));
//qdbsSO.findRange( fieldNum (SalesTable, SalesStatus))
qbrdocumentstatus.value(strfmt('!%1,%2,%3,%4',enum2str(DocumentStatus::None),enum2str(DocumentStatus::Confirmation),enum2str(DocumentStatus::Invoice),enum2str(DocumentStatus::PackingSlip)));
if(type ==EQNOrderTypes ::Both)
qbrsalesType.value(strfmt('%1,%2',enum2str(SalesType::Sales),enum2str(SalesType::RORRental)));
else if(type == EQNOrderTypes::SalesOrder)
{
qbrsalesType.value(strfmt('%1',enum2str(SalesType::Sales)));
}
else if(type == EQNOrderTypes::RentalOrder)
{
qbrsalesType.value(strfmt('%1',enum2str(SalesType::RORRental)));
}
if(_salesId)
{
qbrsalesId = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, salesId));
qbrsalesId.value(_salesId);
//qbrsalesStatus.value(strfmt('!%1,%2,%3',enum2str(SalesStatus::Invoiced),enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
//qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(enum2str(SalesStatus::Invoiced));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(enum2str(SalesStatus::Canceled));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::None)));
}
if(_rentalId)
{
qbrrentalId = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, salesId));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::Invoiced)));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::Canceled)));
//qbrsalesStatus.value(strfmt('!%1,!%2',enum2str(SalesStatus::Invoiced),enum2str(SalesStatus::Canceled)));
qbrrentalId.value(_rentalId);
}
if(_custacc)
{
qbrcustAcc = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, custAccount));
qbrcustAcc.value(_custacc);
}
return query;
}
public static AmountCur openBalanceCur(CustTable _custTable,
TransDate _fromDate = dateNull(),
TransDate _toDate = dateMax(),
TransDate _assessmentDate = dateNull(),
CurrencyCode _currency = CompanyInfoHelper::standardCurrency())
{
CustTrans custTrans;
CustTransOpen custTransOpen;
CustSettlement custSettlement;
AmountCur openBalanceCur;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
if (_assessmentDate)
{
//custSettlement = this.settlementBuffer();
select sum(SettleAmountCur)
from custSettlement
group by AccountNum
where custSettlement.AccountNum == _custTable.AccountNum
&& custSettlement.TransDate > _assessmentDate
join custTrans
where custTrans.RecId == custSettlement.TransRecId
&& custTrans.TransDate >= _fromDate
&& custTrans.TransDate <= _toDate
&& custTrans.CurrencyCode == _currency
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceCur = custSettlement.SettleAmountCur;
openBalanceCur += EQNCreditExposureCalculations::openBalanceCur(_custTable,_fromDate, _toDate, dateNull(), _currency);
}
else
{
select custTrans
where custTrans.AccountNum == _custTable.AccountNum
&& custTrans.CurrencyCode == _currency
join sum(AmountCur) from custTransOpen
group by AccountNum
where custTransOpen.RefRecId == custTrans.RecId
&& custTransOpen.TransDate >= _fromDate
&& custTransOpen.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceCur = custTransOpen.AmountCur;
}
return openBalanceCur;
}
public static AmountMST openBalanceMST(CustTable _custTable,
FromDate _fromDate = dateNull(),
ToDate _toDate = dateMax(),
TransDate _assessmentDate = dateNull())
{
CustTrans custVendTrans;
CustTransOpen custVendTransOpen;
CustSettlement custVendSettlement;
AmountMST openBalanceMST;
boolean hasAccess;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
if (_assessmentDate)
{
switch (custVendTrans.TableId)
{
case tableNum(CustTrans) :
hasAccess = hasFieldAccess(tableNum(CustSettlement), fieldNum(CustSettlement, SettleAmountMST));
hasAccess = hasAccess && hasFieldAccess(tableNum(CustSettlement), fieldNum(CustSettlement, ExchAdjustment));
break;
case tableNum(VendTrans) :
hasAccess = true;
break;
default :
hasAccess = false;
}
if (!hasAccess)
throw error("@SYS57330");
select sum(SettleAmountMST),sum(ExchAdjustment) from custVendSettlement
group by AccountNum
where custVendSettlement.AccountNum == _custTable.AccountNum &&
custVendSettlement.TransDate > _assessmentDate
join custVendTrans
where custVendTrans.RecId == custVendSettlement.TransRecId &&
custVendTrans.TransDate >= _fromDate &&
custVendTrans.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custVendTrans.Voucher
&& custInvoiceJour.InvoiceId == custVendTrans.Invoice
&& custInvoiceJour.InvoiceDate == custVendTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custVendTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceMST = custVendSettlement.SettleAmountMST + custVendSettlement.ExchAdjustment;
openBalanceMST += EQNCreditExposureCalculations::openBalanceMST(_custTable,_fromDate, _toDate);
}
else
{
select sum(AmountMST) from custVendTransOpen
where custVendTransOpen.AccountNum == _custTable.AccountNum &&
custVendTransOpen.TransDate >= _fromDate &&
custVendTransOpen.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custVendTrans.Voucher
&& custInvoiceJour.InvoiceId == custVendTrans.Invoice
&& custInvoiceJour.InvoiceDate == custVendTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custVendTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceMST = custVendTransOpen.AmountMST;
}
return openBalanceMST;
}
}
===================================================================
class EQNCustBalanceListUIBuilder extends SrsReportDataContractUIBuilder
{
DialogField dialogexceededLimit;
DialogField dialogzeroBalance;
DialogField dialogasOfDate;
DialogField dialogpercent;
boolean enable;
EQNCustBalanceListContract contract;
public void build()
{
Dialog dialogLocal;
dialogLocal = this.dialog();
contract = this.dataContractObject();
utcDateTime myDateTime;
dialogasOfDate = this.addDialogField(methodStr(EQNCustBalanceListContract, parmAsOfDate),contract);
myDateTime = DateTimeUtil::applyTimeZoneOffset(myDateTime,DateTimeUtil::getUserPreferredTimeZone());
//contract.parmAsOfDate(today());
contract.parmAsOfDate(systemDateGet());
dialogasOfDate.value(today());
dialogasOfDate.enabled(False);
dialogpercent = this.addDialogField(methodStr(EQNCustBalanceListContract, parmPercent),contract);
dialogpercent.value(100);
dialogexceededLimit = this.addDialogField(methodStr(EQNCustBalanceListContract, parmExceededLimit),contract);
dialogzeroBalance = this.addDialogField(methodStr(EQNCustBalanceListContract, parmZeroBalance),contract);
controller.parmDialogCaption('@EQN:CustbalancelistbasedonCreditExposure');
}
public void getFromDialog()
{
contract = this.dataContractObject();
super();
}
/*public void initializeFields()
{
utcDateTime myDateTime;
contract = this.dataContractObject();
myDateTime = DateTimeUtil::applyTimeZoneOffset(myDateTime,DateTimeUtil::getUserPreferredTimeZone());
//contract.parmAsOfDate(today());
contract.parmAsOfDate(myDateTime);
}*/
}
==================================================================
[ExtensionOf(classStr(CustCreditLimit))]
Final class EQNCustCreditLimit_Extension
{
AmountMST EQNbalanceEstimate()
{
AmountMST balanceEstimate=0;
SalesTable localSalesTable;
QueryRun queryRun;
queryRun = new QueryRun(this.initQuery());
queryRun.query().dataSourceTable(tablenum(SalesTable)).fields().addField(fieldnum(SalesTable,Estimate),SelectionField::Sum);
// queryRun.query().dataSourceTable(tablenum(SalesTable)).addRange(fieldNum(SalesTable,SalesPoolId)).value(SYSQuery::valueNot(queryvalue(CustParameters::find().EQNExcludeFromExposure)));
while (queryRun.next())
{
if (queryRun.changed(tablenum(SalesTable)))
{
localSalesTable = queryRun.get(tablenum(SalesTable));
if(!PaymTerm::find(localSalesTable.Payment,false).EQNExcludefromexposurecalculations)
balanceEstimate += localSalesTable.Estimate;
}
}
return balanceEstimate;
}
public boolean check()
{
boolean ret = true;
// ret = next check();
CustCreditLimit thisclass = new CustCreditLimit(custtable);
TypeOfCreditmaxCheck typeOfCreditmaxCheck1;
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
typeOfCreditmaxCheck1 = typeOfCreditmaxCheck;
typeOfCreditmaxCheck = typeOfCreditmaxCheck::None;
}
ret = next check();
if(CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
ret = true;
//FINCheckCreditLimit::checkCreditLimit_Sales(SalesTable, true, CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure);*/
return ret;
}
public boolean EQNuseEstimated()
{
return (FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum));
}
}
===================================================================
class EQNCustomerCreditExposurePerOrderUIBuilder extends SrsReportDataContractUIBuilder
{
DialogField dialogexceededLimit;
DialogField dialogOrderType;
DialogField dialogpercent;
boolean enable;
EQNCustomerCreditExposurePerOrderContract contract;
public void build()
{
Dialog dialogLocal;
dialogLocal = this.dialog();
contract = this.dataContractObject();
dialogOrderType = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmOrderTypes),contract);
dialogpercent = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmPercent),contract);
dialogpercent.value(100);
dialogexceededLimit = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmExceededLimit),contract);
controller.parmDialogCaption('@EQN:CustomerCreditExposurePerOrder');
}
public void getFromDialog()
{
contract = this.dataContractObject();
super();
}
}
====================================================================
class EQNFINCustExposureTransDel
{
[FormControlEventHandler(formControlStr(SalesTable, buttonUpdateInvoice), FormControlEventType::Clicked)]
public static void buttonUpdateInvoice_OnClicked(FormControl sender, FormControlEventArgs e)
{
EQNFINCustExposureTrans finCustExposureTrans = null;
SalesTable ST;
FormRun formRun = sender.formRun() as FormRun;
FormDataSource ST_ds;
SALESLINE SL;
ST_ds = sender.formRun().dataSource(1);
ST = ST_ds.cursor();
select sum(REMAINSALESPHYSICAL) from SL where SL.SALESID == ST.SalesId;
if(SL.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == ST.SalesId;
}
}
[FormControlEventHandler(formControlStr(SalesTableListPage, buttonUpdateInvoice), FormControlEventType::Clicked)]
public static void buttonUpdateInvoiceLiatPage_OnClicked(FormControl sender, FormControlEventArgs e)
{
EQNFINCustExposureTrans finCustExposureTrans = null;
SalesTable ST;
FormRun formRun = sender.formRun() as FormRun;
FormDataSource ST_ds;
SALESLINE SL;
ST_ds = sender.formRun().dataSource(1);
ST = ST_ds.cursor();
select sum(REMAINSALESPHYSICAL) from SL where SL.SALESID == ST.SalesId;
if(SL.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == ST.SalesId;
}
}
}
=======================================================================
[
DataContractAttribute
//,SysOperationContractProcessingAttribute(classStr(EQNRecalculateExposureUIBuilder))
]
class EQNRecalculateExposureContract implements SysOperationValidatable
{
CustAccount custAccount;
Salesid salesId,rentalId;
EQNOrderTypes orderTypes;
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('EQNOrderTypes'),
SysOperationLabelAttribute('@EQN:OrderTypes'),
SysOperationDisplayOrderAttribute('1'),
SysOperationHelpTextAttribute(literalStr("Select an Order Type"))
]
Public EQNOrderTypes parmOrderTypes(EQNOrderTypes _orderTypes = orderTypes)
{
orderTypes = _orderTypes;
Return orderTypes;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('CustAccount'),
SysOperationLabelAttribute('@EQN:CustomerAccount'),
SysOperationDisplayOrderAttribute('2'),
SysOperationHelpTextAttribute(literalStr("Customer Account no."))
]
public CustAccount parmCustAccount(CustAccount _custAccount = custAccount)
{
custAccount = _custAccount;
return custAccount;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('SalesId'),
SysOperationLabelAttribute('@EQN:Salesorder'),
SysOperationDisplayOrderAttribute('3'),
SysOperationHelpTextAttribute(literalStr("@EQN:Salesorder"))
]
public SalesId parmSalesId(SalesId _salesId = salesId)
{
salesId = _salesId;
return salesId;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('@DNR6238'),
SysOperationLabelAttribute('@DNR6238'),
SysOperationDisplayOrderAttribute('4'),
SysOperationHelpTextAttribute(literalStr("@DNR6238"))
]
public SalesId parmRentalOrder(SalesId _rentalId = rentalId)
{
rentalId = _rentalId;
return rentalId;
}
public boolean validate()
{
boolean isValid = true;
/* if (!custAccount)
{
isValid = checkFailed(strFmt("@SYS84753", custAccount));
}*/
return isValid;
}
}
==============================================================
class EQNRecalculateExposureController extends SysOperationServiceController
{
Common callerRecord;
void new()
{
super();
this.parmClassName(classStr(EQNRecalculateExposureService));
this.parmMethodName(methodStr(EQNRecalculateExposureService, process));
this.parmDialogCaption('@EQN:RecalculateExposure');
}
protected object initializeserviceParameter(DictMethod dictMethod, int parameterIndex)
{
object ret;
EQNRecalculateExposureContract dc;
ret = super(dictMethod,parameterIndex);
if(ret is EQNRecalculateExposureContract)
{
dc = ret;
dc.parmOrderTypes(EQNOrderTypes::Both);
}
return ret;
}
public static void main(Args _args)
{
EQNRecalculateExposureController controller;
controller = new EQNRecalculateExposureController();
controller.parmShowDialog(true);
EQNRecalculateExposureContract contract;
controller.startOperation();
}
public LabelType parmDialogCaption(LabelType _dialogCaption = "")
{
LabelType caption;
caption = "@EQN:RecalculateExposure";
return caption;
}
public boolean canGoBatch()
{
return true;
}
public Common parmCallerRecord(Common _callerRecord = callerRecord)
{
callerRecord = _callerRecord;
return callerRecord;
}
/// Refreshes the calling form data source.
protected void refreshCallerRecord()
{
FormDataSource callerDataSource;
if (this.parmCallerRecord() && this.parmCallerRecord().dataSource())
{
callerDataSource = this.parmCallerRecord().dataSource();
callerDataSource.research(true);
}
}
}
========================================================================
class EQNRecalculateExposureService extends SysOperationServiceBase
{
CustAccount custAccount;
Salesid salesId,rentalId;
EQNOrderTypes orderTypes;
public void process(EQNRecalculateExposureContract _contract)
{
orderTypes = _contract.parmOrderTypes();
custAccount = _contract.parmCustAccount();
salesId = _contract.parmSalesId();
rentalId = _contract.parmRentalOrder();
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
EQNRecalculateExposureService::recalculation(orderTypes,salesId,rentalId,custAccount);
//EQNRecalculateExposureService::createInvoiceJournal();
}
}
/* public static void createInvoiceJournal()
{
LedgerJournalName ledgerJournalName;
LedgerJournalTable ledgerJournalTable;
LedgerJournalTrans ledgerJournalTrans;
LedgerJournalTrans_Project ledgerJournalTrans_Project;
NumberSequenceTable numberSequenceTable;
ledgerJournalCheckPost ledgerJournalCheckPost;
ProjLinePropertySetup projLinePropertySetup;
DirPersonUser personUser;
HcmWorker worker;
boolean priceFound = false;
CostPrice costPriceMST;
ProjPostCostJournal projPostCostJournal;
ResourceView resourceView;
NumberSeq numberseq;
Amount amount = 100;
boolean result = false;
TransDate invoiceDate = _date;
ttsbegin;
ledgerJournalName = LedgerJournalName::find("APInvoice");
if(ledgerJournalName)
{
ledgerJournalTable.JournalName = ledgerJournalName.JournalName;
ledgerJournalTable.initFromLedgerJournalName();
ledgerJournalTable.JournalNum = JournalTableData::newTable(ledgerJournalTable).nextJournalId();
ledgerJournalTable.Name = ledgerJournalName.Name;
ledgerJournalTable.JournalType = LedgerJournalType::VendInvoiceRegister;
ledgerJournalTable.insert();
if(ledgerJournalTable)
{
select NumberSequence from numberSequenceTable
where NumberSequenceTable.RecId == ledgerJournalName.NumberSequenceTable;
numberseq = NumberSeq::NewGetVoucherFromCode(numberSequenceTable.NumberSequence);
ledgerJournalTrans.initValue();
ledgerJournalTrans.JournalNum = ledgerJournalTable.JournalNum;
ledgerJournalTrans.Voucher = numberseq.voucher();
ledgerJournalTrans.TransDate = today();
ledgerJournalTrans.Qty = 1;
ledgerJournalTrans.AccountType = LedgerJournalACType::Vend;
ledgerJournalTrans.OffsetAccountType = LedgerJournalACType::Ledger;
container account = ["401200-DEMF-000000079------"];
//ledgerJournalTrans.parmLedgerDimension(AxdDimensionUtil::getla(account));
LedgerDimensionAccount ledgerDim = DimensionStorage::get getDynamicAccount("401200-DEMF-000000079------", LedgerJournalACType::Cust);
//LedgerJournalTrans.LedgerDimension = DimensionAttributeValueCombination::find(ledgerDim).Recid;
// LedgerJournalTrans.DefaultDimension = Default Dimension;
// ledgerJournalTrans.parmOffsetAccount(con2Str(account, '-'),ledgerJournalTrans.OffsetAccountType);//(_facility);
ledgerJournalTrans.parmOffsetAccount("1010",ledgerJournalTrans.OffsetAccountType);//(_facility);
//ledgerJournalTrans.parmOffsetDefaultDimension(
//ledgerJournalTrans.LedgerDimension = 5637145350;
ledgerJournalTrans.TransactionType = 14;// LedgerTransType::Payment;
ledgerJournalTrans.CurrencyCode = "USD";
ledgerJournalTrans.Invoice = ledgerJournalTrans.JournalNum;
ledgerJournalTrans.Txt = strFmt("AP Invoice");
ledgerJournalTrans.Approved = NoYes::Yes;
if(amount> 0)
{
ledgerJournalTrans.AmountCurDebit = amount;
}
else
{
ledgerJournalTrans.AmountCurCredit = abs(amount);
}
ledgerJournalTrans.Company = strUpr(curExt());
ledgerJournalTrans.OffsetCompany = strUpr(curExt());
select firstonly personUser where personUser.User == curUserId()
join worker
where worker.Person == personUser.PersonParty;
ledgerJournalTrans.Approver = worker.RecId ? worker.RecId : 5637145326;// worker.RecId;
//ledgerJournalTrans.PostingProfile = 'GEN';
ledgerJournalTrans.parmAccount(_Account,ledgerJournalTrans.AccountType);
ledgerJournalTrans.insert();
result = true;
}
}
ttscommit;
}*/
public static void recalculation(EQNOrderTypes _orderTypes,SalesId _salesId, SalesId _rentalId,accountNum _custacc)
{
Query query;
QueryRun qr;
SalesTable salesTable;
SalesLine salesline;
SalesId tmpSalesId;
Amount financialriskperorder,financialriskperline = 0,misccharges =0;
boolean recalculationstarted = false;
EQNCreditExposureCalculations eqncreditExposureCalculations = new EQNCreditExposureCalculations();
query = eqncreditExposureCalculations.buildQuery(_orderTypes,_salesId,_rentalId,_custacc);
qr = new QueryRun(query);
while (qr.next())
{
recalculationstarted = true;
salesTable = qr.get(tableNum(SalesTable));
boolean execute = true;
if(PaymTerm::find(salesTable.Payment,false).EQNExcludefromexposurecalculations)
{
execute = false;
}
if( salesTable.SalesPoolId == CustParameters::find().EQNExcludeFromExposure) // If sales table pool id is also equal we need to skip it.
{
execute = false;
}
if(execute)
{
financialriskperorder = EQNCreditExposureCalculations::financalExposurePerOrder(_orderTypes,salesTable);
misccharges = EQNCreditExposureCalculations::calculateMarkupTrans(salesTable.SalesId);
financialriskperorder = financialriskperorder+misccharges;
if(financialriskperorder>0)
EQNCreditExposureCalculations::insertEQNFINCustExposureTrans(salesTable,financialriskperorder);
}
else
{
EQNCreditExposureCalculations::delEqnCustExposureTrans(salesTable);
}
}
if(!recalculationstarted)
info("Batch has no records to execute with given criteria");
else
info("Financial risk for queried orders is Calculated in batch");
}
}
==============================================================
class EQNRecalculateExposureUIBuilder extends SysOperationAutomaticUIBuilder
{
Dialog dlg;
DialogField dialogCustAcc;
DialogField dialogSalesId;
DialogField dialogRentalId;
DialogField dialogOrderTypes;
EQNRecalculateExposureContract contract;
public void build()
{
DialogGroup dlgGrp;
contract = this.dataContractObject();
//get the current dialog
dlg = this.dialog();
dialogCustAcc = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmCustAccount),contract);
dialogCustAcc.value('');
dialogSalesId = this.addDialogField(methodStr(EQNRecalculateExposureContract,parmSalesId),contract);
dialogSalesId.value('');
dialogRentalId = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmRentalOrder),contract);
dialogRentalId.value('');
dialogOrderTypes = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmOrderTypes),contract);
}
public void run()
{
try
{
}
catch (Exception::Deadlock)
{
retry;
}
}
public void enableBasedOnOrderTypes(FormComboBoxControl _orderTypes)
{
EQNOrderTypes orderTypes;
switch(dialogOrderTypes.value())
{
case (EQNOrderTypes::Both) :
{
dialogSalesId.enabled(true);
dialogRentalId.enabled(true);
break;
}
case (EQNOrderTypes::SalesOrder):
{
dialogSalesId.enabled(true);
dialogRentalId.enabled(false);
break;
}
case (EQNOrderTypes::RentalOrder):
{
dialogSalesId.enabled(false);
dialogRentalId.enabled(true);
break;
}
}
}
public void postBuild()
{
contract = this.dataContractObject();
dialogCustAcc = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmCustAccount));
dialogSalesId = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmSalesId));
dialogRentalId = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmRentalOrder));
dialogOrderTypes = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmOrderTypes));
//dialogOrderTypes.registerOverrideMethod(methodstr(FormComboBoxControl,modified), methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);
dialogOrderTypes.registerOverrideMethod(methodstr(FormComboBoxControl,selectionChange), methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);
}
public void postRun()
{
super();
//Register overrides for form control events
dialogCustAcc.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, custAccLookup),
this);
dialogSalesId.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, salesIdLookup),
this);
dialogRentalId.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, rentalIdLookup),
this);
/* dialogOrderTypes.registerOverrideMethod(
methodstr(FormComboBoxControl,modified),
methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);*/
}
public void SalesIdLookup(FormStringControl salesIdLookup)
{
Query query = new Query();
QueryBuildDataSource qbds_SalesTable;
SysTableLookup sysTableLookup;
// Create an instance of SysTableLookup with the current calling form control.
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesTable), salesIdLookup);
// Add fields to be shown in the lookup form.
sysTableLookup.addLookupfield(fieldNum(SalesTable,SalesId));
qbds_SalesTable = query.addDataSource(tableNum(SalesTable));
//qbds_SalesTable.addRange(fieldnum(SalesTable, SalesStatus)).value(strfmt('!%1,!%2',enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
qbds_SalesTable.addRange(fieldNum(SalesTable,SalesType)).value(enum2str(SalesType::Sales));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
}
public void RentalIdLookup(FormStringControl rentalIdLookup)
{
Query query = new Query();
QueryBuildDataSource qbds_SalesTable;
QueryBuildRange qbrSalesType;
SysTableLookup sysTableLookup;
// Create an instance of SysTableLookup with the current calling form control.
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesTable), rentalIdLookup);
// Add fields to be shown in the lookup form.
sysTableLookup.addLookupfield(fieldNum(SalesTable,SalesId));
qbds_SalesTable = query.addDataSource(tableNum(SalesTable));
//qbds_SalesTable.addRange(fieldnum(SalesTable, SalesStatus)).value(strfmt('!%1,!%2',enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
qbds_SalesTable.addRange(fieldNum(SalesTable,SalesType)).value(enum2str(SalesType::RORRental));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
}
public void custAccLookup(FormStringControl custAcclookup)
{
Query query = new Query();
QueryBuildDataSource qbds_CustTable;
SysTableLookup sysTableLookup;
sysTableLookup = SysTableLookup::newParameters(tableNum(CustTable), custAcclookup);
sysTableLookup.addLookupfield(fieldNum(CustTable,AccountNum));
sysTableLookup.addLookupMethod(tableMethodStr(CustTable,Name));
qbds_CustTable = query.addDataSource(tableNum(CustTable));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
//CustTable::lookupCustomer(custAcclookup, curExt());
}
}
=======================================================================
[ExtensionOf(classStr(SalesFormLetterProvider))]
Final class EQNSalesFormLetterProvider_Extension
{
protected boolean creditMaxOk(SalesTotals _salesTotals)
{
CustCreditLimit custCreditLimit;
boolean ret = next creditMaxOk(_salesTotals);
if(_salesTotals is SalesTotals_ParmTransInvoice)
{
EQNCreditExposureCalculations::delEqnCustExposureTrans(SalesTable);
}
return ret;
}
public boolean checkJournal()
{
boolean ret = next checkJournal();
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
ret = FINCheckCreditLimit::checkCreditLimit_Sales(SalesTable, true, true);
return ret;
}
}
===================================================================
[ExtensionOf(tableStr(TmpCustVendTrans))]
Final class EQNTmpCustVendTrans_Extension
{
static container custCalcSalesTotals(CustAccount _custAccount,
CurrencyCode _currencyCode,
AgreementHeaderExtRecId_RU _agreementHeaderExtRecId
)
{
container con;
CustCreditLimit custCreditLimit;
SalesTotals salesTotals;
SalesTable salesTable;
// <GEERU>
SalesTable_RU salesTableRU;
// </GEERU>
AmountMST mcrCreditCardBalance = 0;
con = next custCalcSalesTotals(_custAccount,_currencyCode ,_agreementHeaderExtRecId);
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
Amount custexposureamt;
salesTable.CustAccount = _custAccount;
salesTable.initFromCustTable();
// <GEERU>
salesTableRU.AgreementHeaderExt_RU = _agreementHeaderExtRecId;
salesTable.packSalesTable_RU(salesTableRU);
// </GEERU>
salesTotals = SalesTotals::construct(salesTable);
// <GEERU>
salesTotals.parmCheckAgreementLimit_RU(_agreementHeaderExtRecId != 0);
// </GEERU>
salesTotals.calc();
custCreditLimit = CustCreditLimit::construct(salesTable);
// <GEERU>
custCreditLimit.parmCheckAgreementLimit_RU(_agreementHeaderExtRecId != 0);
// </GEERU>
//Return credit card balance as well.
if (isConfigurationkeyEnabled(configurationKeyNum(MCRCallCenter)))
{
mcrCreditCardBalance = custCreditLimit.MCRBalanceCreditCard();
}
custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_custAccount);
return [salesTotals.displayFieldsCurrency(_currencyCode)] +
[custexposureamt] +
[custCreditLimit.EQNuseEstimated()] +
[mcrCreditCardBalance];
}
else
return con;
}
static TmpCustVendTrans custTransBalanceCurrency(
CustAccount _accountNum,
boolean _addTotalAndCredit,
CurrencyCode _currencyCode,
BankLCBankDocument _bankLCBankDocument)
{
TmpCustVendTrans tmpCustVendTrans = null;
CustTrans custTrans;
CustTransOpen custTransOpen;
BankLCCustTrans bankLCCustTrans;
AmountMST sumAmountMST;
AmountMST creditRemain;
AmountMST creditLimit;
container displayFields;
AmountMST balanceEstimate;
AmountMST balanceCreditCard;
boolean useEstimated;
tmpCustVendTrans = next custTransBalanceCurrency(_accountNum,_addTotalAndCredit ,_currencyCode,_bankLCBankDocument);
if(CustParameters::find(false).FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
tmpCustVendTrans = null;
sumAmountMST = 0;
creditRemain = 0;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
container conRecIds;
if (_bankLCBankDocument == BankLCBankDocumentType::All)
{
while select CurrencyCode
from custTrans
group by CurrencyCode
where custTrans.AccountNum == _accountNum
join sum(AmountCur), sum(AmountMST)
from custTransOpen
where custTransOpen.RefRecId == custTrans.RecId
/*join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes*/
{
tmpCustVendTrans = TmpCustVendTrans::insertTmpCustVendTransForCustBalance(
tmpCustVendTrans,
_accountNum,
custTrans,
custTransOpen);
sumAmountMST += tmpCustVendTrans.AmountMst;
}
}
else
{
while
select CurrencyCode
from custTrans
group by CurrencyCode
where custTrans.AccountNum == _accountNum
join BankLCExportLine from bankLCCustTrans
where custTrans.BankLCExportLine == bankLCCustTrans.BankLCExportLine
&& bankLCCustTrans.BankDocumentType == BankLCCustVendTransHelper::convertDocumentType(_bankLCBankDocument)
join sum(AmountCur), sum(AmountMST)
from custTransOpen
where custTransOpen.RefRecId == custTrans.RecId
{
tmpCustVendTrans = TmpCustVendTrans::insertTmpCustVendTransForCustBalance(
tmpCustVendTrans,
_accountNum,
custTrans,
custTransOpen);
sumAmountMST += tmpCustVendTrans.AmountMst;
}
}
if (_addTotalAndCredit)
{
tmpCustVendTrans.data(TmpCustVendTrans::populateLineTotal(sumAmountMST));
tmpCustVendTrans.insert();
// Add line with packing slip or orderd amount
if (CustParameters::find().CreditMaxCheck != TypeOfCreditmaxCheck::None)
{
//Return back the credit card balance.
[displayFields, balanceEstimate, useEstimated, balanceCreditCard] = TmpCustVendTrans::custCalcSalesTotals(_accountNum, _currencyCode);
TmpCustVendTrans::insertTmpCustVendTransBasedOnTypeOfCreditmaxCheck(tmpCustVendTrans, balanceEstimate, useEstimated);
creditRemain -= TmpCustVendTrans::getAmountToDecreaseCreditRemaining(balanceEstimate, useEstimated);
//Display any unposted credit card amount
if (useEstimated && balanceCreditCard
&& isConfigurationkeyEnabled(configurationKeyNum(MCRCallCenter)))
{
tmpCustVendTrans.Txt = "@MCR20754";
tmpCustVendTrans.AmountMst = balanceCreditCard;
tmpCustVendTrans.insert();
//Add the credit card unposted back to the balance.
creditRemain += balanceCreditCard;
}
creditLimit = FINCheckCreditLimit::maxCreditLimit(_accountNum);
if (creditLimit)
{
creditRemain += conpeek(displayFields, TradeTotals::posFreeValue());
}
else
{
creditRemain = 0;
}
Amount balanceMST,custexposureamt;
CustTable custTbl;
creditRemain = 0;
custTbl = (CustTable::find(_accountNum,false));
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
balanceMST = custTbl.openBalanceMST()+creditExposureCalculations.custorderedbal(custTbl);
//balanceMST = EQNCreditExposureCalculations::openBalanceMST(custTbl)+creditExposureCalculations.custorderedbal(custTbl);
creditRemain = creditLimit - custexposureamt -balanceMST;
tmpCustVendTrans.data(TmpCustVendTrans::populateLineCreditLimit(creditLimit, false));
tmpCustVendTrans.insert();
tmpCustVendTrans.data(TmpCustVendTrans::populateLineCreditRemain(creditRemain, false));
tmpCustVendTrans.insert();
}
}
}
return tmpCustVendTrans;
}
}
======================================================================
[ExtensionOf(classStr(FINCheckCreditLimit))]
Final class FINCheckCreditLimitEQN_Extension
{
public static client server void checkCreditLimit_Cust(CustAccount _custacc)
{
boolean ret = true;
CustTable custtable;
AmountMST openBalanceMST;
Amount creditLimit,custexposureamt=0,excessamt;
custTable = CustTable::find(_custacc,false);
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
creditLimit = FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum);
//custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_custacc);
excessamt = openBalanceMST+custexposureamt+-creditLimit;
if (openBalanceMST+custexposureamt >= creditLimit)
{
info(strfmt("@EQN:CustCreditlimitError",openBalanceMST,creditLimit,excessamt)); }
else
{
Percent percent;
if(creditLimit >0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
info(strfmt("@EQN:CustCreditlimitPercentWarning",openBalanceMST,CustParameters::find(false).EQNPctOfCreditLimit,creditLimit,excessamt));
}
}
public static client server boolean checkCreditLimit_Sales(SalesTable _salesTable,
boolean _onlyWarning,
boolean _showMsg)
{
CustTable custTable;
AmountMST openBalanceMST;
Amount creditLimit,financialriskperorder,custexposureamt=0,excessamt,misccharges;
EQNFINCustExposureTrans eqncustExposuretransold;
EQNOrderTypes ordertypes;
FINCreditLimitException finCreditLimitException;
FINModule finModule;
boolean ret = next checkCreditLimit_Sales(_salesTable,_onlyWarning,_showMsg);
boolean execute = true;
if(PaymTerm::find(_salesTable.Payment,false).EQNExcludefromexposurecalculations)
{
execute = false;
}
if( _salesTable.SalesPoolId == CustParameters::find().EQNExcludeFromExposure) // If sales table pool id is also equal we need to skip it.
{
execute = false;
}
if (CustParameters::find().FINCustCreditCheckType != FINCustCreditCheckType::BasedonExposure)//basedonexposure need to be added
{
execute = false;
}
if (execute)//basedonexposure need to be added
{
ret = true;
String10 salestype;
custTable = _salesTable.custTable_InvoiceAccount();
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
select eqncustExposuretransold
where eqncustExposuretransold.EQNSalesId == _salesTable.SalesId;
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
if(eqncustExposuretransold.EQNExposureValue)
openBalanceMST = openBalanceMST-eqncustExposuretransold.EQNExposureValue;
creditLimit = FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum);
if(_salesTable.SalesType == SalesType::Sales)
{
ordertypes = EQNOrderTypes::SalesOrder;
salestype = "@EQN:Sales";
finModule = FINModule::SalesOrder;
}
else if(_salesTable.SalesType == SalesType::RORRental)
{
ordertypes = EQNOrderTypes::RentalOrder;
SalesType = "@EQN:Rental";
finModule = FINModule::RentalOrder;
}
financialriskperorder = EQNCreditExposureCalculations::financalExposurePerOrder(ordertypes,_salesTable);
misccharges = EQNCreditExposureCalculations::calculateMarkupTrans(_salesTable.SalesId);
financialriskperorder = financialriskperorder+misccharges;
//custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_salesTable.CustAccount);
excessamt = openBalanceMST+custexposureamt+financialriskperorder-creditLimit;
if (openBalanceMST+financialriskperorder >= creditLimit)
{
if (FINCheckCreditLimit::hasCreditLimitException(_salesTable.CustAccount, finModule, _salesTable.SalesId))
{
info(strfmt("@EQN:salesconfirmerror",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,salestype));
}
else
{
error(strfmt("@EQN:salesconfirmerror",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,salestype));
ret = false;
}
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit>0)
percent=((openBalanceMST+financialriskperorder)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
info(strfmt("@EQN:salesconfirmwarning",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,CustParameters::find().EQNPctOfCreditLimit,salestype));
}
}
//}
if(ret)
{
EQNCreditExposureCalculations::insertEQNFINCustExposureTrans( _salesTable,financialriskperorder);
}
}
return ret;
}
public static client server boolean checkCreditLimit_WPPline(WPPWorkOrderLine _workOrderLine)
{
boolean ret = true;
WPPParameters wppParameters;
CustTable custTable;
AmountMST openBalanceMST;
Amount creditLimit,custexposureamt,excessamt;
WPPWorkOrderTable wppWorkorderTable;
if(ProjGroup::find((ProjTable::find(_workOrderLine.ProjId,false).ProjGroupId),FALSE).FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit != EQNWPPMessagewhenexceedingcreditlimit::Review)
{
wppWorkorderTable = WPPWorkOrderTable::find(_workOrderLine.WorkOrderId,false);
custTable = CustTable::find(wppWorkorderTable.CustVendAccount);
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
creditLimit = FINCheckCreditLimit::maxCreditLimit(wppWorkorderTable.CustVendAccount);
excessamt = openBalanceMST+custexposureamt-creditLimit;
wppParameters = WPPParameters::find(false);
if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit == EQNWPPMessagewhenexceedingcreditlimit::Error)
{
if (openBalanceMST >= creditLimit)
{
if (FINCheckCreditLimit::hasCreditLimitException(custTable.AccountNum,
FINModule::WPPWorkOrder,
_workOrderLine.WorkOrderId))
{
info(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
}
else
{
throw error(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
ret = false;
}
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit > 0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent=100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
return warning(strfmt("@EQN:WorkOrderexcesscreditwarning",openBalanceMST+custexposureamt,creditLimit,custTable.currency,excessamt,CustParameters::find().EQNPctOfCreditLimit));
}
}
}
else if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit == EQNWPPMessagewhenexceedingcreditlimit::Warning)
{
if (openBalanceMST >= creditLimit)
{
info(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
ret = false;
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit >0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
return warning(strfmt("@EQN:WorkOrderexcesscreditwarning",openBalanceMST+custexposureamt,creditLimit,custTable.currency,excessamt,CustParameters::find().EQNPctOfCreditLimit));
}
}
}
}
}
return ret;
}
}
======================================================================
class SalesCreateOrderEventhandler
{
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(SalesCreateOrder, SalesTable_CustAccount), FormControlEventType::Modified)]
public static void SalesTable_CustAccount_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl custacc = formRun.design(0).controlName("SalesTable_CustAccount");
if(custacc.valueStr() != "")
FINCheckCreditLimit::checkCreditLimit_Cust(custacc.valueStr());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(RORSalesCreateOrder, SalesTable_CustAccount), FormControlEventType::Modified)]
public static void RORSalesTable_CustAccount_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl custacc = formRun.design(0).controlName("SalesTable_CustAccount");
if(custacc.valueStr() != "")
FINCheckCreditLimit::checkCreditLimit_Cust(custacc.valueStr());
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
[PostHandlerFor(formStr(SalesTable), formMethodStr(SalesTable, init))]
public static void SalesTable_Post_init(XppPrePostArgs args)
{
FormRun initialFormRun;
Common initialFormRunRecord;
CustTable custTable;
initialFormRun= args.getThis();
if (TradeFormHelper::isCalledFromForm(initialFormRun.args(), formStr(CustTable))
&& initialFormRun.args().record().TableId == tableNum(CustTable))
{
//initialFormRun = initialFormRun.args().caller() as FormRun;
initialFormRunRecord = initialFormRun.args().record();
//custTable = initialFormRun.args().record() as CustTable;
initialFormRunRecord = initialFormRun.args().record();
custTable = initialFormRunRecord;
if(custTable)
FINCheckCreditLimit::checkCreditLimit_Cust(custTable.AccountNum);
}
}
}
=================================================================
[ExtensionOf(classStr(WPPWorkOrderStatusUpdate))]
Final class WPPWorkOrderStatusUpdateEQN_Extension
{
protected boolean checkcreditlimitonWorkOrderline()
{
boolean ret;
ret = FINCheckCreditLimit::checkCreditLimit_WPPline(this.workOrderLine);
return ret;
}
protected void updateWorkOrderLine()
{
this.checkcreditlimitonWorkOrderline();
next updateWorkOrderLine();
}
}
{
//Enable and Disable field "Extra Calculationday" based on Enum value for the field "CreditCheckType".
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_FINCustCreditCheckType), FormControlEventType::Modified)]
public static void FormGroupControl1_FINCustCreditCheckType_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormComboBoxControl finCreditCheckType = formRun.design(0).controlName("FormGroupControl1_FINCustCreditCheckType");
FormIntControl extraCalculationDays = formRun.design(0).controlName("FormGroupControl1_EQNExtraCalculationDays");
if(finCreditCheckType.valueStr() == enum2str(FINCustCreditCheckType::BasedonExposure))
{
extraCalculationDays.enabled(true);
}
else
{
extraCalculationDays.enabled(false);
}
}
//Lookup for the Sales PoolId
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_EQNExcludeFromExposure), FormControlEventType::Lookup)]
public static void FormGroupControl1_EQNExcludeFromExposure_OnLookup(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl excludeFromExposure = formRun.design(0).controlName("FormGroupControl1_EQNExcludeFromExposure");
Query query = new Query();
QueryBuildDataSource qbds;
SysTableLookup sysTableLookup;
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesPool), sender);
sysTableLookup.addLookupfield(fieldNum(SalesPool,SalesPoolId));
sysTableLookup.addLookupfield(fieldNum(SalesPool, Name));
qbds = query.addDataSource(tableNum(SalesPool));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
//Lookup created for standardDayRateCode using existing Table reference lookup method
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(CustParameters, FormGroupControl1_EQNStandardDayRateCodeint), FormControlEventType::Lookup)]
public static void FormGroupControl1_EQNStandardDayRateCodeint_OnLookup(FormControl sender, FormControlEventArgs e)
{
CustParameterEventhandler::createLookup(sender);
}
private static void createLookup(FormReferenceGroupControl _ctrl)
{
SysReferenceTableLookup sysTableLookup = SysReferenceTableLookup::newParameters(tablenum(UnitOfMeasure), _ctrl);
Query query = new Query();
QueryBuildDataSource unitMeasureDS;
unitMeasureDS = query.addDataSource(tableNum(UnitOfMeasure));
unitMeasureDS.addRange(fieldNum(UnitOfMeasure,UnitOfMeasureClass)).value(SysQuery::value(UnitOfMeasureClass::Time));
sysTableLookup.addLookupfield(fieldNum(UnitOfMeasure,Symbol));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
}
======================================================================
class EQNCreditExposureCalculations
{
Amount openbalance,orderedAmt,totExposure,TotPercentExposure;
static Amount calculateMarkupTrans(SalesId _salesId)
{
AmountCur markupAmount,headermarkupamt,linemarkupamt,totTaxAmountCur,lineamount;
MarkupTrans markupTrans;
CurrencyExchangeHelper curCurrencyExchangeHelper;
SalesTable salesTable = SalesTable::find(_salesId);
SalesLine salesLine;
SalesTotals salestotals;
container cont;
// Code to calculate total tax for sales order inlucing charges tax-->
salesTotals = SalesTotals::construct(salesTable, SalesUpdate::All);
salesTotals.calc();
cont = salesTotals.displayFieldsCurrency(salesTotals.currencyCode());
totTaxAmountCur = conpeek(cont, TradeTotals::posTaxTotal());
// Code to calculate total tax for sales order inlucing charges tax<--
// Code to calculate total Charge for sales order header-->
while select markupTrans
where markupTrans.TransTableId == salesTable.TableId
&&markupTrans.TransRecId == salesTable.RecId
{
markupAmount = markupTrans.Value;
if (markupTrans.CurrencyCode != salesTable.CurrencyCode)
{
// To automatically conver amount Markup::calcMarkupAmount can be used
curCurrencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::primaryLedger(CompanyInfo::findDataArea(markupTrans.company()).RecId), systemDateGet());
markupAmount = curCurrencyExchangeHelper.calculateAccountingToTransaction(salesTable.CurrencyCode, markupAmount, true);
}
headermarkupamt =headermarkupamt+markupAmount;
}
// Code to calculate total Charge for sales order header <--
// Code to calculate total Charge for sales order lines-->
while select salesLine
where salesLine.SalesId == salesTable.SalesId
{
while select markupTrans
where markupTrans.TransTableId == salesLine.TableId
&&markupTrans.TransRecId == salesLine.RecId
{
markupAmount = Markup::calcTrans(markupTrans, salesLine.SalesQty, salesLine.LineAmount);
if (markupTrans.CurrencyCode != salesTable.CurrencyCode)
{
// To automatically conver amount Markup::calcMarkupAmount can be used
curCurrencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::primaryLedger(CompanyInfo::findDataArea(markupTrans.company()).RecId), systemDateGet());
markupAmount = curCurrencyExchangeHelper.calculateAccountingToTransaction(salesTable.CurrencyCode, markupAmount, true);
}
linemarkupamt = linemarkupamt+markupAmount;
}
}
// Code to calculate total Charge for sales order lines<--
markupAmount = linemarkupamt+headermarkupamt;//Sum both line and Header Charges for Sales order
// Calculate Charge lines tax if we get tax > 0 for sales order-->
if(salesTable.InclTax == noyes::No && totTaxAmountCur >0)// Calculate Charge lines tax if we get tax > 0 for sales order
{
TaxGroupHeading taxgroup;
TaxGroupData taxgroupdata;
select * from taxgroupdata
where taxgroupdata.TaxGroup == salesTable.TaxGroup;
real taxpercent =taxgroupdata.ShowTaxValue();
markupAmount =markupAmount+(markupAmount*taxgroupdata.ShowTaxValue())/100;//Add tax amount to Charge lines when Salestable Includetax field is set to no.
}
// Calculate Charge lines tax if we get tax > 0 for sales order-->
return markupAmount;
}
public Amount custorderedbal(CustTable _custTbl)
{
CustCreditLimit custCreditLimit;
SalesTable salesTable;
SalesTotals salesTotals;
salesTable.CustAccount = _custTbl.AccountNum;
salesTable.initFromCustTable();
salesTotals = SalesTotals::construct(salesTable);
salesTotals.calc();
custCreditLimit = CustCreditLimit::construct(salesTable);
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
orderedAmt = EQNFINCustExposureTrans::CustomerExposure(_custTbl.AccountNum);
}
else
orderedAmt = custCreditLimit.balanceEstimate();
return orderedAmt;
}
//Calculates Financial Exposure for the Current Order.
public static client server Amount financalExposurePerOrder(EQNOrderTypes _orderTypes,SalesTable _salesTable)
{
Amount financialriskperorder,financialriskperline;
Query query;
QueryRun qr;
SalesTable salesTable;
SalesLine salesLine;
EQNCreditExposureCalculations fincheckcreditlimit = new EQNCreditExposureCalculations();
while select salesLine
where salesLine.SalesId ==_salesTable.SalesId
{
Amount lineamount=0,TaxAmountCur=0;
financialriskperline =0;
if(salesline.SalesQty-salesline.invoicedInTotal()== 0)
{
financialriskperline =0;
continue;
}
if(salesLine.RORTradeType == RORTradeType::Rental || salesLine.RORTradeType == RORTradeType::SubRental)
{
if(salesLine.INVInvoiceProfileId != CustParameters::find().EQNINVInvoiceProfileSetRate)
financialriskperline = fincheckcreditlimit.rentalTypeCreditExposure(salesLine,_salesTable.CustAccount);//(salesline.SalesQty-salesline.invoicedInTotal()) * fincheckcreditlimit.rentalTypeCreditExposure(salesLine,_salesTable.CustAccount);
else
{
lineamount = salesLine.RORRentalLine::editLineAmount(false,salesLine.LineAmount);
if(SalesTable::find(salesLine.SalesId).InclTax == noyes::No)
{
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
financialriskperline = lineamount;
}
}
else if (salesLine.RORTradeType == RORTradeType::SalesPurch)
{
if(_salesTable.SalesType ==SalesType::RORRental)
{
lineamount = salesLine.RORRentalLine::editLineAmount(false,salesLine.LineAmount);
if(salesline.invoicedInTotal()>0)
{
qty invoicedqty = salesline.invoicedInTotal();
lineamount = (lineamount/salesline.SalesQty)*(salesline.SalesQty-invoicedqty);//Get line amount for only uninvoiced lines
}
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
financialriskperline = lineamount;
}
else
{
qty invoicedqty = salesline.invoicedInTotal();
if(salesline.SalesQty-salesline.invoicedInTotal()>0)
{
if(salesline.lineDisc > 0)
lineamount = salesLine.SalesPrice-salesline.lineDisc;
if(salesLine.LinePercent >0)
lineamount = salesLine.SalesPrice - ((salesLine.SalesPrice*salesLine.LinePercent)/100);
if(salesline.lineDisc == 0 && salesLine.LinePercent == 0)
lineamount = salesLine.SalesPrice;//salesLine.LineAmount;
if(SalesTable::find(salesLine.SalesId).InclTax == noyes::No)
{
//TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, salesLine.LineAmount, TaxModuleType::Sales);
TaxAmountCur=Tax::calcTaxAmount(salesLine.TaxGroup, salesLine.TaxItemGroup, Systemdateget(), salesLine.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
financialriskperline = (salesline.SalesQty-salesline.invoicedInTotal()) * lineamount;
}
//financialriskperline = financialriskperline +TaxAmountCur;
}
}
financialriskperorder = financialriskperorder + financialriskperline;
}
//fincheckcreditlimit.insertEQNFINCustExposureTrans(_salesTable,financialExposurePerOrder);
return financialriskperorder;
}
public static void delEqnCustExposureTrans(SalesTable _salesTable)
{
SalesLine salesline;
EQNFINCustExposureTrans finCustExposureTrans = null;
select sum(REMAINSALESPHYSICAL) from salesline where salesline.SALESID == _salesTable.SalesId;
if(salesline.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == _salesTable.SalesId;
}
}
//Insert Financial Exposure for the Current Order in to EQNFINCustExposureTrans.
public static client server void insertEQNFINCustExposureTrans(SalesTable _salesTable,Amount financialriskAmt)
{
EQNFINCustExposureTrans finCustExposureTrans =null;
finCustExposureTrans = EQNFINCustExposureTrans::find(_salesTable.SalesId,true);
if(finCustExposureTrans)
{
ttsbegin;
finCustExposureTrans.EQNExposureValue = financialriskAmt;
finCustExposureTrans.update();
ttscommit;
}
else
{
finCustExposureTrans.EQNCurrency = _salesTable.CurrencyCode;
finCustExposureTrans.EQNExposureValue = financialriskAmt;
finCustExposureTrans.EQNProspectAccount = _salesTable.CustAccount;
finCustExposureTrans.EQNSalesId = _salesTable.SalesId;
if(_salesTable.SalesType == SalesType::Sales)
finCustExposureTrans.EQNSalesType = Eqnordertypes::SalesOrder;
if(_salesTable.SalesType == SalesType::RORRental)
finCustExposureTrans.EQNSalesType = Eqnordertypes::RentalOrder;
finCustExposureTrans.insert();
}
}
public int workingdaysIncalendar(CalendarId _calendarId,int days)
{
WorkCalendarSched workCalendarSched;
date start;
date end;
counter workingdays;
counter totaldays;
CalendarId primCalendar=_calendarId;
start=today();
end= today()+days;
workCalendarSched = new workCalendarSched();
while(start<end)
{
if(workCalendarSched.isdateopen(primCalendar,start)==true)
{
workingdays++;
}
start++;
}
return workingdays;
}
//Calculation of financial exposure for Rental order type
public Amount rentalTypeCreditExposure(SalesLine _salesline, accountNum _custacc)
{
Days creditExposurePeriod,paymentdays,expectedRentalPeriod,rentaldayInExposure;
TransDate estimatedoffrentdate,calDate;
CustParameters custParameters;
Amount rentalLineFinancialRisk=0,ratePerRentalDay=0;
PaymTerm PaymTerm;
RORRentalDateTimes rentalDateTimes;
INVInvoicePeriod invInvoicePeriod;
real chargeableDays=0,unitconversion=0,unitconversionfinal=0,workingdays=0,unitval;
Amount lineamount=0,TaxAmountCur=0;
custParameters = CustParameters::find(false);
rentalDateTimes = RORRentalDateTimes::findReference(_salesline.TableId,_salesline.RecId,false);
paymentdays = PaymTerm::find(SalesTable::find(_salesline.SalesId).payment).NumOfDays;
select * from invInvoicePeriod
where invInvoicePeriod.PeriodStatus == INVPeriodStatus::Uninvoiced
&& invInvoicePeriod.RefRecId == _salesline.RecId
&& invInvoicePeriod.RefTableId == _salesline.TableId;
if(!invInvoicePeriod.RecId)
return 0;
if(DateTimeUtil::date(rentalDateTimes.OffRentDateTime)!= dateNull())
estimatedoffrentdate = DateTimeUtil::date(rentalDateTimes.OffRentDateTime);
else
estimatedoffrentdate = DateTimeUtil::date(rentalDateTimes.ExpectedOffRentDateTime);
select firstonly invInvoicePeriod
order by RecId desc
where invInvoicePeriod.RefRecId == _salesline.RecId
&& invInvoicePeriod.RefTableId == _salesline.TableId
&& (invInvoicePeriod.PeriodStatus == INVPeriodStatus::FullyInvoiced) || (invInvoicePeriod.PeriodStatus == INVPeriodStatus::PartiallyInvoiced);
if(invInvoicePeriod)
{
if(DateTimeUtil::date(invInvoicePeriod.PeriodEndDateTime) > today())
calDate = DateTimeUtil::date(invInvoicePeriod.PeriodEndDateTime);
else
calDate = today();
if(DateTimeUtil::date(rentalDateTimes.OnRentDateTime) > calDate)
calDate = DateTimeUtil::date(rentalDateTimes.OnRentDateTime);
}
else
{
if(DateTimeUtil::date(rentalDateTimes.OnRentDateTime) > today())
calDate = DateTimeUtil::date(rentalDateTimes.OnRentDateTime);
else
calDate = today();
}
expectedRentalPeriod = estimatedoffrentdate-calDate+1;
if(paymentdays+custParameters.EQNExtraCalculationDays > expectedRentalPeriod)
rentaldayInExposure = expectedRentalPeriod;
else
rentaldayInExposure = paymentdays+custParameters.EQNExtraCalculationDays;
UnitOfMeasure unitofmeasure,unitofmeasure1;
select unitofmeasure
where unitofmeasure.RecId == _salesline.RORPriceTimeUnit;
select unitofmeasure1
where unitofmeasure1.RecId == custParameters.EQNStandardDayRateCodeint;
unitconversion = UnitOfMeasureConverter::convert(rentaldayInExposure,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
NoYes::No,
NoYes::No);
unitval = UnitOfMeasureConverter::convert(1.0,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
NoYes::No,
NoYes::No);
workingdays = this.workingdaysIncalendar(_salesline.RORCalendarId,unitconversion);
unitconversionfinal = UnitOfMeasureConverter::convert(workingdays,
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure1.Symbol),
UnitOfMeasure::unitOfMeasureIdBySymbol(unitofmeasure.Symbol),
NoYes::No,
NoYes::No);
chargeableDays = unitconversionfinal;
if(SalesTable::find(_salesline.SalesId).InclTax == noyes::No)
{
RORRentalLine rorRentalline;
select rorRentalline
where rorRentalline.InventTransId == _salesline.InventTransId;
lineamount = _salesline.RORRentalLine::editLineAmount(false,_salesline.LineAmount);//_salesline.RORRentalGrossAmount;//RORRentalLine::editLineAmount(false,_salesline.LineAmount);
//lineamount = _salesline.RORRentalLine::ROREditNetAmount(false,_salesline.LineAmount);
TaxAmountCur=Tax::calcTaxAmount(_salesline.TaxGroup, _salesline.TaxItemGroup, Systemdateget(), _salesline.CurrencyCode, lineamount, TaxModuleType::Sales);
lineamount = lineamount+TaxAmountCur;
}
Qty invoiced = _salesline.invoicedInTotal();
//lineamount = lineamount*(_salesline.SalesQty-_salesline.invoicedInTotal());//Value will not differ for rental line as salesline
ratePerRentalDay = lineamount/unitval;
rentalLineFinancialRisk = chargeableDays * ratePerRentalDay;
return rentalLineFinancialRisk;
}
//Build Query to calculate
public Query buildQuery(EQNOrderTypes type,SalesId _salesId, SalesId _rentalId, accountNum _custacc)
{
QueryBuildDataSource qdbsSO;
QueryBuildRange qbrsalesType,qbrsalesStatus,qbrsalesId,qbrrentalId,qbrcustAcc,qbrdocumentstatus;
Query query = new Query(queryStr (EQNRecalculateExposureQry));
qdbsSO = query.dataSourceTable(tablenum(SalesTable));
//Apply parameter ranges on query
qbrsalesType = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, SalesType));
qbrsalesStatus = query.dataSourceTable( tablenum (SalesTable)).findRange( fieldNum (SalesTable, SalesStatus));
if(!qbrsalesStatus)
query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, SalesStatus));
qbrdocumentstatus = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, DocumentStatus));
//qdbsSO.findRange( fieldNum (SalesTable, SalesStatus))
qbrdocumentstatus.value(strfmt('!%1,%2,%3,%4',enum2str(DocumentStatus::None),enum2str(DocumentStatus::Confirmation),enum2str(DocumentStatus::Invoice),enum2str(DocumentStatus::PackingSlip)));
if(type ==EQNOrderTypes ::Both)
qbrsalesType.value(strfmt('%1,%2',enum2str(SalesType::Sales),enum2str(SalesType::RORRental)));
else if(type == EQNOrderTypes::SalesOrder)
{
qbrsalesType.value(strfmt('%1',enum2str(SalesType::Sales)));
}
else if(type == EQNOrderTypes::RentalOrder)
{
qbrsalesType.value(strfmt('%1',enum2str(SalesType::RORRental)));
}
if(_salesId)
{
qbrsalesId = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, salesId));
qbrsalesId.value(_salesId);
//qbrsalesStatus.value(strfmt('!%1,%2,%3',enum2str(SalesStatus::Invoiced),enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
//qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(enum2str(SalesStatus::Invoiced));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(enum2str(SalesStatus::Canceled));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::None)));
}
if(_rentalId)
{
qbrrentalId = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, salesId));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::Invoiced)));
qdbsSO.addRange( fieldNum (SalesTable, SalesStatus)).value(SysQuery::valueNot(enum2str(SalesStatus::Canceled)));
//qbrsalesStatus.value(strfmt('!%1,!%2',enum2str(SalesStatus::Invoiced),enum2str(SalesStatus::Canceled)));
qbrrentalId.value(_rentalId);
}
if(_custacc)
{
qbrcustAcc = query.dataSourceTable( tablenum (SalesTable)).addRange( fieldNum (SalesTable, custAccount));
qbrcustAcc.value(_custacc);
}
return query;
}
public static AmountCur openBalanceCur(CustTable _custTable,
TransDate _fromDate = dateNull(),
TransDate _toDate = dateMax(),
TransDate _assessmentDate = dateNull(),
CurrencyCode _currency = CompanyInfoHelper::standardCurrency())
{
CustTrans custTrans;
CustTransOpen custTransOpen;
CustSettlement custSettlement;
AmountCur openBalanceCur;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
if (_assessmentDate)
{
//custSettlement = this.settlementBuffer();
select sum(SettleAmountCur)
from custSettlement
group by AccountNum
where custSettlement.AccountNum == _custTable.AccountNum
&& custSettlement.TransDate > _assessmentDate
join custTrans
where custTrans.RecId == custSettlement.TransRecId
&& custTrans.TransDate >= _fromDate
&& custTrans.TransDate <= _toDate
&& custTrans.CurrencyCode == _currency
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceCur = custSettlement.SettleAmountCur;
openBalanceCur += EQNCreditExposureCalculations::openBalanceCur(_custTable,_fromDate, _toDate, dateNull(), _currency);
}
else
{
select custTrans
where custTrans.AccountNum == _custTable.AccountNum
&& custTrans.CurrencyCode == _currency
join sum(AmountCur) from custTransOpen
group by AccountNum
where custTransOpen.RefRecId == custTrans.RecId
&& custTransOpen.TransDate >= _fromDate
&& custTransOpen.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceCur = custTransOpen.AmountCur;
}
return openBalanceCur;
}
public static AmountMST openBalanceMST(CustTable _custTable,
FromDate _fromDate = dateNull(),
ToDate _toDate = dateMax(),
TransDate _assessmentDate = dateNull())
{
CustTrans custVendTrans;
CustTransOpen custVendTransOpen;
CustSettlement custVendSettlement;
AmountMST openBalanceMST;
boolean hasAccess;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
if (_assessmentDate)
{
switch (custVendTrans.TableId)
{
case tableNum(CustTrans) :
hasAccess = hasFieldAccess(tableNum(CustSettlement), fieldNum(CustSettlement, SettleAmountMST));
hasAccess = hasAccess && hasFieldAccess(tableNum(CustSettlement), fieldNum(CustSettlement, ExchAdjustment));
break;
case tableNum(VendTrans) :
hasAccess = true;
break;
default :
hasAccess = false;
}
if (!hasAccess)
throw error("@SYS57330");
select sum(SettleAmountMST),sum(ExchAdjustment) from custVendSettlement
group by AccountNum
where custVendSettlement.AccountNum == _custTable.AccountNum &&
custVendSettlement.TransDate > _assessmentDate
join custVendTrans
where custVendTrans.RecId == custVendSettlement.TransRecId &&
custVendTrans.TransDate >= _fromDate &&
custVendTrans.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custVendTrans.Voucher
&& custInvoiceJour.InvoiceId == custVendTrans.Invoice
&& custInvoiceJour.InvoiceDate == custVendTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custVendTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceMST = custVendSettlement.SettleAmountMST + custVendSettlement.ExchAdjustment;
openBalanceMST += EQNCreditExposureCalculations::openBalanceMST(_custTable,_fromDate, _toDate);
}
else
{
select sum(AmountMST) from custVendTransOpen
where custVendTransOpen.AccountNum == _custTable.AccountNum &&
custVendTransOpen.TransDate >= _fromDate &&
custVendTransOpen.TransDate <= _toDate
join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custVendTrans.Voucher
&& custInvoiceJour.InvoiceId == custVendTrans.Invoice
&& custInvoiceJour.InvoiceDate == custVendTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custVendTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes;
openBalanceMST = custVendTransOpen.AmountMST;
}
return openBalanceMST;
}
}
===================================================================
class EQNCustBalanceListUIBuilder extends SrsReportDataContractUIBuilder
{
DialogField dialogexceededLimit;
DialogField dialogzeroBalance;
DialogField dialogasOfDate;
DialogField dialogpercent;
boolean enable;
EQNCustBalanceListContract contract;
public void build()
{
Dialog dialogLocal;
dialogLocal = this.dialog();
contract = this.dataContractObject();
utcDateTime myDateTime;
dialogasOfDate = this.addDialogField(methodStr(EQNCustBalanceListContract, parmAsOfDate),contract);
myDateTime = DateTimeUtil::applyTimeZoneOffset(myDateTime,DateTimeUtil::getUserPreferredTimeZone());
//contract.parmAsOfDate(today());
contract.parmAsOfDate(systemDateGet());
dialogasOfDate.value(today());
dialogasOfDate.enabled(False);
dialogpercent = this.addDialogField(methodStr(EQNCustBalanceListContract, parmPercent),contract);
dialogpercent.value(100);
dialogexceededLimit = this.addDialogField(methodStr(EQNCustBalanceListContract, parmExceededLimit),contract);
dialogzeroBalance = this.addDialogField(methodStr(EQNCustBalanceListContract, parmZeroBalance),contract);
controller.parmDialogCaption('@EQN:CustbalancelistbasedonCreditExposure');
}
public void getFromDialog()
{
contract = this.dataContractObject();
super();
}
/*public void initializeFields()
{
utcDateTime myDateTime;
contract = this.dataContractObject();
myDateTime = DateTimeUtil::applyTimeZoneOffset(myDateTime,DateTimeUtil::getUserPreferredTimeZone());
//contract.parmAsOfDate(today());
contract.parmAsOfDate(myDateTime);
}*/
}
==================================================================
[ExtensionOf(classStr(CustCreditLimit))]
Final class EQNCustCreditLimit_Extension
{
AmountMST EQNbalanceEstimate()
{
AmountMST balanceEstimate=0;
SalesTable localSalesTable;
QueryRun queryRun;
queryRun = new QueryRun(this.initQuery());
queryRun.query().dataSourceTable(tablenum(SalesTable)).fields().addField(fieldnum(SalesTable,Estimate),SelectionField::Sum);
// queryRun.query().dataSourceTable(tablenum(SalesTable)).addRange(fieldNum(SalesTable,SalesPoolId)).value(SYSQuery::valueNot(queryvalue(CustParameters::find().EQNExcludeFromExposure)));
while (queryRun.next())
{
if (queryRun.changed(tablenum(SalesTable)))
{
localSalesTable = queryRun.get(tablenum(SalesTable));
if(!PaymTerm::find(localSalesTable.Payment,false).EQNExcludefromexposurecalculations)
balanceEstimate += localSalesTable.Estimate;
}
}
return balanceEstimate;
}
public boolean check()
{
boolean ret = true;
// ret = next check();
CustCreditLimit thisclass = new CustCreditLimit(custtable);
TypeOfCreditmaxCheck typeOfCreditmaxCheck1;
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
typeOfCreditmaxCheck1 = typeOfCreditmaxCheck;
typeOfCreditmaxCheck = typeOfCreditmaxCheck::None;
}
ret = next check();
if(CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
ret = true;
//FINCheckCreditLimit::checkCreditLimit_Sales(SalesTable, true, CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure);*/
return ret;
}
public boolean EQNuseEstimated()
{
return (FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum));
}
}
===================================================================
class EQNCustomerCreditExposurePerOrderUIBuilder extends SrsReportDataContractUIBuilder
{
DialogField dialogexceededLimit;
DialogField dialogOrderType;
DialogField dialogpercent;
boolean enable;
EQNCustomerCreditExposurePerOrderContract contract;
public void build()
{
Dialog dialogLocal;
dialogLocal = this.dialog();
contract = this.dataContractObject();
dialogOrderType = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmOrderTypes),contract);
dialogpercent = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmPercent),contract);
dialogpercent.value(100);
dialogexceededLimit = this.addDialogField(methodStr(EQNCustomerCreditExposurePerOrderContract, parmExceededLimit),contract);
controller.parmDialogCaption('@EQN:CustomerCreditExposurePerOrder');
}
public void getFromDialog()
{
contract = this.dataContractObject();
super();
}
}
====================================================================
class EQNFINCustExposureTransDel
{
[FormControlEventHandler(formControlStr(SalesTable, buttonUpdateInvoice), FormControlEventType::Clicked)]
public static void buttonUpdateInvoice_OnClicked(FormControl sender, FormControlEventArgs e)
{
EQNFINCustExposureTrans finCustExposureTrans = null;
SalesTable ST;
FormRun formRun = sender.formRun() as FormRun;
FormDataSource ST_ds;
SALESLINE SL;
ST_ds = sender.formRun().dataSource(1);
ST = ST_ds.cursor();
select sum(REMAINSALESPHYSICAL) from SL where SL.SALESID == ST.SalesId;
if(SL.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == ST.SalesId;
}
}
[FormControlEventHandler(formControlStr(SalesTableListPage, buttonUpdateInvoice), FormControlEventType::Clicked)]
public static void buttonUpdateInvoiceLiatPage_OnClicked(FormControl sender, FormControlEventArgs e)
{
EQNFINCustExposureTrans finCustExposureTrans = null;
SalesTable ST;
FormRun formRun = sender.formRun() as FormRun;
FormDataSource ST_ds;
SALESLINE SL;
ST_ds = sender.formRun().dataSource(1);
ST = ST_ds.cursor();
select sum(REMAINSALESPHYSICAL) from SL where SL.SALESID == ST.SalesId;
if(SL.RemainSalesPhysical == 0)
{
delete_from finCustExposureTrans where finCustExposureTrans.EQNSalesId == ST.SalesId;
}
}
}
=======================================================================
[
DataContractAttribute
//,SysOperationContractProcessingAttribute(classStr(EQNRecalculateExposureUIBuilder))
]
class EQNRecalculateExposureContract implements SysOperationValidatable
{
CustAccount custAccount;
Salesid salesId,rentalId;
EQNOrderTypes orderTypes;
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('EQNOrderTypes'),
SysOperationLabelAttribute('@EQN:OrderTypes'),
SysOperationDisplayOrderAttribute('1'),
SysOperationHelpTextAttribute(literalStr("Select an Order Type"))
]
Public EQNOrderTypes parmOrderTypes(EQNOrderTypes _orderTypes = orderTypes)
{
orderTypes = _orderTypes;
Return orderTypes;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('CustAccount'),
SysOperationLabelAttribute('@EQN:CustomerAccount'),
SysOperationDisplayOrderAttribute('2'),
SysOperationHelpTextAttribute(literalStr("Customer Account no."))
]
public CustAccount parmCustAccount(CustAccount _custAccount = custAccount)
{
custAccount = _custAccount;
return custAccount;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('SalesId'),
SysOperationLabelAttribute('@EQN:Salesorder'),
SysOperationDisplayOrderAttribute('3'),
SysOperationHelpTextAttribute(literalStr("@EQN:Salesorder"))
]
public SalesId parmSalesId(SalesId _salesId = salesId)
{
salesId = _salesId;
return salesId;
}
[
//DataMemberAttribute(identifierStr(CustAccount))
DataMemberAttribute('@DNR6238'),
SysOperationLabelAttribute('@DNR6238'),
SysOperationDisplayOrderAttribute('4'),
SysOperationHelpTextAttribute(literalStr("@DNR6238"))
]
public SalesId parmRentalOrder(SalesId _rentalId = rentalId)
{
rentalId = _rentalId;
return rentalId;
}
public boolean validate()
{
boolean isValid = true;
/* if (!custAccount)
{
isValid = checkFailed(strFmt("@SYS84753", custAccount));
}*/
return isValid;
}
}
==============================================================
class EQNRecalculateExposureController extends SysOperationServiceController
{
Common callerRecord;
void new()
{
super();
this.parmClassName(classStr(EQNRecalculateExposureService));
this.parmMethodName(methodStr(EQNRecalculateExposureService, process));
this.parmDialogCaption('@EQN:RecalculateExposure');
}
protected object initializeserviceParameter(DictMethod dictMethod, int parameterIndex)
{
object ret;
EQNRecalculateExposureContract dc;
ret = super(dictMethod,parameterIndex);
if(ret is EQNRecalculateExposureContract)
{
dc = ret;
dc.parmOrderTypes(EQNOrderTypes::Both);
}
return ret;
}
public static void main(Args _args)
{
EQNRecalculateExposureController controller;
controller = new EQNRecalculateExposureController();
controller.parmShowDialog(true);
EQNRecalculateExposureContract contract;
controller.startOperation();
}
public LabelType parmDialogCaption(LabelType _dialogCaption = "")
{
LabelType caption;
caption = "@EQN:RecalculateExposure";
return caption;
}
public boolean canGoBatch()
{
return true;
}
public Common parmCallerRecord(Common _callerRecord = callerRecord)
{
callerRecord = _callerRecord;
return callerRecord;
}
/// Refreshes the calling form data source.
protected void refreshCallerRecord()
{
FormDataSource callerDataSource;
if (this.parmCallerRecord() && this.parmCallerRecord().dataSource())
{
callerDataSource = this.parmCallerRecord().dataSource();
callerDataSource.research(true);
}
}
}
========================================================================
class EQNRecalculateExposureService extends SysOperationServiceBase
{
CustAccount custAccount;
Salesid salesId,rentalId;
EQNOrderTypes orderTypes;
public void process(EQNRecalculateExposureContract _contract)
{
orderTypes = _contract.parmOrderTypes();
custAccount = _contract.parmCustAccount();
salesId = _contract.parmSalesId();
rentalId = _contract.parmRentalOrder();
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
EQNRecalculateExposureService::recalculation(orderTypes,salesId,rentalId,custAccount);
//EQNRecalculateExposureService::createInvoiceJournal();
}
}
/* public static void createInvoiceJournal()
{
LedgerJournalName ledgerJournalName;
LedgerJournalTable ledgerJournalTable;
LedgerJournalTrans ledgerJournalTrans;
LedgerJournalTrans_Project ledgerJournalTrans_Project;
NumberSequenceTable numberSequenceTable;
ledgerJournalCheckPost ledgerJournalCheckPost;
ProjLinePropertySetup projLinePropertySetup;
DirPersonUser personUser;
HcmWorker worker;
boolean priceFound = false;
CostPrice costPriceMST;
ProjPostCostJournal projPostCostJournal;
ResourceView resourceView;
NumberSeq numberseq;
Amount amount = 100;
boolean result = false;
TransDate invoiceDate = _date;
ttsbegin;
ledgerJournalName = LedgerJournalName::find("APInvoice");
if(ledgerJournalName)
{
ledgerJournalTable.JournalName = ledgerJournalName.JournalName;
ledgerJournalTable.initFromLedgerJournalName();
ledgerJournalTable.JournalNum = JournalTableData::newTable(ledgerJournalTable).nextJournalId();
ledgerJournalTable.Name = ledgerJournalName.Name;
ledgerJournalTable.JournalType = LedgerJournalType::VendInvoiceRegister;
ledgerJournalTable.insert();
if(ledgerJournalTable)
{
select NumberSequence from numberSequenceTable
where NumberSequenceTable.RecId == ledgerJournalName.NumberSequenceTable;
numberseq = NumberSeq::NewGetVoucherFromCode(numberSequenceTable.NumberSequence);
ledgerJournalTrans.initValue();
ledgerJournalTrans.JournalNum = ledgerJournalTable.JournalNum;
ledgerJournalTrans.Voucher = numberseq.voucher();
ledgerJournalTrans.TransDate = today();
ledgerJournalTrans.Qty = 1;
ledgerJournalTrans.AccountType = LedgerJournalACType::Vend;
ledgerJournalTrans.OffsetAccountType = LedgerJournalACType::Ledger;
container account = ["401200-DEMF-000000079------"];
//ledgerJournalTrans.parmLedgerDimension(AxdDimensionUtil::getla(account));
LedgerDimensionAccount ledgerDim = DimensionStorage::get getDynamicAccount("401200-DEMF-000000079------", LedgerJournalACType::Cust);
//LedgerJournalTrans.LedgerDimension = DimensionAttributeValueCombination::find(ledgerDim).Recid;
// LedgerJournalTrans.DefaultDimension = Default Dimension;
// ledgerJournalTrans.parmOffsetAccount(con2Str(account, '-'),ledgerJournalTrans.OffsetAccountType);//(_facility);
ledgerJournalTrans.parmOffsetAccount("1010",ledgerJournalTrans.OffsetAccountType);//(_facility);
//ledgerJournalTrans.parmOffsetDefaultDimension(
//ledgerJournalTrans.LedgerDimension = 5637145350;
ledgerJournalTrans.TransactionType = 14;// LedgerTransType::Payment;
ledgerJournalTrans.CurrencyCode = "USD";
ledgerJournalTrans.Invoice = ledgerJournalTrans.JournalNum;
ledgerJournalTrans.Txt = strFmt("AP Invoice");
ledgerJournalTrans.Approved = NoYes::Yes;
if(amount> 0)
{
ledgerJournalTrans.AmountCurDebit = amount;
}
else
{
ledgerJournalTrans.AmountCurCredit = abs(amount);
}
ledgerJournalTrans.Company = strUpr(curExt());
ledgerJournalTrans.OffsetCompany = strUpr(curExt());
select firstonly personUser where personUser.User == curUserId()
join worker
where worker.Person == personUser.PersonParty;
ledgerJournalTrans.Approver = worker.RecId ? worker.RecId : 5637145326;// worker.RecId;
//ledgerJournalTrans.PostingProfile = 'GEN';
ledgerJournalTrans.parmAccount(_Account,ledgerJournalTrans.AccountType);
ledgerJournalTrans.insert();
result = true;
}
}
ttscommit;
}*/
public static void recalculation(EQNOrderTypes _orderTypes,SalesId _salesId, SalesId _rentalId,accountNum _custacc)
{
Query query;
QueryRun qr;
SalesTable salesTable;
SalesLine salesline;
SalesId tmpSalesId;
Amount financialriskperorder,financialriskperline = 0,misccharges =0;
boolean recalculationstarted = false;
EQNCreditExposureCalculations eqncreditExposureCalculations = new EQNCreditExposureCalculations();
query = eqncreditExposureCalculations.buildQuery(_orderTypes,_salesId,_rentalId,_custacc);
qr = new QueryRun(query);
while (qr.next())
{
recalculationstarted = true;
salesTable = qr.get(tableNum(SalesTable));
boolean execute = true;
if(PaymTerm::find(salesTable.Payment,false).EQNExcludefromexposurecalculations)
{
execute = false;
}
if( salesTable.SalesPoolId == CustParameters::find().EQNExcludeFromExposure) // If sales table pool id is also equal we need to skip it.
{
execute = false;
}
if(execute)
{
financialriskperorder = EQNCreditExposureCalculations::financalExposurePerOrder(_orderTypes,salesTable);
misccharges = EQNCreditExposureCalculations::calculateMarkupTrans(salesTable.SalesId);
financialriskperorder = financialriskperorder+misccharges;
if(financialriskperorder>0)
EQNCreditExposureCalculations::insertEQNFINCustExposureTrans(salesTable,financialriskperorder);
}
else
{
EQNCreditExposureCalculations::delEqnCustExposureTrans(salesTable);
}
}
if(!recalculationstarted)
info("Batch has no records to execute with given criteria");
else
info("Financial risk for queried orders is Calculated in batch");
}
}
==============================================================
class EQNRecalculateExposureUIBuilder extends SysOperationAutomaticUIBuilder
{
Dialog dlg;
DialogField dialogCustAcc;
DialogField dialogSalesId;
DialogField dialogRentalId;
DialogField dialogOrderTypes;
EQNRecalculateExposureContract contract;
public void build()
{
DialogGroup dlgGrp;
contract = this.dataContractObject();
//get the current dialog
dlg = this.dialog();
dialogCustAcc = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmCustAccount),contract);
dialogCustAcc.value('');
dialogSalesId = this.addDialogField(methodStr(EQNRecalculateExposureContract,parmSalesId),contract);
dialogSalesId.value('');
dialogRentalId = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmRentalOrder),contract);
dialogRentalId.value('');
dialogOrderTypes = this.addDialogField(methodStr(EQNRecalculateExposureContract, parmOrderTypes),contract);
}
public void run()
{
try
{
}
catch (Exception::Deadlock)
{
retry;
}
}
public void enableBasedOnOrderTypes(FormComboBoxControl _orderTypes)
{
EQNOrderTypes orderTypes;
switch(dialogOrderTypes.value())
{
case (EQNOrderTypes::Both) :
{
dialogSalesId.enabled(true);
dialogRentalId.enabled(true);
break;
}
case (EQNOrderTypes::SalesOrder):
{
dialogSalesId.enabled(true);
dialogRentalId.enabled(false);
break;
}
case (EQNOrderTypes::RentalOrder):
{
dialogSalesId.enabled(false);
dialogRentalId.enabled(true);
break;
}
}
}
public void postBuild()
{
contract = this.dataContractObject();
dialogCustAcc = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmCustAccount));
dialogSalesId = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmSalesId));
dialogRentalId = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmRentalOrder));
dialogOrderTypes = this.bindInfo().getDialogField(
this.dataContractObject(), methodStr(EQNRecalculateExposureContract, parmOrderTypes));
//dialogOrderTypes.registerOverrideMethod(methodstr(FormComboBoxControl,modified), methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);
dialogOrderTypes.registerOverrideMethod(methodstr(FormComboBoxControl,selectionChange), methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);
}
public void postRun()
{
super();
//Register overrides for form control events
dialogCustAcc.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, custAccLookup),
this);
dialogSalesId.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, salesIdLookup),
this);
dialogRentalId.registerOverrideMethod(
methodstr(FormStringControl, lookup),
methodstr(EQNRecalculateExposureUIBuilder, rentalIdLookup),
this);
/* dialogOrderTypes.registerOverrideMethod(
methodstr(FormComboBoxControl,modified),
methodStr(EQNRecalculateExposureUIBuilder,enableBasedOnOrderTypes),this);*/
}
public void SalesIdLookup(FormStringControl salesIdLookup)
{
Query query = new Query();
QueryBuildDataSource qbds_SalesTable;
SysTableLookup sysTableLookup;
// Create an instance of SysTableLookup with the current calling form control.
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesTable), salesIdLookup);
// Add fields to be shown in the lookup form.
sysTableLookup.addLookupfield(fieldNum(SalesTable,SalesId));
qbds_SalesTable = query.addDataSource(tableNum(SalesTable));
//qbds_SalesTable.addRange(fieldnum(SalesTable, SalesStatus)).value(strfmt('!%1,!%2',enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
qbds_SalesTable.addRange(fieldNum(SalesTable,SalesType)).value(enum2str(SalesType::Sales));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
}
public void RentalIdLookup(FormStringControl rentalIdLookup)
{
Query query = new Query();
QueryBuildDataSource qbds_SalesTable;
QueryBuildRange qbrSalesType;
SysTableLookup sysTableLookup;
// Create an instance of SysTableLookup with the current calling form control.
sysTableLookup = SysTableLookup::newParameters(tableNum(SalesTable), rentalIdLookup);
// Add fields to be shown in the lookup form.
sysTableLookup.addLookupfield(fieldNum(SalesTable,SalesId));
qbds_SalesTable = query.addDataSource(tableNum(SalesTable));
//qbds_SalesTable.addRange(fieldnum(SalesTable, SalesStatus)).value(strfmt('!%1,!%2',enum2str(SalesStatus::Canceled),enum2str(SalesStatus::None)));
qbds_SalesTable.addRange(fieldNum(SalesTable,SalesType)).value(enum2str(SalesType::RORRental));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
}
public void custAccLookup(FormStringControl custAcclookup)
{
Query query = new Query();
QueryBuildDataSource qbds_CustTable;
SysTableLookup sysTableLookup;
sysTableLookup = SysTableLookup::newParameters(tableNum(CustTable), custAcclookup);
sysTableLookup.addLookupfield(fieldNum(CustTable,AccountNum));
sysTableLookup.addLookupMethod(tableMethodStr(CustTable,Name));
qbds_CustTable = query.addDataSource(tableNum(CustTable));
sysTableLookup.parmQuery(query);
// Perform the lookup
sysTableLookup.performFormLookup();
//CustTable::lookupCustomer(custAcclookup, curExt());
}
}
=======================================================================
[ExtensionOf(classStr(SalesFormLetterProvider))]
Final class EQNSalesFormLetterProvider_Extension
{
protected boolean creditMaxOk(SalesTotals _salesTotals)
{
CustCreditLimit custCreditLimit;
boolean ret = next creditMaxOk(_salesTotals);
if(_salesTotals is SalesTotals_ParmTransInvoice)
{
EQNCreditExposureCalculations::delEqnCustExposureTrans(SalesTable);
}
return ret;
}
public boolean checkJournal()
{
boolean ret = next checkJournal();
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
ret = FINCheckCreditLimit::checkCreditLimit_Sales(SalesTable, true, true);
return ret;
}
}
===================================================================
[ExtensionOf(tableStr(TmpCustVendTrans))]
Final class EQNTmpCustVendTrans_Extension
{
static container custCalcSalesTotals(CustAccount _custAccount,
CurrencyCode _currencyCode,
AgreementHeaderExtRecId_RU _agreementHeaderExtRecId
)
{
container con;
CustCreditLimit custCreditLimit;
SalesTotals salesTotals;
SalesTable salesTable;
// <GEERU>
SalesTable_RU salesTableRU;
// </GEERU>
AmountMST mcrCreditCardBalance = 0;
con = next custCalcSalesTotals(_custAccount,_currencyCode ,_agreementHeaderExtRecId);
if( CustParameters::find().FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
Amount custexposureamt;
salesTable.CustAccount = _custAccount;
salesTable.initFromCustTable();
// <GEERU>
salesTableRU.AgreementHeaderExt_RU = _agreementHeaderExtRecId;
salesTable.packSalesTable_RU(salesTableRU);
// </GEERU>
salesTotals = SalesTotals::construct(salesTable);
// <GEERU>
salesTotals.parmCheckAgreementLimit_RU(_agreementHeaderExtRecId != 0);
// </GEERU>
salesTotals.calc();
custCreditLimit = CustCreditLimit::construct(salesTable);
// <GEERU>
custCreditLimit.parmCheckAgreementLimit_RU(_agreementHeaderExtRecId != 0);
// </GEERU>
//Return credit card balance as well.
if (isConfigurationkeyEnabled(configurationKeyNum(MCRCallCenter)))
{
mcrCreditCardBalance = custCreditLimit.MCRBalanceCreditCard();
}
custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_custAccount);
return [salesTotals.displayFieldsCurrency(_currencyCode)] +
[custexposureamt] +
[custCreditLimit.EQNuseEstimated()] +
[mcrCreditCardBalance];
}
else
return con;
}
static TmpCustVendTrans custTransBalanceCurrency(
CustAccount _accountNum,
boolean _addTotalAndCredit,
CurrencyCode _currencyCode,
BankLCBankDocument _bankLCBankDocument)
{
TmpCustVendTrans tmpCustVendTrans = null;
CustTrans custTrans;
CustTransOpen custTransOpen;
BankLCCustTrans bankLCCustTrans;
AmountMST sumAmountMST;
AmountMST creditRemain;
AmountMST creditLimit;
container displayFields;
AmountMST balanceEstimate;
AmountMST balanceCreditCard;
boolean useEstimated;
tmpCustVendTrans = next custTransBalanceCurrency(_accountNum,_addTotalAndCredit ,_currencyCode,_bankLCBankDocument);
if(CustParameters::find(false).FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
tmpCustVendTrans = null;
sumAmountMST = 0;
creditRemain = 0;
CustInvoiceJour custInvoiceJour;
PaymTerm paymTerm;
container conRecIds;
if (_bankLCBankDocument == BankLCBankDocumentType::All)
{
while select CurrencyCode
from custTrans
group by CurrencyCode
where custTrans.AccountNum == _accountNum
join sum(AmountCur), sum(AmountMST)
from custTransOpen
where custTransOpen.RefRecId == custTrans.RecId
/*join LedgerVoucher,InvoiceId,InvoiceDate,InvoiceAccount,Payment from custInvoiceJour
where custInvoiceJour.LedgerVoucher == custTrans.Voucher
&& custInvoiceJour.InvoiceId == custTrans.Invoice
&& custInvoiceJour.InvoiceDate == custTrans.TransDate
&& custInvoiceJour.InvoiceAccount == custTrans.AccountNum
join paymTerm
where paymTerm.PaymTermId == custInvoiceJour.Payment
&& paymTerm.EQNExcludefromexposurecalculations !=NoYes::Yes*/
{
tmpCustVendTrans = TmpCustVendTrans::insertTmpCustVendTransForCustBalance(
tmpCustVendTrans,
_accountNum,
custTrans,
custTransOpen);
sumAmountMST += tmpCustVendTrans.AmountMst;
}
}
else
{
while
select CurrencyCode
from custTrans
group by CurrencyCode
where custTrans.AccountNum == _accountNum
join BankLCExportLine from bankLCCustTrans
where custTrans.BankLCExportLine == bankLCCustTrans.BankLCExportLine
&& bankLCCustTrans.BankDocumentType == BankLCCustVendTransHelper::convertDocumentType(_bankLCBankDocument)
join sum(AmountCur), sum(AmountMST)
from custTransOpen
where custTransOpen.RefRecId == custTrans.RecId
{
tmpCustVendTrans = TmpCustVendTrans::insertTmpCustVendTransForCustBalance(
tmpCustVendTrans,
_accountNum,
custTrans,
custTransOpen);
sumAmountMST += tmpCustVendTrans.AmountMst;
}
}
if (_addTotalAndCredit)
{
tmpCustVendTrans.data(TmpCustVendTrans::populateLineTotal(sumAmountMST));
tmpCustVendTrans.insert();
// Add line with packing slip or orderd amount
if (CustParameters::find().CreditMaxCheck != TypeOfCreditmaxCheck::None)
{
//Return back the credit card balance.
[displayFields, balanceEstimate, useEstimated, balanceCreditCard] = TmpCustVendTrans::custCalcSalesTotals(_accountNum, _currencyCode);
TmpCustVendTrans::insertTmpCustVendTransBasedOnTypeOfCreditmaxCheck(tmpCustVendTrans, balanceEstimate, useEstimated);
creditRemain -= TmpCustVendTrans::getAmountToDecreaseCreditRemaining(balanceEstimate, useEstimated);
//Display any unposted credit card amount
if (useEstimated && balanceCreditCard
&& isConfigurationkeyEnabled(configurationKeyNum(MCRCallCenter)))
{
tmpCustVendTrans.Txt = "@MCR20754";
tmpCustVendTrans.AmountMst = balanceCreditCard;
tmpCustVendTrans.insert();
//Add the credit card unposted back to the balance.
creditRemain += balanceCreditCard;
}
creditLimit = FINCheckCreditLimit::maxCreditLimit(_accountNum);
if (creditLimit)
{
creditRemain += conpeek(displayFields, TradeTotals::posFreeValue());
}
else
{
creditRemain = 0;
}
Amount balanceMST,custexposureamt;
CustTable custTbl;
creditRemain = 0;
custTbl = (CustTable::find(_accountNum,false));
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
balanceMST = custTbl.openBalanceMST()+creditExposureCalculations.custorderedbal(custTbl);
//balanceMST = EQNCreditExposureCalculations::openBalanceMST(custTbl)+creditExposureCalculations.custorderedbal(custTbl);
creditRemain = creditLimit - custexposureamt -balanceMST;
tmpCustVendTrans.data(TmpCustVendTrans::populateLineCreditLimit(creditLimit, false));
tmpCustVendTrans.insert();
tmpCustVendTrans.data(TmpCustVendTrans::populateLineCreditRemain(creditRemain, false));
tmpCustVendTrans.insert();
}
}
}
return tmpCustVendTrans;
}
}
======================================================================
[ExtensionOf(classStr(FINCheckCreditLimit))]
Final class FINCheckCreditLimitEQN_Extension
{
public static client server void checkCreditLimit_Cust(CustAccount _custacc)
{
boolean ret = true;
CustTable custtable;
AmountMST openBalanceMST;
Amount creditLimit,custexposureamt=0,excessamt;
custTable = CustTable::find(_custacc,false);
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
creditLimit = FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum);
//custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_custacc);
excessamt = openBalanceMST+custexposureamt+-creditLimit;
if (openBalanceMST+custexposureamt >= creditLimit)
{
info(strfmt("@EQN:CustCreditlimitError",openBalanceMST,creditLimit,excessamt)); }
else
{
Percent percent;
if(creditLimit >0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
info(strfmt("@EQN:CustCreditlimitPercentWarning",openBalanceMST,CustParameters::find(false).EQNPctOfCreditLimit,creditLimit,excessamt));
}
}
public static client server boolean checkCreditLimit_Sales(SalesTable _salesTable,
boolean _onlyWarning,
boolean _showMsg)
{
CustTable custTable;
AmountMST openBalanceMST;
Amount creditLimit,financialriskperorder,custexposureamt=0,excessamt,misccharges;
EQNFINCustExposureTrans eqncustExposuretransold;
EQNOrderTypes ordertypes;
FINCreditLimitException finCreditLimitException;
FINModule finModule;
boolean ret = next checkCreditLimit_Sales(_salesTable,_onlyWarning,_showMsg);
boolean execute = true;
if(PaymTerm::find(_salesTable.Payment,false).EQNExcludefromexposurecalculations)
{
execute = false;
}
if( _salesTable.SalesPoolId == CustParameters::find().EQNExcludeFromExposure) // If sales table pool id is also equal we need to skip it.
{
execute = false;
}
if (CustParameters::find().FINCustCreditCheckType != FINCustCreditCheckType::BasedonExposure)//basedonexposure need to be added
{
execute = false;
}
if (execute)//basedonexposure need to be added
{
ret = true;
String10 salestype;
custTable = _salesTable.custTable_InvoiceAccount();
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
select eqncustExposuretransold
where eqncustExposuretransold.EQNSalesId == _salesTable.SalesId;
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
if(eqncustExposuretransold.EQNExposureValue)
openBalanceMST = openBalanceMST-eqncustExposuretransold.EQNExposureValue;
creditLimit = FINCheckCreditLimit::maxCreditLimit(custTable.AccountNum);
if(_salesTable.SalesType == SalesType::Sales)
{
ordertypes = EQNOrderTypes::SalesOrder;
salestype = "@EQN:Sales";
finModule = FINModule::SalesOrder;
}
else if(_salesTable.SalesType == SalesType::RORRental)
{
ordertypes = EQNOrderTypes::RentalOrder;
SalesType = "@EQN:Rental";
finModule = FINModule::RentalOrder;
}
financialriskperorder = EQNCreditExposureCalculations::financalExposurePerOrder(ordertypes,_salesTable);
misccharges = EQNCreditExposureCalculations::calculateMarkupTrans(_salesTable.SalesId);
financialriskperorder = financialriskperorder+misccharges;
//custexposureamt = EQNFINCustExposureTrans::CustomerExposure(_salesTable.CustAccount);
excessamt = openBalanceMST+custexposureamt+financialriskperorder-creditLimit;
if (openBalanceMST+financialriskperorder >= creditLimit)
{
if (FINCheckCreditLimit::hasCreditLimitException(_salesTable.CustAccount, finModule, _salesTable.SalesId))
{
info(strfmt("@EQN:salesconfirmerror",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,salestype));
}
else
{
error(strfmt("@EQN:salesconfirmerror",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,salestype));
ret = false;
}
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit>0)
percent=((openBalanceMST+financialriskperorder)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
info(strfmt("@EQN:salesconfirmwarning",_salesTable.SalesId,openBalanceMST,_salesTable.CurrencyCode,financialriskperorder,financialriskperorder+openBalanceMST,creditLimit,excessamt,CustParameters::find().EQNPctOfCreditLimit,salestype));
}
}
//}
if(ret)
{
EQNCreditExposureCalculations::insertEQNFINCustExposureTrans( _salesTable,financialriskperorder);
}
}
return ret;
}
public static client server boolean checkCreditLimit_WPPline(WPPWorkOrderLine _workOrderLine)
{
boolean ret = true;
WPPParameters wppParameters;
CustTable custTable;
AmountMST openBalanceMST;
Amount creditLimit,custexposureamt,excessamt;
WPPWorkOrderTable wppWorkorderTable;
if(ProjGroup::find((ProjTable::find(_workOrderLine.ProjId,false).ProjGroupId),FALSE).FINCustCreditCheckType == FINCustCreditCheckType::BasedonExposure)
{
if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit != EQNWPPMessagewhenexceedingcreditlimit::Review)
{
wppWorkorderTable = WPPWorkOrderTable::find(_workOrderLine.WorkOrderId,false);
custTable = CustTable::find(wppWorkorderTable.CustVendAccount);
EQNCreditExposureCalculations creditExposureCalculations =new EQNCreditExposureCalculations();
//openBalanceMST = custTable.openBalanceCur()+creditExposureCalculations.custorderedbal(custTable);
openBalanceMST = custTable.openBalanceMST()+creditExposureCalculations.custorderedbal(custTable);
creditLimit = FINCheckCreditLimit::maxCreditLimit(wppWorkorderTable.CustVendAccount);
excessamt = openBalanceMST+custexposureamt-creditLimit;
wppParameters = WPPParameters::find(false);
if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit == EQNWPPMessagewhenexceedingcreditlimit::Error)
{
if (openBalanceMST >= creditLimit)
{
if (FINCheckCreditLimit::hasCreditLimitException(custTable.AccountNum,
FINModule::WPPWorkOrder,
_workOrderLine.WorkOrderId))
{
info(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
}
else
{
throw error(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
ret = false;
}
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit > 0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent=100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
return warning(strfmt("@EQN:WorkOrderexcesscreditwarning",openBalanceMST+custexposureamt,creditLimit,custTable.currency,excessamt,CustParameters::find().EQNPctOfCreditLimit));
}
}
}
else if(WPPParameters::find(false).EQNWPPMessagewhenexceedingcreditlimit == EQNWPPMessagewhenexceedingcreditlimit::Warning)
{
if (openBalanceMST >= creditLimit)
{
info(strFmt("@EQN:Workorderexcesscrediterror", openBalanceMST,creditLimit,custTable.currency,excessamt));
ret = false;
}
if(ret == true)
{
if(CustParameters::find().EQNPctOfCreditLimit > 0 &&CustParameters::find().EQNPctOfCreditLimit != 100 )
{
Percent percent;
if(creditLimit >0)
percent=((openBalanceMST)/creditLimit)* 100;
else
percent = 100;
if(percent> CustParameters::find().EQNPctOfCreditLimit)
return warning(strfmt("@EQN:WorkOrderexcesscreditwarning",openBalanceMST+custexposureamt,creditLimit,custTable.currency,excessamt,CustParameters::find().EQNPctOfCreditLimit));
}
}
}
}
}
return ret;
}
}
======================================================================
class SalesCreateOrderEventhandler
{
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(SalesCreateOrder, SalesTable_CustAccount), FormControlEventType::Modified)]
public static void SalesTable_CustAccount_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl custacc = formRun.design(0).controlName("SalesTable_CustAccount");
if(custacc.valueStr() != "")
FINCheckCreditLimit::checkCreditLimit_Cust(custacc.valueStr());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormControlEventHandler(formControlStr(RORSalesCreateOrder, SalesTable_CustAccount), FormControlEventType::Modified)]
public static void RORSalesTable_CustAccount_OnModified(FormControl sender, FormControlEventArgs e)
{
FormRun formRun = sender.formRun();
FormStringControl custacc = formRun.design(0).controlName("SalesTable_CustAccount");
if(custacc.valueStr() != "")
FINCheckCreditLimit::checkCreditLimit_Cust(custacc.valueStr());
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
[PostHandlerFor(formStr(SalesTable), formMethodStr(SalesTable, init))]
public static void SalesTable_Post_init(XppPrePostArgs args)
{
FormRun initialFormRun;
Common initialFormRunRecord;
CustTable custTable;
initialFormRun= args.getThis();
if (TradeFormHelper::isCalledFromForm(initialFormRun.args(), formStr(CustTable))
&& initialFormRun.args().record().TableId == tableNum(CustTable))
{
//initialFormRun = initialFormRun.args().caller() as FormRun;
initialFormRunRecord = initialFormRun.args().record();
//custTable = initialFormRun.args().record() as CustTable;
initialFormRunRecord = initialFormRun.args().record();
custTable = initialFormRunRecord;
if(custTable)
FINCheckCreditLimit::checkCreditLimit_Cust(custTable.AccountNum);
}
}
}
=================================================================
[ExtensionOf(classStr(WPPWorkOrderStatusUpdate))]
Final class WPPWorkOrderStatusUpdateEQN_Extension
{
protected boolean checkcreditlimitonWorkOrderline()
{
boolean ret;
ret = FINCheckCreditLimit::checkCreditLimit_WPPline(this.workOrderLine);
return ret;
}
protected void updateWorkOrderLine()
{
this.checkcreditlimitonWorkOrderline();
next updateWorkOrderLine();
}
}
No comments:
Post a Comment