Thursday, 11 May 2017

How to get user based security roles using x++ code in Ax 2012 R3

Export user based roles in Ax 2012 R3

static void Export_Userbasedroles(Args _args)
{
    SysExcelApplication         xlsApplication;
    SysExcelWorkBooks           xlsWorkBookCollection;
    SysExcelWorkBook            xlsWorkBook;
    SysExcelWorkSheets          xlsWorkSheetCollection;
    SysExcelWorkSheet           xlsWorkSheet;
    SysExcelRange               xlsRange;
    CustTable                   custTable;
    int                         row = 1;
    str                         fileName;
    SecurityUserRole            _SecurityUserRole;
    SecurityRoleTaskGrant       _SecurityRoleTaskGrant;
    SecurityTask                _SecurityTask;
    SecurityRole                _SecurityRole;
    UserInfo                    _UserInfo;
    
    fileName = @"C:\Users\Rajendra\Desktop\Roles.xlsx";
    xlsApplication           = SysExcelApplication::construct();
    xlsWorkBookCollection    = xlsApplication.workbooks();
    xlsWorkBook              = xlsWorkBookCollection.add();
    xlsWorkSheetCollection   = xlsWorkBook.worksheets();
    xlsWorkSheet             = xlsWorkSheetCollection.itemFromNum(1);
    xlsWorkSheet.cells().item(row,1).value("User Role");
    xlsWorkSheet.cells().item(row,2).value("User Id");
    xlsWorkSheet.cells().item(row,3).value("Legal Entity");
    row++;

    while select _UserInfo
    {
        while select _SecurityUserRole where _SecurityUserRole.User==_UserInfo.id
        {
                while select _SecurityRole where _SecurityRole.RecId==_SecurityUserRole.SecurityRole
                {
                    xlsWorkSheet.cells().item(row,1).value(_SecurityRole.Name);
                    xlsWorkSheet.cells().item(row,2).value(_UserInfo.id);
                    xlsWorkSheet.cells().item(row,3).value(_UserInfo.company);
                    row++;
                }
        }
    }
   
    if(WinApi::fileExists(fileName))
        WinApi::deleteFile(fileName);
    xlsWorkbook.saveAs(fileName);
    xlsApplication.visible(true);

}

From reference 

Sunday, 7 May 2017

How to update financial dimensions for master data using x++ code in Ax 2012

Customers

To update financial dimensions to all legal entities.

static void updateCustomerDimensions(Args _args)
{
    CustTable       custTable;
 
    Struct struct;// = new Struct();
    container           ledgerDimension,com;
    DimensionDefault    DimensionDefault;
    CompanyInfo         companyInfo;

    while select companyInfo where companyInfo.DataArea !="DAT"
    {
        struct = new struct();
        com = conNull();
        changeCompany(companyInfo.DataArea)
        {
            ledgerDimension =conNull();
            com = conIns(com,1,companyInfo.DataArea);
         
            struct.add('LegalEntity',companyInfo.DataArea);
            ledgerDimension += struct.fields();
            ledgerDimension += struct.fieldName(1);
            ledgerDimension += struct.valueIndex(1);


            DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
            //Customers
         
            while select forUpdate crossCompany:com * from custTable
            {
                if(custTable.RecId)
                {
                    ttsBegin;
                    custTable.DefaultDimension = DimensionDefault;
                    custTable.update();
                    info(strFmt("Customer %1 dimension updated -- %2",custTable.AccountNum,custTable.dataAreaId));
                    ttsCommit;
                }
            }
        }
    }


}

Fixed asset

static void updateAssetDimensions(Args _args)
{
    AssetTable      assetTable;
    AssetBook       assetBook;
    Struct struct;// = new Struct();
    container           ledgerDimension,com;
    DimensionDefault    DimensionDefault;
    CompanyInfo         companyInfo;

    while select companyInfo where companyInfo.DataArea !="DAT"
    {
        struct = new struct();
        com = conNull();
        changeCompany(companyInfo.DataArea)
        {
            ledgerDimension =conNull();
            com = conIns(com,1,companyInfo.DataArea);

            struct.add('LegalEntity',companyInfo.DataArea);
            ledgerDimension += struct.fields();
            ledgerDimension += struct.fieldName(1);
            ledgerDimension += struct.valueIndex(1);


            DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
            //Vendors

            while select forUpdate crossCompany:com * from assetBook
            {
                if(assetBook.RecId)
                {
                    ttsBegin;
                    assetBook.DefaultDimension = DimensionDefault;
                    assetBook.update();
                    info(strFmt("Asset %1 dimension updated -- %2",assetBook.assetid,assetBook.dataAreaId));
                    ttsCommit;
                }
            }
        }
    }


}

Update financial dimensions for master data

static void testUpdateCustomerDimensions(Args _args)
{
    CustTable           custTable;
    Struct              struct;
    container           ledgerDimension,com;
    DimensionDefault    DimensionDefault,custDimensionDefault;
    CompanyInfo         companyInfo;

    DimensionAttributeValueSetStorage    dimStorage;
    Counter                              i;
    str                                  BusUnit,CCUnit,Dep,IG;
    ProjId                               projId;
    container                            conDefaultdim;

    struct = new struct();
    com = conNull();

    ledgerDimension =conNull();

    select forUpdate custTable where custTable.AccountNum =="US-011";

    custDimensionDefault = custTable.DefaultDimension;

    dimStorage = DimensionAttributeValueSetStorage::find(custDimensionDefault); //default dimension value

    for (i=1 ; i<= dimStorage.elements() ; i++)
    {
        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name == "BusinessUnit")
        {
            BusUnit = dimStorage.getDisplayValueByIndex(i);
        }
        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name == "CostCenter")
        {
            CCUnit = dimStorage.getDisplayValueByIndex(i);
        }
        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name == "Department")
        {
            Dep = dimStorage.getDisplayValueByIndex(i);
        }
        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name == "ItemGroup")
        {
            IG = dimStorage.getDisplayValueByIndex(i);
        }


        if(DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name == "Project")
        {
            projId = "000003";//dimStorage.getDisplayValueByIndex(i);
        }

    }
    //projId = "000002";

    conDefaultdim = [5,'BusinessUnit',BusUnit,'CostCenter',CCUnit,'Department',Dep,'ItemGroup',IG,'Project',projId];

    DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(conDefaultdim);

    if(custTable.RecId)
    {
        ttsBegin;
        custTable.DefaultDimension = DimensionDefault;
        custTable.update();
        info(strFmt("Customer %1 dimension updated -- %2",custTable.AccountNum,custTable.dataAreaId));
        ttsCommit;
    }


}




Tuesday, 18 April 2017

Due Date calculation using x++ code in Ax 2012 R3

Due Date Calculation
Customers
//Added by Rajendra - Due date calculation on 18-04-2017
public TransDate HM_DueDate()
{
    ProjInvoiceJour   ProjInvoiceJour;
    str s;
   
    select ProjInvoiceJour where ProjInvoiceJour.ProjInvoiceId == custTrans.Invoice;
    if(ProjInvoiceJour.RecId)
    {
        s = strFmt('%1',ProjInvoiceJour.InvoiceDate + PaymTerm::find(custTable::find(custTrans.AccountNum).PaymTermId).NumOfDays);
    }
    else
    {
        if(custTrans.DocumentDate)
        {
            s = strFmt('%1',custTrans.DocumentDate + PaymTerm::find(custTable::find(custTrans.AccountNum).PaymTermId).NumOfDays);
        }
        else
        {
            s = strFmt('%1',datenull());
        }
    }
    return str2Date(s,213);
}


In General Journal due date calculation

ledgerJournalTrans.Payment      = termsofPayment;
if(ledgerJournalTrans.Payment)
{
   ledgerJournalTrans.Due = ledgerJournalEngine.getDueDateBaseDate(ledgerJournalTrans);
   ledgerJournalTrans.Due = PaymCalendarSourceLedgerJournalTrans::getUpdatedDueDate(ledgerJournalTrans,this.paymDayId(ledgerJournalTrans));
}

public PaymDayId paymDayId(LedgerJournalTrans _ledgerJournalTrans)
{
    PaymDayId   paymDayId;
    CompanyId   companyId;
    LedgerJournalEngine ledgerJournalEngine = new ledgerJournalEngine();
    ;

    if (xDataArea::exist(_ledgerJournalTrans.Company))
    {
        companyId =_ledgerJournalTrans.Company;
    }
    else
    {
        companyId = curext();
    }

    changecompany(companyId)
    {
        switch(_ledgerJournalTrans.AccountType)
        {
            case LedgerJournalACType::Cust :
                paymDayId = ledgerJournalEngine.findCustTable(_ledgerJournalTrans).PaymDayId;
                break;

            case LedgerJournalACType::Vend :
                paymDayId = _ledgerJournalTrans.findVendTable().PaymDayId;
                break;

            default :
                paymDayId = '';
        }
    }
    return paymDayId;

}

Friday, 14 April 2017

Purchase Requision through X++ in Ax 2012

Header

private PurchReqId createPurchReqHeader()
{
    PurchReqTable                   purchReqTable;
    ;

    ttsbegin;
    purchReqTable.clear();
    purchReqTable.initValue();
    purchReqTable.PurchReqId        = NumberSeq::newGetNum(PurchReqTable::numRefPurchReqId()).num();
    purchReqTable.PurchReqName      = description;
    purchReqTable.TransDate         = requestedDate;
    purchReqTable.Originator        = HcmWorker::findByPersonnelNumber(workerId).RecId;
    if(purchReqTable.validateWrite())
    {
        purchReqTable.insert();
    }
    ttsCommit;

    return purchReqTable.PurchReqId;

}


Lines

private void createPurchReqLines(PurchReqId                      _purchReqId,
                                 MaterialIndentParmLines     _materialIndentParmLine)
{
    PurchReqLine                        purchReqLine;
    InventDim                           inventDim;
    EcoResCategory                      category;
    PurchReqLineTaxExtensionIN          purchReqLineTaxExtensionIN;
    MaterialIndentTransTable        materialIndentTranstable;
    MaterialIndentLine              materialIndentLine;
    RecId                               recId;
    ;

    // Multi lines created
    purchReqLine.clear();
    purchReqLine.initValue();

    inventdim.InventSiteId              =   dfSite.value();
    inventdim.InventLocationId          =   dfWarehouse.value();
    purchReqLine.InventDimId            =   InventDim::findOrCreate(InventDim).InventDimId;
    purchReqLine.initFromPurchReqTable(PurchReqTable::find(_purchReqId));

    purchReqLine.ItemId                 = _materialIndentParmLine.ItemId;
    purchReqLine.BuyingLegalEntity      = CompanyInfo::find().RecId;
    purchReqLine.InventDimIdDataArea    = curext();

    select * from    category
        where category.Name == _materialIndentParmLine.ProcurementCategory;
    purchReqLine.ProcurementCategory    =  category.RecId;
    purchReqLine.Requisitioner          = HcmWorker::findByPersonnelNumber(workerId).RecId;
    purchReqLine.Name                   = _materialIndentParmLine.ItemName;
    purchReqLine.PurchQty               = _materialIndentParmLine.Qty;
    purchReqLine.PurchUnitOfMeasure     = UnitOfMeasure::findBySymbol(_materialIndentParmLine.UnitOfMeasureSymbol).RecId;
    purchReqLine.CurrencyCode           = CompanyInfo::standardCurrency();
    purchReqLine.TransDate              = today();
    //purchReqLine.initTransDate();
    purchReqLine.initFromEcoResCategory(category.RecId);
    purchReqLine.RequiredDate           = today();
    purchReqLine.PriceUnit              = 1;
    purchReqLine.ItemIdDataArea         = curext();
    purchReqLine.PurchReqTable           = PurchReqTable::findPurchReqId(_purchReqId).RecId;
    purchReqLine.editItemName(true,_materialIndentParmLine.ItemName);

    if(purchReqLine.validateWrite())
    {
        //purchReqLine.insert();
        purchReqLine.createLine(true, true);
        if(SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIN]))
        {
            ttsBegin;
            purchReqLineTaxExtensionIN.selectForUpdate(true);
            purchReqLineTaxExtensionIN.TaxModelDocLineExtensionIN::init(purchReqLine);
            purchReqLineTaxExtensionIN.insert();


            _materialIndentparmline.selectForUpdate(true);
            _materialIndentparmline.MaterialIndentLineStatus    = MaterialIndentLineStatus::PR;
            _materialIndentparmline.update();

            // Updates remaining qty to material indent line and changes the status to submitted if qty = 0
            select forUpdate materialIndentLine
                where materialIndentLine.RecId == _materialIndentparmline.MaterialIndentLinesRecId;

            materialIndentLine.Qty  = _materialIndentparmline.RemainingQty;
            if(_materialIndentparmline.RemainingQty == 0)
            {
                materialIndentLine.MaterialIndentLineStatus = MaterialIndentHeaderStatus::Completed;
            }
            materialIndentLine.update();

            //inserts record in MaterialIndentTrans

            recId = materialIndentTranstable.findbyparmIdMaterialIndentId(_materialIndentparmline.MaterialIndentparmTable, _materialIndentparmline.MaterialIndentId).RecId;
            if(!recId)
            {
                recId = this.insertTransTable(_materialIndentparmline, _purchReqId);
            }
            this.insertTransLines(_materialIndentparmline, recId);
            materialIndentId = _materialIndentparmline.MaterialIndentId;
            }
            ttsCommit;
        info(strFmt("Purchase requisition is created - %1 for an item - %2.", _purchReqId, purchReqLine.ItemId),"", SysInfoAction_Formrun::newFormname(formStr(PurchReqTableListPage)));

    }
}