Tuesday, April 11, 2023

GSTHelper using x++

 GSTHelper using x++.


class GSTHelper
{
    ITaxDocument                taxDocument;
    Common                      sourceHeader;
    Common                      sourceLine;
    Amount                      CGSTAmount,IGSTAmount,SGSTAmount,reverseAmount,recoverableAmount;
    real                        CGSTRate,IGSTRate,SGSTRate;
    Amount                      CESSAmount;
    real                        CESSRate;

    HSNCode_IN                  HSNOrSACCode;
    Amount                      taxBaseAmount,discountAmount;
    ClassName                   bundlerClassName;

    /*Amount  CGSTAmountMiscChrg,IGSTAmountMiscChrg,SGSTAmountMiscChrg;
    real    CGSTRateMiscChrg,IGSTRateMiscChrg,SGSTRateMiscChrg;*/

    RecId   TaxDocumentRecId;
    boolean isUTGST;

    #define.TaxType('GST')
    #define.CGST('CGST')
    #define.IGST('IGST')
    #define.SGST('SGST')
    #define.CESS('CESS')

    public classname parmBundlerClassName(ClassName _bundlerClassName)
    {
        bundlerClassName = _bundlerClassName;
        return bundlerClassName;
    }

    public Amount parmCGSTAmount(Amount _cgstAmount = CGSTAmount)
    {
        CGSTAmount = _cgstAmount;
        return CGSTAmount;
    }

    public real parmCGSTRate(real _cgstRate = CGSTRate)
    {
        CGSTRate = _cgstRate;
        return CGSTRate;
    }

    public HSNCode_IN parmHSNOrSACCode(HSNCode_IN _HSNOrSACCode = HSNOrSACCode)
    {
        HSNOrSACCode = _HSNOrSACCode;
        return HSNOrSACCode;
    }

    public Amount parmIGSTAmount(Amount _igstAmount = IGSTAmount)
    {
        IGSTAmount = _igstAmount;
        return IGSTAmount;
    }

    public real parmIGSTRate(real _igstRate = IGSTRate)
    {
        IGSTRate = _igstRate;
        return IGSTRate;
    }

    public Amount parmCESSAmount(Amount _cessAmount = CESSAmount)
    {
        CESSAmount = _cessAmount;
        return CESSAmount;
    }

    public real parmCESSRate(real _cessRate = CESSRate)
    {
        CESSRate = _cessRate;
        return CESSRate;
    }

    public boolean parmIsUTGST(boolean _isUTGST = isUTGST)
    {
        isUTGST = _isUTGST;
        return isUTGST;
    }

    public Amount parmSGSTAmount(Amount _sgstAmount = SGSTAmount)
    {
        SGSTAmount = _sgstAmount;
        return SGSTAmount;
    }

    public Amount parmReverseChargeAmount(Amount _reverseAmount = reverseAmount)
    {
        reverseAmount = _reverseAmount;
        return reverseAmount;
    }

    public Amount parmRecoverableAmount(Amount _recoverableAmount = recoverableAmount)
    {
        recoverableAmount = _recoverableAmount;
        return recoverableAmount;
    }

    public real parmsGSTRate(real _sgstRate = sGSTRate)
    {
        SGSTRate = _sgstRate;
        return SGSTRate;
    }

    public Common parmSourceHeader(Common _sourceHeader = sourceHeader)
    {
        sourceHeader = _sourceHeader;
        return sourceHeader;
    }

    public Common parmSourceLine(Common _sourceLine = sourceLine)
    {
        sourceLine = _sourceLine;
        return sourceLine;
    }

    public amount parmTaxBaseAmount(Amount _taxBaseAmount = taxBaseAmount)
    {
        taxBaseAmount = _taxBaseAmount;
        return taxBaseAmount;
    }

    public RecID parmTaxDocumentRecID(RecId _TaxDocumentRecID = TaxDocumentRecId)
    {
        TaxDocumentRecId = _TaxDocumentRecID;
        return TaxDocumentRecId;
    }

    private void initFromSourceHeaderLine(Common sourceHeader,Common sourceLine,ClassName _bundlerClassName = "")
    {
        this.parmSourceHeader(_sourceHeader);
        this.parmSourceLine(_sourceLine);
        this.parmBundlerClassName(_bundlerClassName);
    }

    public void calculate()
    {
        /*#TaxEngineModelFields
        #TaxEngineModelLineMeasures
        #TaxEngineModelFrameworkFields*/

        //#TaxEngineService
        //#Tax

        TaxableDocumentDescriptor           bundler;        
        ITaxableDocument                    taxableDocumentObject;
        ITaxDocumentLine                    iTaxDocumentLine;
        TaxComponentTable_IN                taxComponentTable_IN;
        ITaxDocumentComponentLine           taxDocumentComponentLine;
        ITaxDocumentComponentLineEnumerator taxDocumentComponentLineEnumerator;
        ClassId                             bundlerId;

        bundler = TaxableDocumentDescriptorFactory::getTaxableDocumentDescriptor(sourceHeader);

        if (bundler)
        {
            taxableDocumentObject = TaxableDocumentObject::constructServer(bundler);
            taxDocument = TaxBusinessService::getTaxDocumentBySource(sourceHeader.TableId, sourceHeader.RecId);
            if(!taxDocument)
            {
                bundlerId = className2Id(bundlerClassName);
                if (bundlerId != 0)
                {
                    bundler = TaxableDocumentDescriptor::getTaxDocumentdescriptor(bundlerId, sourceLine);
                    taxableDocumentObject = TaxableDocumentObject::constructServer(bundler);
                    taxDocument = TaxBusinessService::calculateTax(taxableDocumentObject, false);
                }
            }
        }
        if(taxDocument)
        {
            iTaxDocumentLine = taxDocument.findLineBySource(sourceLine.TableId,sourceLine.RecId);


            if(iTaxDocumentLine)
            {                
                this.parmHSNOrSACCode(iTaxDocumentLine.getFieldValue("HSN Code") ? iTaxDocumentLine.getFieldValue("HSN Code") : iTaxDocumentLine.getFieldValue("SAC"));
                this.parmTaxBaseAmount(itaxDocumentLine.getFieldValue("Base Amount"));
                this.parmTaxDocumentRecID(TaxDocument::findByGUID(taxDocument.getGUID()).RecId);
                taxDocumentComponentLineEnumerator = iTaxDocumentLine.componentLines();
                while (taxDocumentComponentLineEnumerator.moveNext())
                {
                    taxDocumentComponentLine = taxDocumentComponentLineEnumerator.current();
                    this.parmRecoverableAmount(taxDocumentComponentLine.getMeasure("Recoverable Amount").value().value());
                    this.parmReverseChargeAmount(taxDocumentComponentLine.getMeasure("Reverse Charge Amount").value().value());
                    
                    switch(taxDocumentComponentLine.metaData().taxComponent())
                    {
                        case #CGST :
                        {
                            this.parmCGSTRate(taxDocumentComponentLine.getMeasure("Rate").value().value());
                            this.parmCGSTAmount(taxDocumentComponentLine.getMeasure("Tax Amount").value().value());
                        }
                        break;
                        case #IGST :
                        {
                            this.parmIGSTRate(taxDocumentComponentLine.getMeasure("Rate").value().value());
                            this.parmIGSTAmount(taxDocumentComponentLine.getMeasure("Tax Amount").value().value());
                        }
                        break;
                        case #SGST :
                        {
                            this.parmSGSTRate(taxDocumentComponentLine.getMeasure("Rate").value().value());
                            this.parmSGSTAmount(taxDocumentComponentLine.getMeasure("Tax Amount").value().value());
                        }
                        break;
                        case #CESS:
                        {
                            this.parmCESSRate(taxDocumentComponentLine.getMeasure("Rate").value().value());
                            this.parmCESSAmount(taxDocumentComponentLine.getMeasure("Tax Amount").value().value());
                        }
                        break;
                    }
                }
            }
        }
    }

    public static GSTHelper constructCalculate(Common sourceHeader,Common sourceLine,classname _bundlerClassName = "")
    {
        GSTHelper gstHelper = new GSTHelper();

        gstHelper.initFromSourceHeaderLine(_sourceHeader,_sourceLine,_bundlerClassName);

        gstHelper.calculate();

        //gstHelper.calculateMiscChrgGST();

        return gstHelper;
    }

}



Keep Daxing!!

Set vendor on hold using x++

 Set vendor on hold using x++.

While inserting the vendor If the vendApproval is yes. I need to hold that vendor. I have used the below code.

[ExtensionOf(tableStr(VendTable))]
internal final class Vendtable_Extension
{
    public void insert()
    {
        next insert();
		
        container con;

        con = conIns(con,1,this);

        if(this.VendorApproval == NoYes::Yes)
        {
            VendTable::updateOnHold(con,
				    CustVendorBlocked::All,
				    dateNull(),
				    false,
				    true,
				    " New Record ");
        }
        
    }
}


Keep Daxing!!

Monday, April 10, 2023

Print current date in report using x++

 Print the current date in the report using x++.


Use any function to print the date:

=formatdatetime(today)


=FORMAT(Cdate(today), "dd-MM-yyyy")


=Report Generation Date: " & FORMAT(Cdate(today), "dd-MM-yyyy")


=Format(Now(), "dd/MM/yyyy hh:mm tt")


="Report generation date:  " & Format(Globals!ExecutionTime,"dd/MM/yyyy  h:mm:ss tt" )


="Report Generation Date: " & Today()

 
=Format(today(), "dd/MM/yyyy")
 
 
=Globals!ExecutionTime


or

=Microsoft.Dynamics.Framework.Reports.DataMethodUtility.ConvertUtcToAxUserTimeZoneForUser
(Parameters!AX_CompanyName.Value, Parameters!AX_UserContext.Value, System.DateTime.UtcNow, 
"d", Parameters!AX_RenderingCulture.Value) & vbCrLf & Microsoft.Dynamics.Framework.Reports.DataMethodUtility.ConvertUtcToAxUserTimeZoneForUser
(Parameters!AX_CompanyName.Value, Parameters!AX_UserContext.Value, System.DateTime.UtcNow, "t", Parameters!AX_RenderingCulture.Value)

Print user details:
 =User!UserID
XUserInfo::find(false, curUserId()).name;   


Keep daxing!!

Sunday, April 9, 2023

Adding a new Financial Dimension tab in purchase requisition form in D365 FO

Adding a new Financial Dimension tab in the purchase requisition form in D365 FO.


 For the Purchase requisition table "Save Data per company" is set No.

So we need to add some extra code. For the Line table in standard, they have developed. I took the reference from there.

Step 1: Add dimension field in Table. Copy from the vendTable. The EDT should be extended with LedgerDimensionValueSet




Step 2: Add dimension control in the form.


In form init method.

	[ExtensionOf(formStr(PurchReqTable))]
	final class PurchReqTable_Extension
	{
	    public void init()
	    {
	        next init();

	        DimensionEntryControl   fCC = DimensionEntryControl as DimensionEntryControl;

	        fCC.parmValidateBlockedForManualEntry(true);     
	    } 
	}


DataSource Active method.

[FormDataSourceEventHandler(formDataSourceStr(PurchReqTable, PurchReqTable), FormDataSourceEventType::Activated)]
public static void PurchReqTable_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)
{
    PurchReqTable    		purchReqTable   =   sender.cursor();
    DimensionEntryControl    	fCC 		=   sender.formRun().design().controlName("DimensionEntryControl") as DimensionEntryControl;

    fCC.parmCompany(curExt());
    fCC.reactivate();
}


TabPage Active method:

[FormControlEventHandler(formControlStr(PurchReqTable, HeaderTabFinancialDimensions), FormControlEventType::PageActivated)]
public static void HeaderTabFinancialDimensions_OnPageActivated(FormControl sender, FormControlEventArgs e)
{
    PurchReqTable    		purchReqTable   = sender.formRun().dataSource(FormDataSourcestr(PurchReqTable, purchReqTable)).cursor();
    DimensionEntryControl    	fCC 		= sender.formRun().design().controlName("DimensionEntryControl") as DimensionEntryControl;

    fCC.parmCompany(curExt());
    fCC.reactivate();
}


Output:





Thursday, April 6, 2023

Consolidation Report using x++

 Consolidation Report using x++.

 I got a requirement to create a consolidation report.

mean I need to fetch the data from multiple companies for this report.

  • I have used change company to get the data from different companies.
  • Before inserting it into my temp table again I have changed to the current company.

    container 	companyCon = ['CMP1','CMP2','CMP3'];
    str			curCompany = curext();

    while select mytable
    {
	for (int j = 1; j <= conLen(companyCon) ; j++)
	{
	    changecompany (conPeek(companyCon, j))
	    {
		// custom code
		// ..........
		//.........
			
		// Before inserting into temp table need to change as current company.
		changecompany (curCompany)
		{
		    ttsbegin;
		    consolidationTmp.insert();
		    ttscommit;
		}
			
	    }
	}
    }



Keep Daxing!!

Monday, April 3, 2023

Import Excel using x++

 Import Excel using x++.


using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.ExcelPackage;
using OfficeOpenXml.ExcelRange;
class ImportExcel
{
    public static void main(Args _args)
    {
        System.IO.Stream            stream;
        ExcelSpreadsheetName        sheeet;
        FileUploadBuild             fileUpload;
        DialogGroup                 dlgUploadGroup;
        FileUploadBuild             fileUploadBuild;
        FormBuildControl            formBuildControl;
        Dialog                      dialog = new Dialog("Import File");

        dlgUploadGroup          = dialog.addGroup('Select the file');
        formBuildControl        = dialog.formBuildDesign().control(dlgUploadGroup.name());
        fileUploadBuild         = formBuildControl.addControlEx(classstr(FileUpload), 'Upload');
        fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);
        fileUploadBuild.fileTypesAccepted('.xlsx');

        if (dialog.run() && dialog.closedOk())
        {
            FileUpload fileUploadControl     = dialog.formRun().control(dialog.formRun().controlId('Upload'));
            FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();

            if (fileUploadResult != null && fileUploadResult.getUploadStatus())
            {
                stream = fileUploadResult.openResult();
                using (ExcelPackage Package = new ExcelPackage(stream))
                {
                    int                         rowCount, i;
                    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++)
                    {
                        str company     = range.get_Item(i, 1).value;
                        str Id          = range.get_Item(i, 2).value;
                        str parentId    = range.get_Item(i, 3).value;
                        str Name        = range.get_Item(i, 4).value;
                    }
                    info("Import completed :)");
                }
            }
            else
            {
                error("Error occurred.");
            }
        }
    }
}


Keep Daxing!!


Sunday, April 2, 2023

Upload file to share Point using x++

 Upload a file to share Point using x++.


using System.IO;
using System.IO.Path;
using Microsoft.Azure;
using Blobstorage = Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Dynamics.Platform.Integration.SharePoint;
using Microsoft.Dynamics.ApplicationPlatform.Services.Instrumentation;
using Microsoft.DynamicsOnline.Infrastructure.Components.SharedServiceUnitStorage;
using Microsoft.Dynamics.AX.Framework.FileManagement;
public class DocumentsUploadToSharePoint// extends RunBaseBatch
{
    str docfiletype;
    Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider storageProvider;
	
    public static void main(Args    args)
    {
        DocumentsUploadToSharePoint documentsUploadToSharePoint = new DocumentsUploadToSharePoint();

        documentsUploadToSharePoint.upload();
    }

    public void upload()
    {
        System.Exception            ex;
        System.IO.Stream            memoryStream;
        Filename 		    fileNameExt; 
	VendTable 		    vendTable;
	DocuRef                	    docuRef;
	DocuValue              	    docuValue;
        str 			    errorMessage;
		
	select * from docuValue
	    join docuref
	        where docuValue.RECID == docuref.VALUERECID
	    join vendTable
		where docuref.REFRECID == vendTable.RECID
		    && vendTable.accountNum =='00000112'
		    && Docuref.REFCOMPANYID == vendTable.DataAreaId;
    
        memoryStream = this.readfromAzureBlob(docuref);
        memoryStream.Seek(0, System.IO.SeekOrigin::Begin);

        fileNameExt =  docuValue.FileName + '.' + docuValue.FileType;
	//str folderPath = "/sites/'new site'/'Folder'";
	str folderPath = "/MyFolder";
	str fileContentType = System.Web.MimeMapping::GetMimeMapping(fileNameExt);

	ISharePointProxy    proxy = null;
	DOCUPARAMETERS      docuParameters;
	str                 src = '';
	str                 hostName = '';

	docuParameters = DOCUPARAMETERS::find();
 
        try
        {
            ttsbegin;
	    if(docuParameters)
	    {
	        src 	    = docuParameters.DefaultSharePointServer;
	        hostName    = builder.Host;  
			
	        System.UriBuilder builder = new System.UriBuilder(src);

	        str externalId = xUserInfo::getCurrentUserExternalId();

	        try
	        {
		    //proxy = SharePointHelper::CreateProxy(hostName, '/', externalId);
		    proxy = SharePointHelper::CreateProxy(hostName, '/sites/MySite', externalId);
	        }
	        catch(Exception::CLRError)
	        {
		    proxy = null;
	        }
	    }
	    if(proxy)
	    {
	        if(SharePointHelper::VerifyAuthentication(proxy))
	        {
		    Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider prov =
		        new Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider(proxy, folderPath);

		    prov.SaveFileWithOverwrite(newguid(), fileNameExt, fileContentType, memoryStream);
	    }
	    else
	    {
	        info('@ApplicationFoundation:SPServerUserNotAuthorized');
	    }
			
        }
        else
        {
	    throw Error("SharePoint connection error");
        }
        ttscommit;
    }
    catch (ex)
    {
       System.Exception e = ex;
       while (e != null)
       {
        errorMessage += e.Message;
	e = e.InnerException;
       }

       if (appl.ttsLevel() > 0)
       {
            ttsabort;
       }

        checkFailed("Process failed");
	error(errorMessage);
    }

    Public System.IO.Stream readfromAzureBlob(DocuRef _docuRef)
    {
        AsciiStreamIo 	file;
        container 	record;
        str 		downloadUrl;
       
	//if (docuValue.FileType != 'PDF')
	//{
	//    continue;
	//}
		
	if (_docuRef.isValueAttached())
        {
	    System.IO.Stream docuRefStream = DocumentManagement::getAttachmentStream(_docuRef);
	    return docuRefStream;
	}
		
        /*if (_docuRef.isValueAttached())
        {
            var docuValueloc = _docuRef.docuValue();
            //downloadUrl = docuValueloc.Path;

            if (!downloadUrl || docuValueloc.Type == DocuValueType::Others)
            {
                str accessToken = DocumentManagement::createAccessToken(_docuRef);
                downloadUrl = Microsoft.Dynamics.AX.Framework.FileManagement.URLBuilderUtilities::GetDownloadUrl(docuValueloc.FileId, accessToken);
            }
			
            //storageProvider = new Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider();
            var  docContents = storageProvider.GetFile(docuValueloc.createLocation());
            //file = AsciiStreamIo::constructForRead(docContents.Content);//File::UseFileFromURL(downloadUrl));
            return docContents.Content;
        }*/
        return null;
    }

}


Keep Daxing!!