Thursday, 31 January 2019

return Temp Table in AIF service method x++

[
    SysEntryPointAttribute(true),
    AifCollectionTypeAttribute("return",Types::Record,tableStr(FCC_EmpDependentTmp)),
    AifCollectionTypeAttribute("PersonnelNumberId",Types::String,extendedTypeStr(HcmPersonnelNumberId))
]
public FCC_EmpDependentTmp getEmpDependentByEmpId(HcmPersonnelNumberId    _personnelNumberId)
{
    Query                               query = new Query(queryStr (FCC_EmpDependent));
    QueryRun                            qRun;
    QueryBuildRange                     qbr;

    DirPartyRelationships_Parent        parentView;
    HcmPersonPrivateDetails             privateDetails;
    HcmJob                              hcmJob, jobLocal;
    HcmPosition                         hcmPosition;
    HcmWorker                           hcmWorker;
    HcmPositionDetail                   hcmPositionDetail;
    FCC_JobRoleTable                    jobRoleTable;
    HcmPositionWorkerAssignment         workerAssignment;
    DirPartyTable                       dirpartyTable;

    FCC_EmpDependentTmp                 empDependentTmp;

    qbr = query.dataSourceTable( tableNum (HcmWorker)).addRange( fieldNum (HcmWorker, personnelNumber));
    qbr.value(_personnelNumberId);
    qRun = new QueryRun(query);

    while (qRun.next())
    {
        privateDetails      =   qRun.get(tableNum(HcmPersonPrivateDetails));
        parentView          =   qRun.get(tableNum(DirPartyRelationships_Parent));
        dirpartyTable       =   qRun.get(tableNum(DirPartyTable));

        while select hcmPosition
        join hcmPositionDetail
            Where hcmPosition.RecId ==  hcmPositionDetail.Position
                join hcmJob
                    where hcmPositionDetail.Job ==  hcmJob.RecId
                        outer join jobRoleTable
                        where hcmJob.FCC_JobRoleId  ==  jobRoleTable.JobRoleId
                            join workerAssignment
                                where hcmPosition.RecId == workerAssignment.Position
                                    join  hcmWorker
                                        where workerAssignment.Worker == hcmWorker.RecId
                                        && hcmWorker.PersonnelNumber  == privateDetails.FCC_IsRelativeInEPG
        {
            empDependentTmp.RelativeEmpId           =       privateDetails.FCC_IsRelativeInEPG;
            empDependentTmp.RelativeEmpName         =       dirpartyTable.Name;
            empDependentTmp.PositionId              =       hcmPosition.PositionId;
            empDependentTmp.PositionName            =       hcmPositionDetail.Description;
            empDependentTmp.JobRoleId               =       jobRoleTable.JobRoleId;
            empDependentTmp.JobRoleName             =       jobRoleTable.Description;
            empDependentTmp.Relationship            =       parentView.Description;
            empDependentTmp.RefRecId                =       dirpartyTable.RecId;
            empDependentTmp.insert();
        }
    }

    select RelativeEmpId,
           JobRoleName,
           PositionName,
           Relationship,
           RefRecId from empDependentTmp;


    return empDependentTmp;
}

Hiding text box on visual studio expression

here group value is 10 text box will be hide, if 20 it will visible

=iif((First(Fields!CustGroup.Value, "10") = "20"),True,false)

Wednesday, 30 January 2019

employee dimension import in D365

using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.ExcelPackage;
using OfficeOpenXml.ExcelRange;
class INTC_EmployeeDefaultDimensionImport
{
    public static void main(Args _args)
    {
        System.IO.Stream            stream;
        ExcelSpreadsheetName        sheeet;
        FileUploadBuild             fileUpload;
        DialogGroup                 dlgUploadGroup;
        FileUploadBuild             fileUploadBuild;
        FormBuildControl            formBuildControl;
        container                   conDimValue;
        container                   conVal;
        int64                       ledgerLoc;
        str                         dimValue;
        HcmPersonnelNumberId        personnelNum;


        hcmWorker                           hcmWorker, hcmWorkerLocal;
        HcmEmployment                       hcmEmployment;
        DimensionValueName           tmpLegal_Entity, tmpOffice_Location, tmpProject_Location, tmpDepartment, tmpService_Line, tmpSub_Service_Line, tmpIndustry,
                                            tmpSub_Industry, tmpCoIndustry, tmpPartner, tmpPM_Employee, tmpProject;
        DimensionAttribute                  dimensionAttribute;
        DimensionAttributeValue             dimensionAttributeValue;
        DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();
        DimensionDefault                    result;
        container                           conAttr = [ "A_Legal_Entity","B_Office_Location","C_Project_Location","D_Department","E_Service_Line","F_Sub_Service_Line","G_Partner","H_Industry","I_Sub_Industry","J_CoIndustry","PM_Employee","Project"];

        Dialog                      dialog = new Dialog("Import employee default dimenson from Excel");

        dlgUploadGroup          = dialog.addGroup("@SYS54759");
        formBuildControl        = dialog.formBuildDesign().control(dlgUploadGroup.name());
        fileUploadBuild         = formBuildControl.addControlEx(classstr(FileUpload), "Import");

        fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);
        fileUploadBuild.fileTypesAccepted('.xlsx');

        if (dialog.run() && dialog.closedOk())
        {

            FileUpload fileUploadControl     = dialog.formRun().control(dialog.formRun().controlId('Import'));
            FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();

            if (fileUploadResult != null && fileUploadResult.getUploadStatus())
            {
                stream = fileUploadResult.openResult();
                using (ExcelPackage Package = new ExcelPackage(stream))
                {
                    int                         rowCount, i, j;
                    Package.Load(stream);
                    ExcelWorksheet  worksheet   = package.get_Workbook().get_Worksheets().get_Item(1);
                    OfficeOpenXml.ExcelRange    range       = worksheet.Cells;
                    rowCount                    = worksheet.Dimension.End.Row - worksheet.Dimension.Start.Row + 1;

                    for (i = 2; i<= rowCount; i++)
                    {
                        personnelNum                = range.get_Item(i, 1).value;
                        tmpLegal_Entity             = range.get_Item(i, 2).value;
                        tmpOffice_Location          = range.get_Item(i, 3).value;
                        tmpProject_Location         = range.get_Item(i, 4).value;
                        tmpDepartment               = range.get_Item(i, 5).value;
                        tmpService_Line             = range.get_Item(i, 6).value;
                        tmpSub_Service_Line         = range.get_Item(i, 7).value;
                        tmpPartner                  = range.get_Item(i, 8).value;
                        tmpIndustry                 = range.get_Item(i, 9).value;
                        tmpSub_Industry             = range.get_Item(i, 10).value;
                        tmpCoIndustry               = range.get_Item(i, 11).value;
                        tmpPM_Employee              = range.get_Item(i, 12).value;
                        tmpProject                  = range.get_Item(i, 13).value;

                        hcmworker       = hcmWorker::findByPersonnelNumber(personnelNum);

                        conVal          = [tmpLegal_Entity, tmpOffice_Location, tmpProject_Location, tmpDepartment, tmpService_Line, tmpSub_Service_Line,tmpPartner, tmpIndustry,
                                            tmpSub_Industry, tmpCoIndustry, tmpPM_Employee, tmpProject];
                     
                        if(hcmworker)
                        {
                            select forupdate hcmEmployment where hcmEmployment.Worker == hcmworker.RecId;
                            if(hcmEmployment)
                            {
                                for (j = 1; j <= conLen(conAttr); j++)
                                {
                                    dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,j));
                                    if (dimensionAttribute.RecId == 0)
                                    {
                                        continue;
                                    }
                                    dimValue = conPeek(conVal,j);
                                    if (dimValue != "")
                                    {
                                        dimensionAttributeValue = dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,true);
                                        valueSetStorage.addItem(dimensionAttributeValue);
                                    }
                                    else
                                    {
                                        valueSetStorage.removeDimensionAttribute(DimensionAttribute::findByName(conPeek(conAttr,j)).RecId);
                                    }
                                }
                                result = valueSetStorage.save();
                                ttsbegin;
                                hcmEmployment.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
                                hcmEmployment.DefaultDimension      = result;
                                hcmEmployment.update();
                                ttscommit;
                                personnelNum            = '';
                                tmpLegal_Entity         = '';
                                tmpOffice_Location      = '';
                                tmpProject_Location     = '';
                                tmpDepartment           = '';
                                tmpService_Line         = '';
                                tmpSub_Service_Line     = '';
                                tmpIndustry             = '';
                                tmpSub_Industry         = '';
                                tmpCoIndustry           = '';
                                tmpPartner              = '';
                                tmpPM_Employee          = '';
                                tmpProject              = '';
                            }
                        }
                        else
                        {
                            Error("Employee ID %1 Not exists ", personnelNum);
                        }
                    }
                }
            }
            else
            {
                error("Error");
            }
        }
    }

}

Tuesday, 22 January 2019

infolog customization navigate to record x++

offSetAcctPattern = [“MainAccountId”,_offsetAccount, 3, “SA_Campus”,”30″, “SB_Department”,”111″, “SC_CostCenter”,”1109″];static void InfoLogButton(Args _args)
{
SysInfoAction_MenuFunction sysInfoAction;
PurchReqTable purchRfqCaseTable;

purchRfqCaseTable = PurchReqTable::findPurchReqId(“PUR-0000007”);

sysInfoAction = SysInfoAction_MenuFunction::newMenuItem(menuitemDisplayStr(PurchReqTable),MenuItemType::Display);
sysInfoAction.parmCallerBuffer(purchRFQCaseTable);
info (strfmt(“@SYS107925″, purchRFQCaseTable.PurchReqId),”, sysInfoAction);
}

offset account format x++

offSetAcctPattern = [“MainAccountId”,_offsetAccount, 3, “SA_Campus”,”30″, “SB_Department”,”111″, “SC_CostCenter”,”1109″];

creating ledger dimension in D365 through x++

below method will accept container, it contains specified ledger dimension values.

ex : ledgerDimensionCon = [mainAccountId,”,”,”,purchaseOrderId,shipmentId,”];

public DimensionDynamicAccount generateLedgerDimension(container _combinationContainer)
{
int hierarchyCount;
int hierarchyIdx;
RecId dimAttId_MainAccount;
LedgerRecId ledgerRecId;
MainAccount mainAccount;

RefRecId recordvalue;
DimensionAttribute dimensionAttribute;
DimensionAttributeValue dimensionAttributeValue;
DimensionSetSegmentName DimensionSet;
DimensionStorage dimStorage;
LedgerAccountContract LedgerAccountContract = new LedgerAccountContract();
DimensionAttributeValueContract ValueContract;

List valueContracts = new List(Types::Class);
dimensionAttributeValueCombination dimensionAttributeValueCombination;

mainAccount = MainAccount::findByMainAccountId(conPeek(_combinationContainer,1));
recordvalue = DimensionHierarchy::getAccountStructure(mainAccount.RecId,Ledger::current());
hierarchyCount = DimensionHierarchy::getLevelCount(recordvalue);
DimensionSet = DimensionHierarchyLevel::getDimensionHierarchyLevelNames(recordvalue);

for(hierarchyIdx = 1;hierarchyIdx<=hierarchyCount;hierarchyIdx++)
{
if(hierarchyIdx == 1)
continue;

dimensionAttribute = DimensionAttribute::findByLocalizedName(DimensionSet[hierarchyIdx],false,"en-us");
if(dimensionAttribute)
{
dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,conPeek(_combinationContainer,hierarchyIdx));

if(dimensionAttributeValue)
{
ValueContract = new DimensionAttributeValueContract();
ValueContract.parmName(dimensionAttribute.Name) ;
ValueContract.parmValue(dimensionAttributeValue.CachedDisplayValue);
valueContracts.addEnd(ValueContract);
}
}
}
LedgerAccountContract.parmMainAccount(conPeek(_combinationContainer,1));
LedgerAccountContract.parmValues(valueContracts);

dimStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(LedgerAccountContract);
dimensionAttributeValueCombination = DimensionAttributeValueCombination::find(dimStorage.save());
ledgerRecId = dimensionAttributeValueCombination.RecId;

return ledgerRecId;
}

sales quantity conversion (units) x++

Go to line table and use below method

display Qty InventQty()
{
return UnitOfMeasureConverter::convert(this.SalesQty,
UnitOfMeasure::findBySymbol(this.SalesUnit).RecId,
UnitOfMeasure::findBySymbol(this.inventTable().inventTableModuleInvent().UnitId).RecId,
NoYes::Yes,
this.inventTable().Product
);
}

Department of a worker / Employee x++

static void EmpDepartment(Args _args)
{
HcmWorker hcmWorker;
HcmPositionWorkerAssignment workerAssignment;
HcmPosition hcmPosition;
HcmPositionDetail hcmPositionDetail;
OMOperatingUnit omOperatingUnit;

select omOperatingUnit
join hcmPositionDetail
where hcmPositionDetail.Department == oMOperatingUnit.RecId
join hcmPosition
where hcmPosition.RecId == hcmPositionDetail.Position
Join workerAssignment
where workerAssignment.Position == hcmPosition.RecId
join hcmWorker
where hcmWorker.RecId == workerAssignment.Worker
&& hcmWorker.PersonnelNumber == “891”;

info(strFmt(“%1”, omOperatingUnit.Name));
}

Read and move CSV file from one location to another x++

* Its a basic code for read and move file, you need to add some more methods depend upon requirement.

public void run()
{
#File
IO iO;
Container record;
boolean first = true;
boolean validJournal;

LedgerJournalId journalId;
TransTxt transTxt;
RefRecId refRecId;
LedgerDimensionDefaultAccount offsetAccount;
Voucher voucher;
INC_GLParameters parameters;

LedgerJournalNameId sybaseCollectionType, axJournalName;

Name sybaseDate, sybaseTime, sybaseVoucherNum, sybaseSCode, sybaseCostCenter, sybaseYearTag, sybaseRemarks;
Name sybaseMethodOfPay, sybasePostingProfile, sybaseBranchNum, sybaseYear, sybaseUser, sybaseVoucherDate, sybasePCode;
AmountMST sybaseDebitAmount, sybaseCreditAmount;

Name axDate, axTime, axVoucherNum, axSCode, axCostCenter, axYearTag, axRemarks;
Name axMethodOfPay, axPostingProfile, axBranchNum, axYear, axUser, axVoucherDate, axPCode;
AmountMST axDebitAmount, axCreditAmount;
INC_SybaseTansaction sybaseTansaction;
INC_CostCenter costCenter;
INC_SybasePaymMethods sybasePaymMethods;
INC_CostCenterDimension costCenterDimension;
custLedger custLedger;
CustLedgerAccounts custLedgerAccounts;
int rwCnt;
System.Array files;
FilePath fPath;

Filename fileName,
filePath,
fileType;

FileNameType fPattern = “*.csv”;

int fileCount;
int i;
str nextFile;
DimensionStorage dimensionStorage;
DimensionAttribute branchDimensionAttribute;
DimensionAttributeValue newBranchValue;
container dimConAttr, dimConValue;
real numPatientId, numFileNo;
str dumpFPath;

Set permissionSet;
Filename fType;

//this.header();
try
{
select firstOnly parameters;
fPath = parameters.IntegrationFolder;

new InteropPermission(InteropKind::ClrInterop).assert();
files = System.IO.Directory::GetFiles(fPath, fPattern);

if (files)
{
fileCount = files.get_Length();
if(fileCount)
{
for(i=0; i 1) //To skip header of csv
{
sybaseCollectionType = conPeek(record, 1);
sybaseDate = conPeek(record, 2);
sybaseTime = conPeek(record, 3);
sybaseVoucherNum = conPeek(record, 4);
sybaseSCode = conPeek(record, 5);
sybaseCostCenter = conPeek(record, 6);
sybaseYearTag = conPeek(record, 7);
sybaseRemarks = conPeek(record, 8);
sybaseMethodOfPay = conPeek(record, 9);
sybasePostingProfile = conPeek(record, 10);
sybaseDebitAmount = conPeek(record, 11);
sybaseCreditAmount = conPeek(record, 12);
sybaseBranchNum = conPeek(record, 13);
sybaseYear = conPeek(record, 14);
sybaseUser = conPeek(record, 15);
sybaseVoucherDate = conPeek(record, 16);
sybasePCode = conPeek(record, 17);

select firstOnly sybaseTansaction where sybaseTansaction.SybaseTransCode == sybaseCollectionType;
axJournalName = sybaseTansaction.AXTransCode;

select firstOnly sybasePaymMethods where sybasePaymMethods.SybasePaymMetghodCode == sybaseMethodOfPay;
axMethodOfPay = sybasePaymMethods.AXPaymMethodCode;

select firstOnly costCenter where costCenter.SybaseCostCenter == sybaseCostCenter;
axCostCenter = costCenter.AXCostCenterCode;

select custLedgerAccounts
join custLedger
where CustLedgerAccounts.PostingProfile == custLedger.PostingProfile
&& custLedger.PostingProfile == sybasePostingProfile;

axCreditAmount = sybaseCreditAmount;
axDebitAmount = sybaseDebitAmount;
axRemarks = sybaseRemarks;

select costCenterDimension where costCenterDimension.CostCenter == sybaseCostCenter;

//Validations. Do not proceed to insert data
if (!sybaseCollectionType)
{
validJournal = checkFailed(strFmt(“Please enter jounal name in the import sheet %1, row number %2”, nextFile, rwCnt));
continue;
}

if (!sybasePostingProfile)
{
validJournal = checkFailed(strFmt(“Please enter posting pofile in the import sheet %1, row number %2”, nextFile, rwCnt));
continue;
}

if (validJournal)
{
if(rwCnt == 2)
{
this.createHeader(axJournalName);
}
this.createLines( parameters.CustAccount
, “”
, axRemarks
, axCreditAmount
, axDebitAmount
, sybaseVoucherNum
, sybaseYearTag
, sybaseUser
, custLedgerAccounts.SummaryLedgerDimension,
sybasePostingProfile
, costCenterDimension.DimensionDefault);
}
}
}
}
//Move file after reading successfully.
if (validJournal)
{
io = null;
info(strFmt(“Journal %1 created”, ledgerJournalTable.JournalNum));
System.IO.File::Move(nextFile, dumpFPath);
info(‘Source file is moved to dump folder’);

ttsCommit;
}
else
{
checkFailed(strFmt(“Errors recorded in file %1”, nextFile));
ttsAbort;
}
}
}
else if(!fileCount)
{
checkFailed(strFmt(“Source CSV file is not found in given location %1”, nextFile));
}
}
}
catch(Exception::Error)
{
throw error(“Error in creating Journals”);
//ttsAbort;
}
}

number seq by group x++

public FCC_ItemNumSeq itemGroupSeq(ItemGroupId _itemGroupId)
{
NumberSequenceCode numberSequenceCode;
RefRecId numberSeqRefRecId;
NumberSequenceTable numberSequenceTable;
NumberSeq num;
EcoResProduct ecoResProductLoc;
FCC_ItemNumSeq itemNumSeq;
FCC_ItemNumberSequence fcc_ItemNumberSequence, fcc_ItemNumberSequenceUpdate;

select fcc_ItemNumberSequence
where fcc_ItemNumberSequence.ItemGroupId == _itemGroupId;

numberSeqRefRecId = fcc_ItemNumberSequence.NumberSequenceRefRecId;
ecoResProductLoc = EcoResProduct::findByProductNumber(fcc_ItemNumberSequence.NumberSequenceFormat);
if(!ecoResProductLoc && fcc_ItemNumberSequence.NumberSequenceFormat != “”)
{
itemNumSeq = fcc_ItemNumberSequence.NumberSequenceFormat;
}
else
{
num = NumberSeq::newGetNumFromId(numberSeqRefRecId);
itemNumSeq = num.num();
select forUpdate fcc_ItemNumberSequenceUpdate
where fcc_ItemNumberSequenceUpdate.ItemGroupId == _itemGroupId;
ttsBegin;
fcc_ItemNumberSequenceUpdate.NumberSequenceFormat = itemNumSeq;
fcc_ItemNumberSequenceUpdate.Count = 1;
fcc_ItemNumberSequenceUpdate.update();
ttsCommit;
}
//this.insert();
return itemNumSeq;
}

warehouse address x++

static void warehoseAddress(Args _args)
{
SalesTable salesTable = SalesTable::find(‘SO-000834’);
InventLocation inventLocation;
LogisticsEntityPostalAddressView postalAddressView;
LogisticsElectronicAddress electronicAddress;
LogisticsLocation contactLocation;

inventLocation = inventLocation::find(salesTable.InventLocationId);
if (inventLocation)
{
select firstonly postalAddressView
where postalAddressView.Entity == inventLocation.RecId
&& postalAddressView.EntityType == LogisticsLocationEntityType::Warehouse
&& postalAddressView.isPrimary == NoYes::Yes;

if (postalAddressView)
{
/*select firstOnly electronicAddress where electronicAddress.Type == LogisticsElectronicAddressMethodType::Phone
join contactLocation where contactLocation.ParentLocation == postalAddressView.Location
&& contactLocation.RecId == electronicAddress.Location;*/

info(strFmt(“wharehouse address : %1”,postalAddressView.Address));
}
}
}

import data from excel x++

public void readFromExcell()
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
int row = 1;

Dialog dialog;
DialogField dialogPath;
CommaIO inFile;
FilenameOpen fileName;
str personnelNumberId;
MonthsOfYear month;
DateExpected saturdayOffDate;
Str60 testMonth;
str dayOfDate;
boolean ret, error;
Description255 remarks;
HcmWorker hcmWorker;

application = SysExcelApplication::construct();
workbooks = application.workbooks();

dialog = new Dialog(“Import Override Exception Saturday Off”);
dialogPath = dialog.addField(extendedTypeStr(Filenameopen), “File Name”);
dialog.run();

if (dialog.run())
{
filename = dialogPath.value();
}

workbooks.open(filename);

workbook = workbooks.item(1);
worksheets = workbook.worksheets();

worksheet = worksheets.itemFromNum(1);
cells = worksheet.cells();

do
{
row++;

personnelNumberId = this.COMVariant2Str(cells.item(row,1).value());
saturdayOffDate = cells.item(row,2).value().date();
remarks = cells.item(row,3).value().bStr();
dayOfDate = dayName(dayOfWk(saturdayOffDate));

type = cells.item(row+1, 1).value().variantType();
}

while (type != COMVariantType::VT_EMPTY);
application.quit();

}

allow numeric values only in string field x++

public boolean validate()
{
boolean ret = true;

ret = super();

ret = (strlen(CustTable.CivilId)) == strlen(strkeep(CustTable.CivilId,’0123456789′));

if(ret == false)
{
ret = checkFailed(“Civil id should have numeric values only”);
}
return ret;
}

finanial dimension values for worker x++

static void getDefaultDimensionAttributeForWorker(Args _args)
{
DimensionAttributeValueSetStorage dimStorage;
HcmPositionDefaultDimension HcmPositionDefaultDimension;
DimensionAttribute DimensionAttribute;
DimensionAttribute dimAttr;
DimensionAttributeValue dimAttrValue;
Common common;
DictTable dictTable;
str Name;
str value;
HcmEmployment employement;
HcmWorker hcmWorker;
Counter i;

hcmWorker = HcmWorker::findByPersonnelNumber(“1297”); //pass required worker
employement = HcmEmployment::findByWorker(hcmWorker.RecId);

dimStorage = DimensionAttributeValueSetStorage::find(employement.DefaultDimension); //DefaultDimension

for (i=1 ; i<= dimStorage.elements() ; i++)
{
select firstonly dimAttrValue
where dimAttrValue.RecId == dimStorage.getValueByIndex(i)
join dimAttr
where dimAttr.RecId == dimAttrValue.DimensionAttribute;

if (dimAttr && dimAttrValue)
{
dictTable = new DictTable(dimAttr.BackingEntityType);
common = dictTable.makeRecord();

if (common.TableId)
{
select common where common.(dimAttr.KeyAttribute) == dimAttrValue.EntityInstance;
name = common.(dimAttr.NameAttribute);
value = common.(dimAttr.ValueAttribute);
}
}
info(dimAttr.Name +"—-" +value + "—-"+name);
}
}

Worker line manager x++

static void WorkerLineManager(Args _args)
{
HcmPosition hcmPosition,hcmPositionLoc;
HcmPositionDetail positionDetail;
HcmPositionWorkerAssignment workerAssignment,workerAssignmentLoc;
HcmPositionHierarchy positionHierarchy, positionHierarchyLoc;
HcmWorker hcmWorker,hcmWorkerLoc;

select positionHierarchy
join hcmPosition
where hcmPosition.RecId == positionHierarchy.Position
join workerAssignment
where workerAssignment.Position == hcmPosition.RecId
join hcmWorker
where hcmWorker.RecId == workerAssignment.Worker
&& hcmWorker.PersonnelNumber == “891”;
{

select positionHierarchyLoc
join hcmPositionLoc
where hcmPositionLoc.RecId == positionHierarchy.ParentPosition
join workerAssignmentLoc
where workerAssignmentLoc.Position == hcmPositionLoc.RecId
join hcmWorkerLoc
where hcmWorkerLoc.RecId == workerAssignmentLoc.Worker;

info(strFmt(“%1–line manager %2”, hcmPositionLoc.PositionId,hcmWorkerLoc.PersonnelNumber));
}
}

PR delegated user x++

Static void PRDeligatedUser(Args _args)
{
PurchReqTable purchReqTable;
WorkflowTrackingStatusTable workflowTrackingStatusTable;
WorkflowTrackingTable workflowTrackingTable;
WorkflowTrackingWorkItem workflowTrackingWorkItem;

purchReqTable = PurchReqTable::findPurchReqId(“000251”);

select workflowtrackingstatustable
join workflowtrackingtable
where workflowtrackingstatustable.ContextRecId == purchReqTable.RecId //RecId of the record
&& workflowtrackingtable.TrackingContext == workflowtrackingcontext::WorkItem
&& workflowtrackingtable.TrackingType == workflowtrackingtype::Delegation
&& workflowtrackingtable.WorkflowTrackingStatusTable == workflowtrackingstatustable.RecId
join workflowTrackingWorkItem
where workflowTrackingWorkItem.WorkflowTrackingTable == workflowtrackingtable.RecId;
{
info(strFmt(“%1 — %2”,SysWorkflowHelper::getDirPartyNameFromUserId(workflowTrackingWorkItem.ToUser), SysWorkflowHelper::getDirPartyNameFromUserId(workflowtrackingtable.USER)));
}
}

Thursday, 17 January 2019

Creating multiple personnel contacts of worker x++ AIF custom services

[
SysEntryPointAttribute(true),
AifCollectionTypeAttribute(“_hrOnBoardingDependentContractList”,Types::Class,classStr(FCC_HROnBoardingDependentContract)),
AifCollectionTypeAttribute(“return”,Types::String),
AifCollectionTypeAttribute(“_update”,Types::Integer)
]
public str createUpdateDependentEmpList(List _hrOnBoardingDependentContractList)
{
DirPartyRelationship dirPartyRelationShip;
NoYes noyes;
HcmPersonPrivateDetails personPrivateDetails;
RecId person,recid,person1;
dirRelationshipTypeId dirRelationshipTypeId;
HcmWorker hcmWorkerLocal;
DirPersonName dirPersonName;
DirSystemRelationshipType dirSystemRelationshipType;
HcmIdentificationType identificationType;

RecId newPartyRecId;
str msg;

HcmWorker hcmWorker;
DirPerson dirPerson;
DirPersonName dirPersonNameLocal;
DirPartyTable dirPartyTable;
FirstName firstName;
MiddleName middleName;
LastName lastName;

FCC_HROnBoardingDependentContract dependentContract;

ListEnumerator listEnum = _hrOnBoardingDependentContractList.getEnumerator();

try
{
ttsBegin;
if (!_hrOnBoardingDependentContractList.empty())
{
while (listEnum.moveNext())
{
dependentContract = listEnum.current();
if (dependentContract)
{
while select dirPartyTable
join dirPerson
where dirPartyTable.RecId == dirPerson.RecId
join dirPersonNameLocal
where dirPerson.RecId == dirPersonNameLocal.Person
join hcmWorker
where dirPerson.RecId == hcmWorker.Person
&& hcmWorker.PersonnelNumber == dependentContract.parmDependentEmployee()
{
firstName = dirPersonNameLocal.FirstName;
middleName = dirPersonNameLocal.MiddleName;
lastName = dirPersonNameLocal.LastName;
}
hcmWorkerLocal = HcmWorker::findByPersonnelNumber(dependentContract.parmPersonnelNumber());
person = hcmWorkerLocal.Person;
recid = hcmWorkerLocal.RecId;

select dirPersonName
where dirPersonName.FirstName == firstName;

if(!dirPersonName)
{
dirPersonName.FirstName = firstName;
dirPersonName.MiddleName = middleName;
dirPersonName.LastName = lastName;

newPartyRecId = HcmPersonalContacts::createPersonContact(dirPersonName,person);

dirRelationshipTypeId = DirRelationshipTypeTable::FCC_findByTypeId(dependentContract.parmRelationShipType()).RelationshipTypeId;
DirPartyRelationship = DirPartyRelationship::find(dirRelationshipTypeId, Person, newPartyRecId, true);

if (!DirPartyRelationship)
{
select forUpdate DirPartyRelationship
where DirPartyRelationship.ChildParty == newPartyRecId
&& DirPartyRelationship.ParentParty == Person;

ttsBegin;
DirPartyRelationship.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
DirPartyRelationship.RelationshipTypeId = DirRelationshipTypeTable::findBySystemType(str2enum(DirSystemRelationshipType , dependentContract.parmRelationShipType())).RelationshipTypeId;
DirPartyRelationship.update();
ttsCommit;

}
personPrivateDetails.Person = dirPersonName.Person;
personPrivateDetails.FCC_RelativeInEPG = NoYes::Yes;
personPrivateDetails.FCC_IsRelativeInEPG = dependentContract.parmDependentEmployee();
personPrivateDetails.insert();
msg =’successfully : Inserted’;
}
else
{
select forUpdate dirPersonName
where dirPersonName.FirstName == firstName;
dirPersonName.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
ttsBegin;

dirPersonName.FirstName = firstName;
dirPersonName.MiddleName = middleName;
dirPersonName.LastName = lastName;
dirPersonName.update();
ttsCommit;
newPartyRecId = HcmPersonalContacts::createPersonContact(dirPersonName,person);

dirRelationshipTypeId = DirRelationshipTypeTable::FCC_findByTypeId(dependentContract.parmRelationShipType()).RelationshipTypeId;
DirPartyRelationship = DirPartyRelationship::find(dirRelationshipTypeId, Person, newPartyRecId, true);

if (!DirPartyRelationship)
{
select forUpdate DirPartyRelationship
where DirPartyRelationship.ChildParty == newPartyRecId
&& DirPartyRelationship.ParentParty == Person;
ttsBegin;
DirPartyRelationship.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
DirPartyRelationship.RelationshipTypeId = DirRelationshipTypeTable::findBySystemType(str2enum(DirSystemRelationshipType , dependentContract.parmRelationShipType())).RelationshipTypeId;
DirPartyRelationship.update();
ttsCommit;

}

select forUpdate personPrivateDetails
where personPrivateDetails.Person == dirPersonName.Person;
ttsBegin;
personPrivateDetails.Person = dirPersonName.Person;
personPrivateDetails.FCC_RelativeInEPG = NoYes::Yes;
personPrivateDetails.FCC_IsRelativeInEPG = dependentContract.parmDependentEmployee();
personPrivateDetails.update();
ttsCommit;
msg =’successfully : Updated’;
}
}
}
}
else
{
throw error(“Error:Empty contract”);
}
ttsCommit;
}
catch
{
msg = infolog.text(infologLine());
infolog.clear();
}
return msg;
}

vendor tax registration number x++

static void vendorTaxRegNum(Args _args)
{
TaxRegistration taxRegistration;
DirPartyLocation dirPartyLocation;
VendTable vendTable;

select registrationNumber
from taxRegistration
join DirPartyLocation
where DirPartyLocation.IsPrimary == NoYes::Yes
&& taxRegistration.DirPartyLocation == dirPartyLocation.RecId
join vendTable
where DirPartyLocation.Party == vendTable.Party
&& vendTable.AccountNum == “V0001”; // vend Account

info(taxRegistration.registrationNumber);
}

Create Applicant x++

[
SysEntryPointAttribute(true),
AifCollectionTypeAttribute(“_hrOnBoardingContract”,Types::Class,classStr(FCC_AgencyAccessToESSContract)),
AifCollectionTypeAttribute(“return”,Types::String)
]
public str createApplicant(FCC_AgencyAccessToESSContract _agencyAccessToESSContract)
{
HcmApplicant hcmApplicant;
HcmAllPersonRecId person;
FirstName personName;
DirPartyRecId partyRecId;
DirPersonName dirPersonName;
RecId dirPersonRecid;
DirPerson dirPerson, dirPersonLocal, dirPersonUpdate;
DirPartyTable dirPartyTable;
HcmPersonPrivateDetails hcmPersonPrivateDetails;
HcmApplicantId applicantId;
str msg;

try
{
ttsBegin;
if (_agencyAccessToESSContract)
{

if(!person)
{
personName = _agencyAccessToESSContract.parmFirstName()+” “+_agencyAccessToESSContract.parmMiddleName()+” “+_agencyAccessToESSContract.parmLastName();

select firstOnly dirPersonName
join dirPersonLocal
where dirPersonName.Person == dirPersonLocal.RecId
join dirPartyTable
where dirPersonLocal.RecId == dirPartyTable.RecId
&& dirPersonName.FirstName == _agencyAccessToESSContract.parmFirstName()
&& dirPersonName.MiddleName == _agencyAccessToESSContract.parmMiddleName()
&& dirPersonName.LastName == _agencyAccessToESSContract.parmLastName();

if(dirPersonName)
{
applicantId = this.getHcmApplicantId();
hcmApplicant.ApplicantId = applicantId;
hcmApplicant.Person = dirPersonLocal.RecId;
hcmApplicant.insert();

this.identificationDetails( dirPersonLocal.RecId,
_agencyAccessToESSContract.parmCivilId(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmCivilIdValidFrom(),
_agencyAccessToESSContract.parmCivilIdValidTo());

this.identificationDetails( dirPersonLocal.RecId,
_agencyAccessToESSContract.parmPassportNumber(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmPassportValidFrom(),
_agencyAccessToESSContract.parmPassportValidTo());

select hcmPersonPrivateDetails
where hcmPersonPrivateDetails.Person == dirPersonLocal.RecId;
if(!hcmPersonPrivateDetails)
{

hcmPersonPrivateDetails.Person = dirPersonLocal.RecId;
hcmPersonPrivateDetails.Gender = _agencyAccessToESSContract.parmGender();
hcmPersonPrivateDetails.BirthDate = _agencyAccessToESSContract.parmBirthDate();
hcmPersonPrivateDetails.FCC_TotalYearsOfExperiance = _agencyAccessToESSContract.parmTotalYearsOfExperiance();
hcmPersonPrivateDetails.insert();
}
else
{
select forUpdate hcmPersonPrivateDetails
where hcmPersonPrivateDetails.Person == dirPersonLocal.RecId;

{
//hcmPersonPrivateDetails.Person = dirPersonLocal.RecId;
hcmPersonPrivateDetails.Gender = _agencyAccessToESSContract.parmGender();
hcmPersonPrivateDetails.BirthDate = _agencyAccessToESSContract.parmBirthDate();
hcmPersonPrivateDetails.FCC_TotalYearsOfExperiance = _agencyAccessToESSContract.parmTotalYearsOfExperiance();
hcmPersonPrivateDetails.update();
}
}

select forUpdate dirPersonUpdate
where dirPersonUpdate.RecId == dirPersonLocal.RecId;
//ttsBegin;
dirPersonUpdate.Nationality = _agencyAccessToESSContract.parmNationality();
dirPersonUpdate.update();
//ttsCommit;

msg = (“Applicant is created”);
}
else
{
partyRecId = DirPartyTable::createNew(DirPartyType::Person, personName).RecId;
dirPersonRecId = DirPerson::find(partyRecId).RecId;
dirPersonLocal = DirPerson::find(partyRecId);

dirPersonName.FirstName = _agencyAccessToESSContract.parmFirstName();
dirPersonName.MiddleName = _agencyAccessToESSContract.parmMiddleName();
dirPersonName.LastName = _agencyAccessToESSContract.parmLastName();
dirPersonName.Person = dirPersonRecId;

if (dirPersonName.validateWrite())
{
dirPersonName.insert();
}
applicantId = this.getHcmApplicantId();
hcmApplicant.ApplicantId = applicantId;

this.identificationDetails( dirPersonLocal.RecId,
_agencyAccessToESSContract.parmCivilId(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmCivilIdValidFrom(),
_agencyAccessToESSContract.parmCivilIdValidTo());

this.identificationDetails( dirPersonLocal.RecId,
_agencyAccessToESSContract.parmPassportNumber(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmPassportValidFrom(),
_agencyAccessToESSContract.parmPassportValidTo());

if(dirPersonRecId != hcmApplicant.Person)
{
hcmApplicant.Person = dirPersonRecId;
hcmApplicant.insert();

hcmPersonPrivateDetails.Person = dirPersonLocal.RecId;
hcmPersonPrivateDetails.Gender = _agencyAccessToESSContract.parmGender();
hcmPersonPrivateDetails.BirthDate = _agencyAccessToESSContract.parmBirthDate();
hcmPersonPrivateDetails.FCC_TotalYearsOfExperiance = _agencyAccessToESSContract.parmTotalYearsOfExperiance();
hcmPersonPrivateDetails.insert();

select forUpdate dirPersonUpdate
where dirPersonUpdate.RecId == dirPersonLocal.RecId;
//ttsBegin;
dirPersonUpdate.Nationality = _agencyAccessToESSContract.parmNationality();
dirPersonUpdate.update();
//ttsCommit;
}
msg = (“Applicant is created with new person”);
}
}
}
else
{
throw error(‘Error:Empty contract’);
}
ttsCommit;
}
catch
{
msg = infolog.text(infologLine());
infolog.clear();
}
return msg;
}

update Applicant AIF x++

[
SysEntryPointAttribute(true),
AifCollectionTypeAttribute(“_hrOnBoardingContract”,Types::Class,classStr(FCC_AgencyAccessToESSContract)),
AifCollectionTypeAttribute(“ApplicantId”,Types::String,extendedTypeStr(HcmApplicantId)),
AifCollectionTypeAttribute(“return”,Types::String)
]
public str updateApplicantDetails(FCC_AgencyAccessToESSContract _agencyAccessToESSContract)
{
HcmApplicant hcmApplicant;
HcmAllPersonRecId person;
FirstName personName;
DirPartyRecId partyRecId;
DirPersonName dirPersonName;
RecId dirPersonRecid;
DirPerson dirPerson, dirPersonLocal, dirPersonUpdate;
DirPartyTable dirPartyTable;
HcmPersonPrivateDetails hcmPersonPrivateDetails;
HcmApplicantId applicantId;
str msg;

try
{
ttsBegin;
if (_agencyAccessToESSContract)
{
select hcmApplicant
join dirPerson
join dirPersonName
where dirPersonName.Person == dirPerson.RecId
&& hcmApplicant.Person == dirPerson.RecId
join dirPartyTable
where dirPerson.RecId == dirPartyTable.RecId
&& hcmApplicant.ApplicantId == _agencyAccessToESSContract.parmApplicantId();

select forUpdate hcmPersonPrivateDetails
where hcmPersonPrivateDetails.Person == dirPerson.RecId;

hcmPersonPrivateDetails.Gender = _agencyAccessToESSContract.parmGender();
hcmPersonPrivateDetails.BirthDate = _agencyAccessToESSContract.parmBirthDate();
hcmPersonPrivateDetails.FCC_TotalYearsOfExperiance = _agencyAccessToESSContract.parmTotalYearsOfExperiance();
hcmPersonPrivateDetails.update();

select forUpdate dirPersonUpdate
where dirPersonUpdate.RecId == dirPerson.RecId;

dirPersonUpdate.Nationality = _agencyAccessToESSContract.parmNationality();
dirPersonUpdate.update();

this.identificationDetails( dirPerson.RecId,
_agencyAccessToESSContract.parmCivilId(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmCivilIdValidFrom(),
_agencyAccessToESSContract.parmCivilIdValidTo());

this.identificationDetails( dirPerson.RecId,
_agencyAccessToESSContract.parmPassportNumber(),
_agencyAccessToESSContract.parmIdentificationType(),
_agencyAccessToESSContract.parmPassportValidFrom(),
_agencyAccessToESSContract.parmPassportValidTo());

msg = (“Applicant is update”);
ttsCommit;
}
else
{
throw error(‘Error:Empty Contract’);
}
}
catch
{
msg = infolog.text(infologLine());
infolog.clear();
}
return msg;
}

create Applicant through x++

static void creatingApplicant(Args _args)
{
HcmApplicant hcmApplicant;
DirPerson dirperson;
DirPersonName dirPersonName;
NumberSeq sequence;
HcmApplicantId applicantId;
RecId person, dirPersonRecid;
DirPartyRecId partyRecId;
Name personName;

personName = “Khadar” +” ” +”shaikh”+ ” ” + “test”;
partyRecId = DirPartyTable::createNew( DirPartyType::Person, personName).RecId;

dirPersonRecId = DirPerson::find(partyRecId).RecId;

dirPersonName.FirstName = “Khadar”;
dirPersonName.MiddleName = “shaikh”;
dirPersonName.LastName = “test”;
dirPersonName.Person = dirPersonRecId;

if (dirPersonName.validateWrite())
{
dirPersonName.insert();
}
sequence = NumberSeq::newGetNum( HRMParameters::numRefApplicantId());
applicantId = sequence.num();

hcmApplicant.ApplicantId = applicantId;

if(dirPersonRecId != hcmApplicant.Person)
{
hcmApplicant.Person = dirPersonRecId;
hcmApplicant.insert();
}
}

create or update customer along with details through x++

static void CreateAndUpdateCustomer(Args _args)
{
LogisticsElectronicAddress logisticselectronicaddress;
LogisticsContactInfoView logisticsContactInfoView;
LogisticsPostalAddress logisticspostaladdress;
LogisticsLocation logisticslocation;
CustTable custTable;
DirParty dirParty;
DirPartyLocation dirPartyLocation;
DirPartyContactInfoView dirPartyContactInfo;
DirPartyTable dirPartyTable;

ContactPerson contactperson;

DirPartyPostalAddressView dirPartyPostalAddressView;

AccountNum accountNum = ‘Test_10′;
CustGroupId custGroupId = ’10’;
Name name = ‘Test_10’;

custTable = CustTable::find(accountNum);

if(!custTable) // if customer not exits
{

ttsBegin;
custTable.clear();
custTable.initValue();

custTable.AccountNum = accountNum;
custTable.CustGroup = custGroupId;

custTable.insert(DirPartyType::Organization, name);

dirParty = DirParty::constructFromCommon(custTable);

dirPartyPostalAddressView.LocationName = ‘Test_10’;
dirPartyPostalAddressView.City = ‘Karmimnagar’;
dirPartyPostalAddressView.Street = ‘Towercircle’;
dirPartyPostalAddressView.StreetNumber = ‘123’;
dirPartyPostalAddressView.CountryRegionId = ‘IND’;

dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);
// inserting phone number details
dirPartyContactInfo.LocationName = ‘SouthStreet Contact Phone’;
dirPartyContactInfo.Locator = ‘55125341’;
dirPartyContactInfo.Type = LogisticsElectronicAddressMethodType::Phone;
dirPartyContactInfo.IsPrimary = NoYes::Yes;
dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
// inserting email details
dirPartyContactInfo.LocationName = ‘SouthStreet Contact email’;
dirPartyContactInfo.Locator = ‘soth@gmail.com’;
dirPartyContactInfo.Type = LogisticsElectronicAddressMethodType::Email;
dirPartyContactInfo.IsPrimary = NoYes::Yes;
dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
// inserting fax details
dirPartyContactInfo.LocationName = ‘SouthStreet Contact fax’;
dirPartyContactInfo.Locator = ‘+91451’;
dirPartyContactInfo.Type = LogisticsElectronicAddressMethodType::Fax;
dirPartyContactInfo.IsPrimary = NoYes::Yes;

// Fill Contacts
dirParty.createOrUpdateContactInfo(dirPartyContactInfo);
ttsCommit;
}

else
{
custTable = CustTable::find(accountNum); //if customer exist

dirParty = DirParty::constructFromCommon(custTable);

while select dirPartyLocation
where dirPartyLocation.Party == custTable.Party
join dirPartyPostalAddressView
where dirPartyPostalAddressView.Location == dirPartyLocation.Location
&& dirPartyPostalAddressView.Party == dirPartyLocation.Party
{
dirPartyPostalAddressView.LocationName = ‘Hyderabad2 ‘;
dirPartyPostalAddressView.City = ‘Hyderabad2’;
dirPartyPostalAddressView.Street = ‘HUda colony2′;
dirPartyPostalAddressView.StreetNumber = ’22’;
dirPartyPostalAddressView.CountryRegionId = ‘IND’;
dirPartyPostalAddressView.IsPrimary = 1;
dirParty.createOrUpdatePostalAddress(dirPartyPostalAddressView);

}
//for updating email address
while select dirPartyLocation
where dirPartyLocation.Party == custTable.Party
{
logisticslocation = logisticslocation::find(dirPartyLocation.Location);
while select forUpdate logisticselectronicaddress
where logisticselectronicaddress.Location == logisticslocation.RecId
&& logisticselectronicaddress.Type == LogisticsElectronicAddressMethodType::Email
&& logisticselectronicaddress.IsPrimary == NoYes::Yes
{
//info(strFmt(“%1”,logisticselectronicaddress.Locator));
ttsBegin;

logisticselectronicaddress.Locator = “Test@gmail2.com”;
logisticselectronicaddress.IsPrimary = NoYes::Yes;
logisticselectronicaddress.update();
info(strFmt(“%1”,logisticselectronicaddress.Locator));

ttsCommit;
}
}
//for updating phone number
while select dirPartyLocation
where dirPartyLocation.Party == custTable.Party
{
logisticslocation = logisticslocation::find(dirPartyLocation.Location);
while select forUpdate logisticselectronicaddress
where logisticselectronicaddress.Location == logisticslocation.RecId
&& logisticselectronicaddress.Type == LogisticsElectronicAddressMethodType::Phone
&& logisticselectronicaddress.IsPrimary == NoYes::Yes
{
//info(strFmt(“%1”,logisticselectronicaddress.Locator));
ttsBegin;

logisticselectronicaddress.Locator = “989898989”;
logisticselectronicaddress.IsPrimary = NoYes::Yes;
logisticselectronicaddress.update();
info(strFmt(“%1”,logisticselectronicaddress.Locator));

ttsCommit;
}
}
//for updating Fax number
while select dirPartyLocation
where dirPartyLocation.Party == custTable.Party
{
logisticslocation = logisticslocation::find(dirPartyLocation.Location);
while select forUpdate logisticselectronicaddress
where logisticselectronicaddress.Location == logisticslocation.RecId
&& logisticselectronicaddress.Type == LogisticsElectronicAddressMethodType::Fax
&& logisticselectronicaddress.IsPrimary == NoYes::Yes
{
ttsBegin;

logisticselectronicaddress.Locator = “2578”;
logisticselectronicaddress.IsPrimary = NoYes::Yes;
logisticselectronicaddress.update();
info(strFmt(“%1”,logisticselectronicaddress.Locator));

ttsCommit;
}
}
}
}

currency exchange rate for given date and currency x++

private ExchRate getExchangeRate(AmountMST amountCur , CurrencyCode currencyCode ,Transdate _createdDatetime)
{
ExchRate _exchRate = 0;
ExchrateSecondary _exchrateSecondary = 0;
ExchRatesTriangulation _exchRatesTriangulation = UnknownNoYes::Unknown;
real temp,ret;

temp= Currency::mstAmount(amountCur, currencyCode, createdDatetime, exchRatesTriangulation, exchRate, exchrateSecondary);

if (temp>0 || temp<0)
{
if (temp== amountCur)
ret = 1.0;
else
ret=temp/amountCur;
}
return ret;
}

workers / employees under line manager x++

static void workerUnderLineManager(Args _args)
{
HcmWorker hcmWorker;
HcmPositionWorkerAssignment workerAssignment;
HcmPosition hcmPosition;
HcmPositionDetail hcmPositionDetail;
HcmPositionHierarchy hcmPositionHierarchy;

while select recid, person , PersonnelNumber from hcmWorker
join worker, position from workerAssignment
where workerAssignment.Worker == hcmWorker.RecId
join recid from hcmPosition
where hcmPosition.RecId == workerAssignment.Position
join hcmPositionHierarchy
where hcmPositionHierarchy.Position == hcmPosition.RecId
&& hcmPositionHierarchy.ParentPosition == 5637153727 // pass the position here
join hcmPositionDetail
where hcmPositionDetail.Position == hcmPosition.RecId

{
info(strFmt(“Name :%1’s , EmployeeId :%2 , position :%3 , Reporting to:%4 “,hcmWorker.name(),hcmWorker.PersonnelNumber,
hcmPositionDetail.Description,hcmPosition::find(hcmPositionHierarchy.ParentPosition).description()));
}
}

sales responsible name while SO conformation x++

HcmWorker::find(custConfirmJour.salestable().WorkerSalesResponsible).name();

Civil Id of a employee (kuwait region) x++

static void getCivilId(Args _args)
{
HcmWorker hcmWorker;
HcmPersonIdentificationNumber hcmPersonIdentificationNumber;
DirPerson dirPerson;
HcmIdentificationType hcmIdentificationType;

select hcmWorker
where hcmWorker.PersonnelNumber == “854”
join dirPerson
where dirPerson.RecId == hcmWorker.Person
join hcmPersonIdentificationNumber
where hcmPersonIdentificationNumber.Person == dirPerson.RecId
join hcmIdentificationType
where hcmIdentificationType.RecId == hcmPersonIdentificationNumber.IdentificationType
&& hcmIdentificationType.IdentificationTypeId == “Civil id”;

info(strFmt(“%1”,hcmPersonIdentificationNumber.IdentificationNumber));
info(strFmt(“%1”,hcmIdentificationType.IdentificationTypeId));
}

Employee details through x++

static void EmployeeDetails(Args _args)
{
HcmWorker hcmWorker;
DirPartyTable dirPartyTable;
DirPartyLocation dirPartyLocation;
LogisticsPostalAddress logisticsPostalAddress;
LogisticsLocation logisticsLocation;
HcmPersonPrivateDetails hcmPersonPrivateDetails;
HcmEmployment hcmEmployment;
LogisticsElectronicAddress logisticsElectronicAddress;
HcmWorkerTitle hcmWorkerTitle;
HcmTitle hcmTitle;
HcmPositionWorkerAssignment hcmPositionWorkerAssignment;
HcmPositionDetail hcmPositionDetail;
HcmPosition hcmPosition;
HcmJob hcmJob;
OMOperatingUnit oMOperatingUnit;


select hcmWorker where hcmWorker.Person == 5637144585
join dirPartyTable where dirPartyTable.RecId == hcmWorker.Person
join hcmPersonPrivateDetails where hcmPersonPrivateDetails.Person == hcmWorker.Person
join hcmEmployment where hcmEmployment.Worker == hcmWorker.RecId
join dirPartyLocation where dirPartyLocation.Party == dirPartyTable.RecId
join logisticsPostalAddress where logisticsPostalAddress.Location == dirPartyLocation.Location;

select dirPartyLocation where dirPartyLocation.Party == dirPartyTable.RecId
join logisticsLocation where logisticsLocation.RecId == dirPartyLocation.Location
join logisticsElectronicAddress where logisticsElectronicAddress.Location == logisticsLocation.RecId
&& logisticsElectronicAddress.Type == LogisticsElectronicAddressMethodType::Phone;

while select hcmPositionWorkerAssignment where hcmPositionWorkerAssignment.Worker == hcmWorker.RecId
join hcmPosition where hcmPosition.RecId == hcmPositionWorkerAssignment.Position
join hcmPositionDetail where hcmPositionDetail.Position == hcmPosition.RecId
join hcmJob where hcmJob.RecId == hcmPositionDetail.Job
join oMOperatingUnit where oMOperatingUnit.RecId == hcmPositionDetail.Department
&& oMOperatingUnit.OMOperatingUnitType == OMOperatingUnitType::OMDepartment
{
info(strFmt(“Name of Worker : %1 , Date of Birth : %2 , Date Of Joining : %3 , Address : %4 , Phone : %5, Department : %6 , Postion : %7 , Designation : %8 , Job : %9” ,
dirPartyTable.Name,hcmPersonPrivateDetails.BirthDate,hcmEmployment.ValidFrom,logisticsPostalAddress.Address,logisticsElectronicAddress.Locator,
oMOperatingUnit.Name,hcmPosition.PositionId,hcmPositionDetail.Description,hcmJob.JobId));
}
}

Job for position x++

static void JobForPosition(Args _args)
{
HcmJob hcmJob;
HcmPositionDetail hcmPositionDetail;
HcmPosition hcmPosition;

select hcmJob
join hcmPositionDetail
where hcmJob.RecId == hcmPositionDetail.Job
join hcmPosition
where hcmPositionDetail.Position == hcmPosition.RecId
&& hcmPosition.PositionId == “P00215”; //Position Id

info(strFmt(“%1—%2”, hcmJob.JobId, hcmJob.description()));
}

Employee reporting to x++

static void empReportingTo(Args _args)
{
HcmWorker hcmWorker;
HcmPositionWorkerAssignment workerAssignment;
HcmPosition hcmPosition;
HcmPositionDetail hcmPositionDetail;
HcmPositionHierarchy hcmPositionHierarchy; // declare this table to get report to position

select Person, RecId, PersonnelNumber from hcmWorker
where hcmWorker.PersonnelNumber == “854” //personnel Number
join workerAssignment
where workerAssignment.Worker == hcmWorker.RecId
join hcmPosition
where hcmPosition.RecId == workerAssignment.Position
join hcmPositionHierarchy
where hcmPositionHierarchy.Position == hcmPosition.RecId
join hcmPositionDetail
where hcmPositionDetail.Position == hcmPosition.RecId;

info(strFmt(“Name :%1’s , EmployeeId :%2 , position :%3 , Reporting to:%4 “,hcmWorker.name(),hcmWorker.PersonnelNumber,
hcmPositionDetail.Description,hcmPosition::find(hcmPositionHierarchy.ParentPosition).description()));
}

Title for employee x++

static void empTitle(Args _args)
{
HcmTitle hcmTitle;
HcmWorker hcmWorkerTitle;
HcmPositionDetail hcmPositionDetailTitle;
HcmPosition hcmPositionTitle;
HcmPositionWorkerAssignment workerAssignmentTitle;
str title;

select hcmWorkerTitle
where hcmWorkerTitle.PersonnelNumber == "977" //Personnel Number
join workerAssignmentTitle
where workerAssignmentTitle.Worker == hcmWorkerTitle.RecId
join hcmPositionTitle
where workerAssignmentTitle.Position == hcmPositionTitle.RecId
join hcmPositionDetailTitle
where hcmPositionTitle.RecId == hcmPositionDetailTitle.Position
join hcmTitle
where hcmPositionDetailTitle.Title == hcmTitle.RecId;

title = hcmTitle.TitleId;
info(strFmt("%1", title));
}

position of worker / employee x++

static void PositionOfWorker(Args _args)
{
HcmWorker hcmWorker;
HcmPositionWorkerAssignment workerAssignment;
HcmPosition hcmPosition;
HcmPositionDetail hcmPositionDetail;
FCC_EssUser essUser;

while select hcmWorker
where hcmWorker.PersonnelNumber == “854”
join workerAssignment
where workerAssignment.Worker == hcmWorker.RecId

join recid from hcmPosition
where hcmPosition.RecId == workerAssignment.Position
join hcmPositionDetail
where hcmPositionDetail.Position == hcmPosition.RecId
{
info(strFmt(“Worker : %1, Position : %2”,hcmWorker.name(), hcmPositionDetail.Description));
}
}

assigned jobs for worker/employee x++

static void JobsForPersonnelNum(Args _args)
{
HcmWorker hcmworker,worker;
HcmPositionWorkerAssignment hcmPositionWorkerAssignment;
HcmPositionDetail hcmPositionDetail;
HcmPosition hcmPosition;
HcmPositionHierarchy hcmpositionHierarchy;
HcmJob hcmJob;
HcmJobDetail hcmJobDetail;
HcmTitle hcmTitle;

while select hcmPositionWorkerAssignment
join Worker
where hcmPositionWorkerAssignment.Worker == worker.RecId
&& worker.PersonnelNumber == “977” //Personnel Number
join hcmPosition where hcmPosition.RecId == hcmPositionWorkerAssignment.Position
join hcmPositionDetail where hcmPositionDetail.Position == hcmPosition.RecId
join hcmJob where hcmJob.RecId == hcmPositionDetail.Job
join hcmJobDetail where hcmJobDetail.job == hcmJob.RecId
join hcmTitle where hcmTitle.RecId == hcmJobDetail.Title
{
info(strFmt(“%1—%2—%3”, hcmJob.JobId, worker.PersonnelNumber, hcmTitle.TitleId));
}
}

convert any value to string while reading data from excel x++

str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
{
switch (_cv.variantType())
{
case (COMVariantType::VT_BSTR):
return _cv.bStr();

case (COMVariantType::VT_R4):
return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_R8):
return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_DECIMAL):
return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);

case (COMVariantType::VT_DATE):
return date2str(_cv.date(),123,2,1,2,1,4);

case (COMVariantType::VT_EMPTY):
return “”;

default:
throw error(strfmt(“@SYS26908”, _cv.variantType()));
}
return “”;
}

Update vendTrans Table while PO invoicing x++

/*Go to PurchFormLetter_Invoice
Add below code to get buffers in afterOperationEnd Method*/

protected void afterOperationEnd()
{
FormletterOutputContract purchFormLetterOutputContract;
ParmId parmId,parmID2;
Purchparmline purchParmLineTable;
PurchParmTable purchParmTable;
purchline purchlineTable;
Amount purchPreviousPrice,purchCurrentPrice;
InventTableModule inventTableModuleTable;
VendInvoiceJour vendInvoiceJournal;
Amount costPrice,profitPercentage,salesPrice,salesCost,salesOverHead;
VendTrans updateVendTrans;

str journalLines;

VendInvoiceTrans vendInvoiceTrans;
VendInvoiceInfoTable vendInvoiceInfoTable;

super();

purchFormLetterOutputContract = this.getOutputContract();

journalLines = purchFormLetterOutputContract.parmJournalLines();
vendInvoiceJournal = purchFormLetterOutputContract.parmJournal() as VendInvoiceJour;

if (purchFormLetterOutputContract.parmNumberOfOrdersPosted() > 0)
{
select vendInvoiceInfoTable where vendInvoiceInfoTable.ParmId==vendInvoiceJournal.ParmId
&& vendInvoiceInfoTable.PurchId==vendInvoiceJournal.PurchId;

select forupdate updateVendTrans where updateVendTrans.Voucher==vendInvoiceJournal.LedgerVoucher
&& updateVendTrans.TransDate == vendInvoiceJournal.InvoiceDate
&& updateVendTrans.AccountNum == vendInvoiceJournal.InvoiceAccount;
if (updateVendTrans.RecId)
{
ttsbegin;
updateVendTrans.Txt=vendInvoiceInfoTable.Description;
updateVendTrans.doUpdate();
ttscommit;
}
}
}