Tuesday, 26 February 2019

update project categories (Remain to Select) through batch process in D365

class INTC_ProjCategoryUpdateBatchJob   extends SysOperationServiceController
{
    public static void main(Args args)
    {
        INTC_ProjCategoryUpdateBatchJob  controller;
   
        controller              = new INTC_ProjCategoryUpdateBatchJob();
        controller.startOperation();
    }

    public void new()
    {
        super();
 
        this.parmClassName(classStr(INTC_ProjCategoryUpdateBatchJob));
        this.parmMethodName(methodStr(INTC_ProjCategoryUpdateBatchJob, projCategory));
   
        this.parmDialogCaption("Assign Category to Project");
    }

    public void ProjCategory()
    {
        ResourceRecId                       resourceRecId;
        ProjTable                           projTable;
        ProjValProjCategorySetUp            projValProjCategorySetUp;
        ProjCategory                        projCategory;



        ProjParameters                      projParm;
        projParm    = ProjParameters::find();
        if(projParm.INTC_AssignCatProj   == NoYes::Yes)
        {
            while select ProjTable
                where ProjTable.INTC_BillableProject    == NoYes::Yes
            {
                while select projCategory
                {
                    select forupdate projValProjCategorySetUp
                        where projValProjCategorySetUp.ProjId       == ProjTable.ProjId
                        &&    projValProjCategorySetUp.CategoryId   == projCategory.CategoryId;

                    if(!projValProjCategorySetUp)
                    {
                        projValProjCategorySetUp.ProjId         =  ProjTable.ProjId;
                        projValProjCategorySetUp.CategoryId     =  projCategory.CategoryId;
                        projValProjCategorySetUp.insert();
                    }
                    else
                    {
                        ttsbegin;
                        projValProjCategorySetUp.ProjId         =  ProjTable.ProjId;
                        projValProjCategorySetUp.CategoryId     =  projCategory.CategoryId;
                        projValProjCategorySetUp.update();
                        ttscommit;
                    }
                }
            }
        }
    }

}

To identify caller form name x++

Form —> datasource—->init
 
    FormDataSource          formDataSource;
    FormName                   formName;
    FormRun                      caller;
    super();

    formDataSource      = this.dataSource() as FormDataSource;
    if(formDataSource)
   {
        formName    = formDataSource.formRun().name();
        caller            = formDataSource.formRun().args().caller();

        if(caller && caller.args().name() == formStr(CustTable))
        {
//your logic
}
    }

Thursday, 21 February 2019

all about hijri calendar D365

using Microsoft.Dynamics.ApplicationPlatform.Environment;
using Microsoft.Dynamics.ApplicationPlatform.Environment.Settings;
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

public static class ALM_Global


    public static str startDateHijri(str _date)
    {
        int d,m,y;
        TransDate dt,dt1;
        str finalDate;
        str hijriDate = _date;
        dt = str2Date(hijriDate,213);
        d = dayOfMth(dt);
        m = mthofyr(dt);
        y = year(dt);
        var hdate = new DateTime(y,m, 1);
       
        finalDate = hdate.ToString("MM/dd/yyyy");
        return finalDate;
    }

    public static str endDateHijri(str _date)
    {
        int days,d,m,y;
        TransDate dt,dt1;
        str finalDate;
        str hijriDate = _date;

        dt = str2Date(hijriDate,213);
        d = dayOfMth(dt);
        m = mthofyr(dt);
        y = year(dt);

        UmAlQuraCalendar cal = new UmAlQuraCalendar();
        days = cal.GetDaysInMonth(y, m);
       // var hdate = new DateTime(y,m, days);
        finalDate = int2Str(m)+'/'+int2Str(days)+'/'+int2Str(y);
       // finalDate = hdate.ToString("MM/dd/yyyy");
        return finalDate;
    }

    public static str hijriToGregorian(str _hijriDate)
    {
        System.Globalization.CultureInfo arCul = new System.Globalization.CultureInfo("ar-SA");
        System.Globalization.CultureInfo enCul = new System.Globalization.CultureInfo("en-US");
        System.DateTime tempDateTime;
        str strTemp,finalDate,hDate,hmonth,hYear;
        System.String[] arr;
        date grDate;
        str hijriDate;
        ;
        //grDate = str2Date(_hijriDate,123);
        //hDate = date2Str(_hijriDate,123,DateDay::Digits2,DateSeparator::Slash,DateMonth::Digits2,DateSeparator::Slash,DateYear::Digits4);
        //all expected dates formats
        arr = new System.String[4]();
       
        arr.SetValue("dd/MM/yyyy", 0);
        arr.SetValue("M/dd/yyyy" , 1);
        arr.SetValue("M/d/yyyy"  , 2);
        arr.SetValue("MM/dd/yyyy", 3);
       
        if(_hijriDate != '')
        {
            tempDateTime = System.DateTime::ParseExact(_hijriDate, arr, arCul, System.Globalization.DateTimeStyles::AllowWhiteSpaces);
            strTemp = tempDateTime.ToString("MM/dd/yyyy");
            //grDate = str2date(strTemp, 123);
            finalDate = strTemp;
        }
        return finalDate;
    }

    public static str getMonthHijri(TransDate date, int periods)
    {
        str hDate,hmonth,hYear,finalDate;
        int gDate,gMonth,gYear;
        ;
        gDate  = dayOfMth(_date);
        gMonth = mthOfYr(_date);
        gYear  = year(_date);

        // Sets a DateTime of the Gregorian calendar.
        DateTime myDT = new DateTime(gYear,gMonth,gDate, new GregorianCalendar());
     
        // Creates an instance of the HijriCalendar.
        HijriCalendar myCal = new HijriCalendar();
       
        myDT     = myCal.AddMonths( myDT, _periods );
        hDate    = int2Str(myCal.GetDayOfMonth(myDT));
        hmonth   = int2Str(myCal.GetMonth(myDT));
        hYear    = int2Str(myCal.GetYear(myDT));
        finalDate = hmonth+"/"+hdate+"/"+hYear;
        return finalDate;

    }

    public static str getNextMonthHijri(str date, int periods)
    {
        str hDate,hmonth,hYear,finalDate,hijriDate, dt1,dt2;
        int gDate,gDate1,gMonth,gYear;
        ;
        dt1 = strDel(_date,1,3);
        //info(a);
        dt2 = strDel(dt1,3,5);

        //Info(b);
        gDate  = str2Int(dt2);
        gMonth = str2Int(strDel(_date,3,8));
        gYear  = str2Int(strDel(_date,1,6));

        //// Sets a DateTime of the Gregorian calendar.
        DateTime myDT = new DateTime(gYear,gMonth,gDate, new HijriCalendar());
     
        // Creates an instance of the HijriCalendar.
        HijriCalendar myCal = new HijriCalendar();
       
        myDT     = myCal.AddMonths( myDT, _periods );
        hDate    = int2Str(myCal.GetDayOfMonth(myDT));
        hmonth   = int2Str(myCal.GetMonth(myDT));
        hYear    = int2Str(myCal.GetYear(myDT));
        finalDate = hmonth+"/"+hdate+"/"+hYear;
        return finalDate;

    }

    public static str getNextWeekHijri(str date, int periods)
    {
        str hDate,hmonth,hYear,finalDate,hijriDate, dt1,dt2;
        int gDate,gDate1,gMonth,gYear;
        ;
        dt1 = strDel(_date,1,3);
        //info(a);
        dt2 = strDel(dt1,3,5);

        //Info(b);
        gDate  = str2Int(dt2);
        gMonth = str2Int(strDel(_date,3,8));
        gYear  = str2Int(strDel(_date,1,6));

        //// Sets a DateTime of the Gregorian calendar.
        DateTime myDT = new DateTime(gYear,gMonth,gDate, new HijriCalendar());
     
        // Creates an instance of the HijriCalendar.
        HijriCalendar myCal = new HijriCalendar();
       
        myDT     = myCal.AddWeeks( myDT, _periods );
        hDate    = int2Str(myCal.GetDayOfMonth(myDT));
        hmonth   = int2Str(myCal.GetMonth(myDT));
        hYear    = int2Str(myCal.GetYear(myDT));
        finalDate = hmonth+"/"+hdate+"/"+hYear;
        return finalDate;

    }

    public static str getHijriDate(TransDate _date)
    {
        int gDate,gMonth,gYear;
        gDate  = dayOfMth(_date);
        gMonth = mthOfYr(_date);
        gYear  = year(_date);
     

        System.Globalization.CultureInfo arCul = new System.Globalization.CultureInfo("ar-SA");
        DateTime dt = new DateTime(gYear, gMonth, gDate);
        str s = dt.ToString("M/dd/yyyy", arCul);
        //MessageBox.Show(s);
        return s;
    }

}

Control level validating in D365

[FormControlEventHandler(formControlStr(ProjJournalTransEmpl, ctrlProjQty), FormControlEventType::Validating)]
    public static void ctrlProjQty_OnValidating(FormControl sender, FormControlEventArgs e)
    {
        ProjJournalTrans            projJournalTransLocal;
        real                        chargeable, nonChargeable, tempQty, validQty;
        boolean                     flag;
        FormDataSource              projFds             =   sender.formRun().dataSource('ProjJournalTrans');
        ProjJournalTrans            projJournalTrans    =   projFds.cursor().orig();
        FormRun                     element             =   sender.formRun();
        FormRealControl             qty                 =   element.design().controlName("ctrlProjQty");
        FormControl                 postButton          =   element.design().controlName("PostJournal");
        ProjCategory                projCategory;


        while select  projJournalTransLocal
        where projJournalTransLocal.JournalId == projJournalTrans.JournalId
        && projJournalTransLocal.RecId      != projJournalTrans.RecId
        {
            projCategory    =   ProjCategory::find(projJournalTransLocal.CategoryId);
            if(projCategory.INTC_IsChargeable   ==  NoYes::No)
            {
                nonChargeable   +=   projJournalTransLocal.Qty;
            }
            else
            {
                chargeable      +=   projJournalTransLocal.Qty;
            }
        }
        validQty        =   qty.realValue() + (chargeable + nonChargeable);

        if(validQty != 0)
        {
            postButton.enabled(false);
            checkFailed(strFmt("Entered hours do not match the criteria : %1", validQty));
        }
        else
        {
            postButton.enabled(true);
        }
    }

Tuesday, 12 February 2019

Dimension values as lookup for string control D365

[FormControlEventHandler(formControlStr(ProjTable, ProjTable_INTC_ReferralDepartment), FormControlEventType::Lookup)]
    public static void ProjTable_INTC_ReferralDepartment_OnLookup(FormControl sender, FormControlEventArgs e)
    {
        SysTableLookup          sysTableLookup = SysTableLookup::newParameters(tablenum(DimensionAttributeValue), sender, true);
        Query                   qr = new Query();
        QueryBuildDataSource    queryBuildDataSource;
        QueryBuildRange         queryBuildRange;
        DimensionAttribute      dimAttribute;

        dimAttribute = DimensionAttribute::findByName("D_Department");
        qr.addDataSource(tablenum(DimensionAttributeValue)).addRange(fieldNum(DimensionAttributeValue,DimensionAttribute)).value(queryValue(dimAttribute.RecId));
        sysTableLookup.addLookupMethod(tableMethodStr(DimensionAttributeValue, getname));
        sysTableLookup.addLookupMethod(tableMethodStr(DimensionAttributeValue, getValue), true);
        sysTableLookup.parmQuery(qr);
        sysTableLookup.parmUseLookupValue(true);
        sysTableLookup.performFormLookup();
    }

Monday, 11 February 2019

current record in a lookup event handler D365

[ExtensionOf(FormStr(ProjJournalTransEmpl))]
final public class INTC_ProjCategoerylookUp_Extension
{
    #define.datasourceName("ProjJournalTrans")
    #define.projName("NON CHARGEABLE")
    [FormControlEventHandler(formControlStr(ProjJournalTransEmpl, ProjJournalTrans_CategoryId), FormControlEventType::Lookup)]
    public void ProjJournalTrans_CategoryId_OnLookup(FormControl sender, FormControlEventArgs e)
    {
        FormControlCancelableSuperEventArgs formControlCancelSuper = e as FormControlCancelableSuperEventArgs;
        formControlCancelSuper.CancelSuperCall();

        ProjJournalTrans            projJournalTrans;
        ProjTable                   projTable;
        SysTableLookup              sysTableLookUp;
        QueryBuildDataSource        qbds;
        Query                       query = new Query();
        FormDataSource              projJournalTrans_ds;
       
        projJournalTrans_ds     =   sender.formRun().dataSource(#datasourceName);
        projJournalTrans        =   projJournalTrans_ds.cursor();
        projTable               =   ProjTable::find(projJournalTrans.ProjId);

        sysTableLookUp          =   SysTableLookup::newParameters(tableNum(ProjCategory), sender, true);
        sysTableLookUp.addLookupfield(fieldNum(ProjCategory, CategoryId));
        sysTableLookUp.addLookupfield(fieldNum(ProjCategory, name));

        qbds    =   query.addDataSource(tableNum(ProjCategory));
        if(projTable.Name   ==  #projName)
        {
            qbds.addRange(fieldNum(ProjCategory, CategoryId)).value(strfmt("NC*"));
        }
        else
        {
            qbds.clearRanges();
        }
        sysTableLookUp.parmQuery(query);
        sysTableLookup.parmUseLookupValue(true);
        sysTableLookUp.performFormLookup();
    }

}

Sunday, 10 February 2019

onActivated controls visibility D365

class INTC_ButtonVisibility
{
    [FormDataSourceEventHandler(formDataSourceStr(ProjJournalTable, ProjJournalTable), FormDataSourceEventType::Activated)]
    public static void ProjJournalTable_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)
    {
        ProjJournalTable        projJournalTable        = sender.cursor();
        FormDataSource          projJournalTable_ds     = sender.formRun().dataSource("ProjJournalTable");
        FormRun                 element                 = sender.formRun();
        FormControl             reverseButton           = element.design(0).controlName("ProjJournalCopyReverse");
     
        reverseButton.enabled(false);
    }

    [FormDataSourceEventHandler(formDataSourceStr(ProjJournalTransEmpl, ProjJournalTrans), FormDataSourceEventType::Activated)]
    public static void ProjJournalTrans_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)
    {

        ProjJournalTrans        projJournalTrans        = sender.cursor();
        FormDataSource          projJournalTrans_ds     = sender.formRun().dataSource("ProjJournalTrans");
        FormRun                 element                 = sender.formRun();
        FormControl             lineLogImage            = element.design(0).controlName("lineLogImage");
     
        projJournalTrans_ds.object(fieldNum(ProjJournalTrans, ActivityNumber)).visible(false);
        projJournalTrans_ds.object(fieldNum(ProjJournalTrans, Resource)).visible(false);
        projJournalTrans_ds.object(fieldNum(ProjJournalTrans, ReverseEntry)).visible(false);
        projJournalTrans_ds.object(fieldNum(ProjJournalTrans, ReverseDate)).visible(false);
        lineLogImage.visible(false);
    }

}

Create hour journals from time sheet lines D365

class INTC_HourJournalCreate
{
    public void getTimesheet(TransDate          _fromDate,
                             TransDate          _toDate,
                             TSTimesheetNbr     _timesheetNumber,
                             NoYesId            _posted)
    {
        TSTimesheetTable                        timesheetTable;
        TSTimesheetLine                         timesheetLine;
        TSTimesheetLineWeek                     timesheetLineWeek;
        real                                    hours;
        TransDate                               createdDate;

        if(_fromDate && _toDate && _timesheetNumber)
        {
            while select timesheetTable
                join timesheetLine
                where timesheetLine.TimesheetNbr == timesheetTable.TimesheetNbr
                join timesheetLineWeek
                where timesheetLine.RecId   ==  timesheetLineWeek.TSTimesheetLine
                && timesheetTable.ApprovalStatus == TSAppStatus::Approved
                && timesheetTable.TimesheetNbr == _timesheetNumber
                && timesheetTable.PeriodFrom >= _fromDate
                && timesheetTable.PeriodTo   <= _toDate
         
                {
                    createdDate =   DateTimeUtil::date(timesheetLine.CreatedDateTime);
                    this.createJournal(timesheetTable.TimesheetNbr,
                                       timesheetTable.Resource,
                                       createdDate,
                                       timesheetLine.ProjId,
                                       timesheetLine.CategoryId,
                                       timesheetLineWeek.totalHours(),
                                       timesheetLine.RecId,
                                       _posted);
                }
        }
        else if(!_fromDate && !_toDate && !_timesheetNumber)
        {
            while select timesheetTable
                join timesheetLine
                where timesheetLine.TimesheetNbr == timesheetTable.TimesheetNbr
                join timesheetLineWeek
                where timesheetLine.RecId   ==  timesheetLineWeek.TSTimesheetLine
                && timesheetTable.ApprovalStatus == TSAppStatus::Approved
            {
                createdDate =   DateTimeUtil::date(timesheetLine.CreatedDateTime);
                this.createJournal(timesheetTable.TimesheetNbr,
                                   timesheetTable.Resource,
                                   createdDate,
                                   timesheetLine.ProjId,
                                   timesheetLine.CategoryId,
                                   timesheetLineWeek.totalHours(),
                                   timesheetLine.RecId,
                                   _posted);
            }
        }

        else if(_fromDate && _toDate && !_timesheetNumber)
        {
            while select timesheetTable
                join timesheetLine
                where timesheetLine.TimesheetNbr == timesheetTable.TimesheetNbr
                join timesheetLineWeek
                where timesheetLine.RecId   ==  timesheetLineWeek.TSTimesheetLine
                && timesheetTable.ApprovalStatus == TSAppStatus::Approved
                && timesheetTable.PeriodFrom >= _fromDate
                && timesheetTable.PeriodTo   <= _toDate
            {
                createdDate =   DateTimeUtil::date(timesheetLine.CreatedDateTime);
                this.createJournal(timesheetTable.TimesheetNbr,
                                   timesheetTable.Resource,
                                   createdDate,
                                   timesheetLine.ProjId,
                                   timesheetLine.CategoryId,
                                   timesheetLineWeek.totalHours(),
                                   timesheetLine.RecId,
                                   _posted);
            }
        }
        else if(!_fromDate && !_toDate && _timesheetNumber)
        {
            while select timesheetTable
                join timesheetLine
                where timesheetLine.TimesheetNbr == timesheetTable.TimesheetNbr
                join timesheetLineWeek
                where timesheetLine.RecId   ==  timesheetLineWeek.TSTimesheetLine
                && timesheetTable.ApprovalStatus == TSAppStatus::Approved
                && timesheetTable.TimesheetNbr == _timesheetNumber
            {
                createdDate =   DateTimeUtil::date(timesheetLine.CreatedDateTime);
                this.createJournal(timesheetTable.TimesheetNbr,
                                   timesheetTable.Resource,
                                   createdDate,
                                   timesheetLine.ProjId,
                                   timesheetLine.CategoryId,
                                   timesheetLineWeek.totalHours(),
                                   timesheetLine.RecId,
                                   _posted);
            }
        }
    }

    public void createJournal(TSTimesheetNbr    _timesheetNbr
                             ,RecId             _worker
                             ,TransDate         _date
                             ,ProjId            _projId
                             ,ProjCategoryId    _categoryId
                             ,real              _totalHours
                             ,RecId             _lineRecId
                             ,NoYesId           _posted)
    {
        ProjJournalTableData                    JournalTableData;
        ProjJournalTransData                    journalTransData;
        ProjJournalTable                        journalTable, journalTableUpdate, journalTableLocal;
        ProjJournalTrans                        journalTrans, journalTransLocal;
        ProjTable                               projTable;
        ProjInvoiceTable                        projInvoiceTable;
        NumberSeq                               numberSeq;
        ProjJournalCheckPost                    jourPost;
        ProjQtyEmpl                             qty;
        JournalNumOfLines                       numOfLines;
        ProjHourCostPrice                       projHourCostPrice;
        boolean                                 flag;
        boolean                                 validJournal;
     
        select journalTableLocal where journalTableLocal.INTC_TSTimesheetNbr == _timesheetNbr;
        select projHourCostPrice where projHourCostPrice.CategoryId ==  _categoryId;
     
        ttsBegin;
        journalTableData = JournalTableData::newTable(journalTable);
        journalTransData = journalTableData.journalStatic().newJournalTransData(journalTrans, journalTableData);
        // Init JournalTable -- header
        journalTable.clear();
        journalTable.JournalId              =   journalTableData.nextJournalId();
        journalTable.JournalType            =   ProjJournalType::Hour;
        journalTable.JournalNameId          =   "Hours";
        journalTable.Description            =   "Hour, Timesheet";
        journalTable.initFromProjJournalName(ProjJournalName::find(journalTable.JournalNameId));
        journalTable.INTC_TSTimesheetNbr    =   _timesheetNbr;
        journalTable.insert();

        // Init JournalTrans -- lines
        journalTableData.initFromJournalName(journalTableData.journalStatic().findJournalName(journalTable.JournalNameId));
        journalTrans.clear();
        journalTransData.initFromJournalTable();
        projTable                               =       ProjTable::find(_projId);
        projInvoiceTable                        =       projTable.projInvoice();
        journalTrans.setTransDate();
        journalTrans.TransDate                  =       systemDateGet();
        journalTrans.ProjTransDate              =       _date;
        journalTrans.ProjId                     =       projTable.ProjId;
        journalTrans.Qty                        =       _totalHours;
        journalTrans.CategoryId                 =       _categoryId;
        journalTrans.INTC_RevenueRecoveryPerc   =       projTable.INTC_ProjRecoveryPerc;
        if(projTable.INTC_ProjRecoveryPerc !=0)
            journalTrans.CostPrice              =       (projHourCostPrice.CostPrice*journalTrans.INTC_RevenueRecoveryPerc)/100;
        else
            journalTrans.CostPrice              =       projHourCostPrice.CostPrice;
        journalTrans.LinePropertyId             =       'Billable';
        journalTrans.Resource                   =       _worker;
        journalTrans.ActivityNumber             =       '';
        journalTrans.Txt                        =       'Hour Journal from Timesheet';
        journalTrans.DefaultDimension           =       projTable.DefaultDimension;
        journalTrans.TaxGroupId                 =       ProjParameters::taxGroupInvoice(projTable.ProjId);
        if (projInvoiceTable.CurrencyId)
            journalTrans.CurrencyId             =       projInvoiceTable.CurrencyId;
        else
            journalTrans.CurrencyId             =       Ledger::accountingCurrency(CompanyInfo::current());
        if (journalTrans.Worker)
        {
            journalTrans.setHourPrices();
            journalTrans.setPeriodDate();
        }
        numberSeq = NumberSeq::newGetVoucherFromId(journalTable.VoucherNumberSequenceTable, false);
        journalTrans.Voucher            =  numberSeq.voucher();
        journalTrans.INTC_RefRecid      =  _lineRecId;
        journalTransData.create();
        ttsCommit;
        info(strFmt("Approved Hour Journal : %1 Created", journalTable.JournalId));

        validJournal        =   this.checkPMSValue(journalTrans.ProjId);

        if(journalTable.Posted == NoYes::No && _posted == NoYes::Yes && validJournal == NoYes::Yes)
        {
            jourPost = ProjJournalCheckPost::newJournalCheckPost(true,true,JournalCheckPostType::Check,tableNum(ProjJournalTable),journalTable.JournalId);
            jourPost = ProjJournalCheckPost::newJournalCheckPost(true,true,JournalCheckPostType::Post,tableNum(ProjJournalTable), journalTable.JournalId);
            jourPost.run();
        }
    }

    public boolean checkPMSValue(ProjId  _projId)
    {
        ProjJournalTrans                projJournalTrans;
        FormDataSource                  projJournalTrans_ds;

        ProjJournalTable                journalTable, journalTableUpdate, journalTableLocal;
        ProjJournalTrans                journalTrans, journalTransLocal;
        real                            timesheetValue, contractValue;
        ProjTable                       projTable;
        ProjInvoiceTable                projInvoiceTable;
        PSAContractLineItems            projContractLine;
        Name                            projId, contractId;
        ProjOnAccTrans                  projOnAccTrans;

        boolean                         validJournal;


        while select journalTable
            join journalTrans
            where journalTable.JournalId == journalTrans.JournalId
            && journalTrans.ProjId == _projId
        {
            timesheetValue  +=   journalTrans.Qty * journalTrans.CostPrice;
        }
        while select projOnAccTrans
            where projOnAccTrans.ProjID ==  _projId
        {
            projId          =   projOnAccTrans.ProjId;
            contractValue   +=  projOnAccTrans.TotalSalesAmountCur;
        }

        if(timesheetValue > contractValue)
        {
            validJournal    =   false;
        }
        else
        {
            validJournal    =   true;
        }

        return validJournal;
    }

}

Wednesday, 6 February 2019

dialog field custom lookup in D365

class INTC_HourJournalDialog extends RunBase
{
    DialogField                 fieldTimesheetNbr;
    DialogField                 fieldFromDate;
    DialogField                 fieldToDate;
    DialogRunbase               dialog;
    DialogGroup                 dialogGroup;
    TSTimesheetTable            timesheetTable;
    TSTimesheetNbr              timesheetNumber;
    TransDate                   fromDate, toDate;
    FormBuildStringControl      timesheetNbrControl;

    public container pack()
    {
        return conNull();
    }

    public boolean unpack(container packedClass)
    {
        return true;
    }

    public void timesheetNbrLookup(FormStringControl _control)
    {
        SysTableLookup              sysTableLookUp;
        QueryBuildDataSource        qbds;
        Query                       query = new Query();

        qbds            = query.addDataSource(tableNum(TSTimesheetTable));
        sysTableLookUp  = SysTableLookup::newParameters(tableNum(TSTimesheetTable), _control, true);

        sysTableLookUp.addLookupfield(fieldNum(TSTimesheetTable, TimesheetNbr));
        sysTableLookUp.addLookupfield(fieldNum(TSTimesheetTable, PeriodFrom));
        sysTableLookUp.addLookupfield(fieldNum(TSTimesheetTable, PeriodTo));
        sysTableLookUp.addLookupfield(fieldNum(TSTimesheetTable, ApprovalStatus));

        qbds.addRange(fieldnum(TSTimesheetTable,ApprovalStatus)).value(queryvalue(TSAppStatus::Approved));

        sysTableLookUp.parmQuery(query);
        sysTableLookUp.performFormLookup();
    }

    public Object dialog()
    {
        dialog = super();

        dialog.caption( 'Create Hour Journal');

        dialogGroup     =   dialog.addGroup("Main Group");
        dialogGroup.columns(2);
       
        fieldFromDate       = dialog.addField(extendedTypeStr(TransDate), 'From date');
        fieldToDate         = dialog.addField(extendedTypeStr(TransDate), 'To date');
        fieldTimesheetNbr   = dialog.addField(extendedTypeStr(TSTimesheetNbr), 'Timesheet number');

        timesheetNbrControl =   fieldTimesheetNbr.control();
        timesheetNbrControl.registerOverrideMethod(methodstr(FormStringControl, lookUp),methodstr(INTC_HourJournalDialog, timesheetNbrLookup),this);

        return dialog;
    }

    public boolean getFromDialog()
    {
        timesheetNumber =   fieldTimesheetNbr.value();
        fromDate        =   fieldFromDate.value();
        toDate          =   fieldToDate.value();
        return super();
    }

    public void run()
    {
        INTC_HourJournalCreate      journalCreate   =   new INTC_HourJournalCreate();
        timesheetTable = TSTimesheetTable::find(timesheetNumber);
        if (timesheetTable)
        {
            journalCreate.getTimesheet(fromDate, toDate, timesheetNumber);
            info("Approved Hour Journal/Journals Created");
        }
        else
        {
            throw error(strFmt("Timesheet - %1 not found!", timesheetNumber));
        }
    }

    public static void main(Args _args)
    {
        INTC_HourJournalDialog hourJournalDialog = new INTC_HourJournalDialog();

        if (hourJournalDialog.prompt())
        {
            hourJournalDialog.run();
        }
    }

}