Search This Blog

Friday, December 5, 2014

Release products to the legal entities using X++ [Dynamics AX 2012]

In this post, I would like to share X++ Code that will help to release products to the legal entities from product master.
In Microsoft Dynamics AX 2012, Microsoft has enhanced the item-product data management framework to provide flexibility and sustainability across the organization.In Microsoft Dynamics AX 2012, all product master data is shared across all companies, and the virtual table collection concept is no longer available for product master data management. The old item representation (InventTable) still exists[msdn]
I will be using 2 legal entities – CEU and newly created legal entity ‘RAX’
[If you want to create new legal entity – Organization administration >> setup >> Organization >> Legal entities >> New]
Let me show you the product master data [a particular product] which I am trying to release using code.

EcoResProductReleaseManagerBase class will help to release products to the legal entities. static method -releaseproduct will release products.

static void SR_ReleaseProducts(Args _args)
{
EcoResProduct ecoResProduct;
;
select firstOnly ecoResProduct where EcoResProduct.DisplayProductNumber == “20003”; //Audio system
EcoResProductReleaseManagerBase::releaseProduct(ecoResProduct.RecId,
CompanyInfo::findDataArea(‘RAX’).RecId);
}

After running the above job, you will see that 20003 product number has been released to legal entity ‘RAX’ as shown below.

I know most of us are very familiar of creating items using code in AX 2009. Now, let me walk through with the equavalent code in AX 2012 [Hope I got it right, please note: This code is an attempt to findout the way it is in AX 2012. Request to test the code in dev environments before using them in live]

static void SR_ReleaseProducts_detailed(Args _args)
{
EcoResProduct ecoResProduct;
InventTable inventTable;
InventTableModule inventTableModule;
NumberSequenceTable numberSequenceTable;
ItemId itemId;
InventItemSetupSupplyType inventItemSetupSupplyType;
EcoResStorageDimensionGroupProduct ecoResStorageDimensionGroupProduct;
EcoResTrackingDimensionGroupProduct ecoResTrackingDimensionGroupProduct;
EcoResStorageDimensionGroupItem ecoResStorageDimensionGroupItem;
EcoResTrackingDimensionGroupItem ecoResTrackingDimensionGroupItem;
;
select firstOnly ecoResProduct where EcoResProduct.DisplayProductNumber == “20003”; //Audio system
changecompany (‘RAX’)
{
ttsBegin;
inventTable = null;
inventTableModule = null;
inventItemSetupSupplyType = null;
ecoResStorageDimensionGroupProduct = null;
ecoResTrackingDimensionGroupProduct = null;
ecoResStorageDimensionGroupItem = null;
ecoResTrackingDimensionGroupItem = null;
numberSequenceTable = InventParameters::numRefItemId().numberSequenceTable();
//get item id from:
//1. Product number if number seq for item ID is not set up or manual or return blank value
if (!numberSequenceTable.RecId || numberSequenceTable.Manual)
{
itemId = ecoResProduct.productNumber();
}
else //number sequence auto, get a number
{
itemId = NumberSeq::newGetNumFromId(numberSequenceTable.RecId).num();
}
inventTable.initValue();
inventTable.initFromEcoResProduct(ecoResProduct);
inventTable.ItemId = ItemId;
inventTable.NameAlias = ecoResProduct.SearchName;
inventTable.insert(true);
// Create inventTableModules
inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Invent;
inventTableModule.insert();
inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Purch;
inventTableModule.insert();
inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Sales;
inventTableModule.insert();
//Create inventItemLocation
InventItemLocation::createDefault(inventTable.ItemId);
// Creates a new item default order type for the product that is released.
inventItemSetupSupplyType.initValue();
inventItemSetupSupplyType.ItemId = inventTable.ItemId;
inventItemSetupSupplyType.ItemDataAreaId = inventTable.DataAreaId;
inventItemSetupSupplyType.insert();
//create relationship tables to dimension groups.
ecoResStorageDimensionGroupProduct = EcoResStorageDimensionGroupProduct::findByProduct(ecoResProduct.RecId);
ecoResTrackingDimensionGroupProduct = EcoResTrackingDimensionGroupProduct::findByProduct(ecoResProduct.RecId);
if (ecoResStorageDimensionGroupProduct.RecId)
{ // mandatory storage dimension group for the product
ecoResStorageDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
ecoResStorageDimensionGroupItem.ItemId = inventTable.ItemId;
ecoResStorageDimensionGroupItem.StorageDimensionGroup = ecoResStorageDimensionGroupProduct.StorageDimensionGroup;
ecoResStorageDimensionGroupItem.insert();
}
if (ecoResTrackingDimensionGroupProduct.RecId)
{ // mandatory tracking dimension group for the product
ecoResTrackingDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
ecoResTrackingDimensionGroupItem.ItemId = inventTable.ItemId;
ecoResTrackingDimensionGroupItem.TrackingDimensionGroup = ecoResTrackingDimensionGroupProduct.TrackingDimensionGroup;
ecoResTrackingDimensionGroupItem.insert();
}
ttsCommit;
info(strfmt(“Product successfully released to ‘RAX’ legal entity”));
}
}

In Microsoft Dynamics AX 2012 inventory dimensions have been divided into the following three categories:
Product dimensions:These correspond to the old item dimensions.
Storage dimensions:These are Site, Warehouse, Location, and Pallet.
Tracking dimensions:These are Batch number and Serial number.

Export to Excel - Dynamics AX Form With Multiple Data Sources

AX 2012 now makes it really easy to output to Excel from a form. Quite simply all you need to do is add a Command button to the form and link it to the command Export to Microsoft Excel. This is great for list pages or any form with a single data source.
However you will find that when several data sources are used on a single form then Ax will output the data from the first data source on the form rather than from the specific data source  that the user is selecting when the Export to Microsoft Excel button is clicked.
Even if you add multiple Export to Microsoft Excel buttons and set the data source individually on the button groups you will still find that the output to Excel is from the first data source of the form.
Now the user can get around this by using CTRL – T from any given grid to export that datasource to Excel but a lot of users may not find it easy to remember which hot key to use.
After a bit of hunting around I have found an easy solution to this issue.
Simply override the Clicked method of the Command button control by calling element.selectControl as shown below: -
void clicked()
{
    element.selectControl(Grid); // The "Grid" argument is the name of the grid
                                 // that you want to export from
 
    super();
}
By keeping track of which grid the user is selecting (override the form datasource Active() methods for example) you can control which grid is exported to Excel.

 

Creating Product or Product Master through X++

static void CreateEcoResProduct(Args _args)
{
    EcoResEcoResProduct_TrackingDimGroup        tracDimGroup;
    EcoResEcoResProduct_Product_Master          productMaster;
    EcoResEcoResProduct_Product_Distinct        distMaster;
    EcoResEcoResProduct_ProductDimGroup         prodDimGroup;
    EcoResEcoResProduct_StorageDimGroup         storDimGroup;
    EcoResEcoResProduct_translation             translation;
    EcoResEcoResProduct_Identifier              identifier;
    EcoResProductService                        ecoProdSvc;
    EcoResProductNumber                         lEcoResProductNumber;
    NumberSequenceTable                         numberSequenceTable;
    EcoResEcoResProduct                         ecoResProd;
    EcoResProductType                           ecoResProductType;
    boolean                                     isMaster = false;
    EcoResProductSearchName                     _ecmProductName;
    EcoResProductSubtype                        prodSubType;
    ;
    prodSubType = EcoResProductSubtype::ProductMaster;
    _ecmProductName = " IDB test 09";
    lEcoResProductNumber = "IDB -099";
    try
    {
        // create product by initializing the Service object
        ecoProdSvc = EcoResProductService::construct();
        // initialize the EcoResEcoResProduct object
        ecoResProd = new EcoResEcoResProduct();
       // numberSequenceTable = EcoResProductParameters::numRefProductNumber().numberSequenceTable(); // Automated
      //  lEcoResProductNumber = NumberSeq::newGetNumFromId(numberSequenceTable.RecId).num(); // Automated
       
       
        ecoResProductType = EcoResProductType::Item;
        if(prodSubType == EcoResProductSubtype::ProductMaster)
        {
            isMaster = true;
            //Create a new product master
            productMaster = new EcoResEcoResProduct_Product_Master();
            //initialize product master
            productMaster.parmDisplayProductNumber(lEcoResProductNumber);
            productMaster.parmProductType(ecoResProductType);
            productMaster.parmSearchName(_ecmProductName);
            productMaster.parmProductType(EcoResProductType::Service);
            productMaster.parmVariantConfigurationTechnology(EcoResVariantConfigurationTechnologyType::PredefinedVariants);
            //create a product master Translation Object
            translation = productMaster.createTranslation().addNew();
            // create a new identifier object
            Identifier = productMaster.createIdentifier().AddNew();
            // Create the ProductDimensionGroup
            prodDimGroup = productMaster.createProductDimGroup().addNew();
            prodDimGroup.parmProduct(lEcoResProductNumber);
            prodDimGroup.parmProductDimensionGroup('Con-Dim');
            // Create the StorageDimgroup object
            storDimGroup = productMaster.createStorageDimGroup().addNew();
            storDimGroup.parmProduct(lEcoResProductNumber);
            storDimGroup.parmStorageDimensionGroup("Con-Dim"); // Storage dimension group
            // Create the TrackingDimGroup object
            tracDimGroup = productMaster.createTrackingDimGroup().addNew();
            tracDimGroup.parmProduct(lEcoResProductNumber);
            tracDimGroup.parmTrackingDimensionGroup("Con-Dim"); // Tracking dimension group
        }
        else
        {
            // Create a new product distinct master
            distMaster = new EcoResEcoResProduct_Product_Distinct();
            // Take the newly created and initialize ProdMaster - variable and fill with product data
            distMaster.parmDisplayProductNumber(lEcoResProductNumber);
            distMaster.parmProductType(ecoResProductType);
            distMaster.parmSearchName(_ecmProductName);
            // Create a translation object
            translation = distMaster.createTranslation().addNew();
            // Create a new identifier object
            Identifier = distMaster.createIdentifier().addNew();
            // Create the StorageDimgroup object
            storDimGroup = distMaster.createStorageDimGroup().addNew();
            storDimGroup.parmProduct(lEcoResProductNumber);
            storDimGroup.parmStorageDimensionGroup("Con-Dim");
            // Create the TrackingDimGroup object
            tracDimGroup = distMaster.createTrackingDimGroup().addNew();
            tracDimGroup.parmProduct(lEcoResProductNumber);
            tracDimGroup.parmTrackingDimensionGroup("Con-Dim");
        }
        // fill the translation object
        translation.parmDescription(_ecmProductName);
        translation.parmLanguageId('en-us');
        //translati
        translation.parmName(_ecmProductName);
        // fill the identifier
        identifier.parmProductNumber(lEcoResProductNumber);
        // add the product to ecoResProd
        if(isMaster)
            ecoResProd.createProduct().add(productMaster);
        else
            ecoResProd.createProduct().add(distMaster);
        // create the product using service
        ecoProdSvc.create(ecoResProd);
    }
    catch(Exception::Error)
    {
        throw Exception::Error;
    }
    catch(Exception::Deadlock)
    {
        retry;
    }
    catch(Exception::UpdateConflict)
    {
        if(appl.ttsLevel() == 0)
        {
            if(xSession::currentRetryCount() >= 4)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }
}

Above code creates the record for product in EcoResProduct Table and Once you get the data in product form(EcoResProduct -Table) you can easily release those product in specified company in a single go, by selecting multiple products. It doesn't take much time as well. Release product will be saved in InventTable. 

 Else use the below method. Pass all the required parameters and get the required result

public container createProduct(str60 _product,
                            str60 _productname,
                            str60 _searchname,                           
                            str60 _desc,
                            str60 _color,
                            str60  _size,
                            str60  _style,
                            str60  _site,
                            str60  _warehouse,
                            Str60  _vendorId,
                            str60  _externalDesc,
                            str60 _countingGroup,
                            str60 _defaultReceipt,
                            str60 _defaultIssue,
                            str60 _defaultLocation,
                            str60 _productDimension,
                            str60  _sizeGrpId,
                            str60  _styleGrpId,
                            str60  _approveStatus,
                            str60  _category)
{
    EcoResProductService erProdSvc;
    EcoResEcoResProduct EcoResProd;
    EcoResEcoResProduct_Product_Master ProdMast;
    EcoResEcoResProduct_Translation Translation;
    EcoResEcoResProduct_Identifier Identifier;
    EcoResEcoResProduct_ProductDimGroup ProdDimGroup;
    boolean                         isVariantExist = false;
    InventDim                       inventDim;
    InventDimCombination            inventDimCombination;
    container productDimensions,displayNumber,ret,sizeColorStyle;
    EcoResDistinctProductVariant        ecoResDistinctProductVariant;
    EcoResProductVariantDimensionValue  EcoResProductVariantDimensionValue;
    RefRecId                                   ecoResDistinctProductVariantRecId;
    EcoResProductReleaseManagerBase     releaseManager;
    CompanyInfo                         companyInfo;
    EcoResProductTranslation            productTranslation;
    RecId           color,size,style;
    Inventtable     inventtable;
    PdsVendorCheckItem vendorCheckItem;
    EcoResCategory          ecoResCategory;
    RetailAttributesGlobalLookup       retailAttributesGlobalLookup;
    CreateProducMaster productMaste = new CreateProducMaster();
    ttsBegin;
    if(!EcoResProduct::findByDisplayProductNumber(_product).RecId)
    {
        //Initialize the service object
        erProdSvc = EcoResProductService::construct();
        EcoResProd = new EcoResEcoResProduct();
        ProdMast = new EcoResEcoResProduct_Product_Master();
        //ProdDimGroup = new EcoResEcoResProduct_ProductDimGroup();
        //Newly created and initialize prodMast
        ProdMast.parmDisplayProductNumber(_product);
        ProdMast.parmProductType(EcoResProductType::Item);
        ProdMast.parmSearchName(_searchname);
        //Create a new translation object:
        Translation = ProdMast.createTranslation().addNew();
        Translation.parmDescription(_desc);
        Translation.parmLanguageId('en-us');
        Translation.parmName(_productname);
        Identifier = ProdMast.createIdentifier().addNew();
        Identifier.parmProductNumber(_product);
        ProdDimGroup = ProdMast.createProductDimGroup().addNew();
        ProdDimGroup.parmProduct(_product);
        ProdDimGroup.parmProductDimensionGroup(_productDimension);
        ProdMast.parmVariantConfigurationTechnology(EcoResVariantConfigurationTechnologyType::PredefinedVariants);
        EcoResProd.createProduct().add(ProdMast);
        erProdSvc.create(EcoResProd);
    }
    select * from ecoResCategory where ecoResCategory.Name == _category;
    select * from retailAttributesGlobalLookup where retailAttributesGlobalLookup.Category == ecoResCategory.RecId;
    sizeColorStyle = productMaste.insertProductDimension(_product,_color,_size,_style,retailAttributesGlobalLookup.VariantColorGroup
                                                    ,retailAttributesGlobalLookup.VariantSizeGroup,retailAttributesGlobalLookup.VariantStyleGroup);
    color = conPeek(sizeColorStyle,1);
    size  = conPeek(sizeColorStyle,2);
    style = conPeek(sizeColorStyle,3);
    if(!color)
        _color = '';
    if(!size)
        _size = '';
    if(!style)
        _style ='';
    productDimensions = EcoResProductVariantDimValue::getDimensionValuesContainer('',_size,_color,_style);
    //if(EcoResProductVariantManager::checkNotExistDistinctProductVariant(EcoResProduct::findByDisplayProductNumber(_product).RecId,
                        //productDimensions) && color && size && style)
    if(!EcoResProductVariantManager::findDistinctProductVariant(EcoResProduct::findByDisplayProductNumber(_product).RecId, productDimensions).RecId && color && size && style)
    {
        ecoResDistinctProductVariant.DisplayProductNumber = EcoResProductNumberBuilderVariant::buildFromProductNumberAndDimensions(
                                                                        _product,
                                                                        productDimensions);
        ecoResDistinctProductVariantRecId = EcoResProductVariantManager::createProductVariant(EcoResProduct::findByDisplayProductNumber(_product).RecId
                                                                ,ecoResDistinctProductVariant.DisplayProductNumber,productDimensions);
    }
    if(!InventTable::find(_product).RecId)
    {
         EcoResProductReleaseManagerBase::releaseProduct(EcoResProduct::findByDisplayProductNumber(_product).RecId
                                                      ,CompanyInfo::findDataArea(curext()).RecId);
    }
    select inventtable where inventtable.ItemId == _product;
    if(inventtable)
    {
        inventtable.selectForUpdate(true);
        inventtable.PdsVendorCheckItem = str2enum(vendorCheckItem,_approveStatus);
        inventtable.doUpdate();
    }
    if(size && color && style)
    {
        inventDim.InventSizeId  = _size;
        inventDim.InventColorId = _color;
        inventDim.InventStyleId = _style;
        isVariantExist = true;
    }
        inventDim.InventSiteId  = _site;
        inventDim.InventLocationId = _warehouse;
        inventDim               = InventDim::findOrCreate(inventDim);
    if(!InventDimCombination::find(_product,inventDim.InventDimId).RecId && ecoResDistinctProductVariantRecId)
    {
        // create InventDimCombination
        inventDimCombination.DistinctProductVariant = ecoResDistinctProductVariantRecId;
        inventDimCombination.ItemId                 = _product;
        inventDimCombination.InventDimId            = inventDim.InventDimId;
        inventDimCombination.Insert();
    }
    ttsCommit;
    ret  = [inventDim.InventDimId,ecoResDistinctProductVariantRecId,isVariantExist];
    return ret;
}