Provision retail component in onebox VM

Provision retail component in onebox VM

Song Nghia - Technical Consultant

Update dbo.USERINFO set Enable = '1' 

Update dbo.RetailTransactionServiceProfile set AzureResource = 'https://usnconeboxax1aos.cloud.onebox.dynamics.com' 

Update dbo.RetailTransactionServiceProfile set ServiceHostUrl = 'https://usnconeboxax1aossoap.cloud.onebox.dynamics.com' 
 
 
Update dbo.RETAILCONNDATABASEPROFILE set ConnectionString = 'AQAAAHNm4l3JT6ikAPoAN//zuzANlILUc2biXclPqKQA+gA3//O7MA2UgtRPAwRDTnplG8+rzS9omxRxmMRG72nKnkzG8RyAzutFnbPmItYRZ3TJ+phMNjDIYIXzV/b/g0sZSExFdZgzDKWya6vZimKx8YCmMCdtl3b8h6VCVnFrRe1f62OKx6kf5DGG9g3JFWv/jfsJRldrgzZv0Wx/+a328WTxKHR/wgNtwTVyzWcc+krMwxLbAnSAtKBYQLD3ewn+MX76SONOmFjp/+sh9Ml5ZcLNHgOQen824hy261hutcBt5XwPYHoUVGw5dVMdurtX9Zp7mrKn0+Ep0W8UuDTbSkaNbm0UaNOVLLMVEIxgy8tIQinx0pz54n12zd0YPo/7NfQUY2Ud2OMNF7kpGZkDSVjUHEsYJRNkHn5g13VSdwxjJOfyy8Ad1y0Czxz4esCGLQWIgboPAXu5KNPYnfnILYVwmZZGLFy3o0TL75zvb6bAREpgSJi38Syjl1pspQm+8Vocs/vNnHpA8eM/f/o63Lx/KIzzwfFi40rVGEPyqgsnvCyMlqXxhnWoeuPEVVscuhEfcE7BCi/Sui2qaExzvNegUHb+G4kEbmBD8EjdHQl7w1a97tYiA+8ZEqsnaUIyrziSwWIUDQsUf7gAwT4bOdke7i8XrK38YRrVrq04U9JZYcvum4DOyEJ6sX7DzSzxUYYS5KBky61n064pO9HJu3idG1ym6Vgi1o/HepDb0TzIjTxJGYHclNVcZz5ttbQCeOOkTW+vnQr6maKzqK44cDdbUgs4Ik2vKagtDo7YToaWv/IcYVI/qSXpbCKLWjd5jsocMgP1+c/AJBouemSOyrvZfKvfoRWk56XAV1ELj0xBxedITv+5P/qWMh0iKeBDTJx1mtBYCaojQ+UPig9vFBUyQB3sE6e6pNGEeuIcv6avPCxnn2SK879vRCwsH6yRSnNpIqaxTQDe6JSKloAEgrZLgYlCOsINlHQi8wkf93BwxWLIXTWYqAmG0Mm1/y04Ydw+0sq+jeUQ' 
 
where Name = 'Default' 
 
 
Update dbo.RETAILCHANNELPROFILEPROPERTY set Value = 'https://usnconeboxax1ret.cloud.onebox.dynamics.com/Commerce' 
 
where ChannelProfile = '5637144576' and key_ = '1'  
 
 
Update dbo.RETAILCHANNELPROFILEPROPERTY set Value = 'https://usnconeboxax1pos.cloud.onebox.dynamics.com' 
 
where ChannelProfile = '5637144576' and key_ = '7' 
 

Update dbo.RETAILCHANNELPROFILEPROPERTY set Value = 'https://usnconeboxax1ret.cloud.onebox.dynamics.com/MediaServer/' 
 
where ChannelProfile = '5637144576' and key_ = '2' 
 
 
EXEC sp_addrolemember 'DataSyncUsersRole','axretaildatasyncuser'; 
 
EXEC sp_addrolemember 'db_owner','axretaildatasyncuser'; 
 
delete crt.DOWNLOADSESSIONDATAFILEHISTORY 
 
delete  ax.retailassortmentlookup




Method to get printers and printers for receipt

Method to get printers and printers for receipt

Song Nghia - Technical Consultant

private ReadOnlyCollection GetPrinters(RequestContext context, string hardwareProfileId, ReceiptType receiptType)
{
 Terminal terminal = context.GetTerminal();
 if (string.IsNullOrEmpty(hardwareProfileId))
 {
  hardwareProfileId = terminal.HardwareProfile;
 }

 GetPrintersDataRequest getPrintersByReceiptTypeDataRequest = new GetPrintersDataRequest(terminal.TerminalId, receiptType, QueryResultSettings.AllRecords, hardwareProfileId);
 IEnumerable printers = context.Execute>(getPrintersByReceiptTypeDataRequest).PagedEntityCollection.Results;
 Printer printer = printers.FirstOrDefault(p => p.PrinterType == (int)DeviceType.WindowsPrinter);

 return new List() { printer }.AsReadOnly();
}

private ReadOnlyCollection GetPrinterForHardcodeReceipt(RequestContext context, string hardwareProfileId, ReceiptType receiptType)
{
 Terminal terminal = context.GetTerminal();
 if (string.IsNullOrEmpty(hardwareProfileId))
  hardwareProfileId = terminal.HardwareProfile;
 GetHardwareProfileDataRequest profileDataRequest = new GetHardwareProfileDataRequest(hardwareProfileId, QueryResultSettings.SingleRecord);
 HardwareProfile entity = context.Runtime.Execute>((Request)profileDataRequest, context).Entity;
 if (entity != null && entity.Printers != null && entity.Printers.Any())
 {
  HardwareProfilePrinter hardwareProfilePrinter = entity.Printers.FirstOrDefault((Func)(printer => (uint)printer.DeviceType > 0U));
  if (hardwareProfilePrinter != null)
   return new List()
 {
  new Printer()
  {
    ReceiptType = receiptType,
    PrintBehavior = PrintBehavior.Always,
    Terminal = terminal == null ? 0L : terminal.RecordId,
    HardwareProfileId = hardwareProfileId,
    Name = hardwareProfilePrinter.DeviceName,
    PrinterType = (int) hardwareProfilePrinter.DeviceType
  }
 }.AsReadOnly();
 }
 return new List().AsReadOnly();
}
How to get all data in shift by CRT

How to get all data in shift by CRT

Song Nghia - Technical Consultant

In this class, You can learn how to get object shift and linking data to object shift like: Tax, Tender, ActiveLine.

public static class LAW_ShiftCalculator
{
 public static void Calculate(
   RequestContext context,
   Shift currentShift,
   string shiftTerminalId,
   long shiftId)
 {
  GetEndOfDayShiftDetailsDataRequest detailsDataRequest = new GetEndOfDayShiftDetailsDataRequest(shiftTerminalId, shiftId, context.GetChannelConfiguration().PriceIncludesSalesTax);
  Shift entity1 = context.Runtime.Execute>((Request)detailsDataRequest, context).Entity;
  LAW_ShiftCalculator.SetShiftSalesTotals(currentShift, entity1);
  LAW_ShiftCalculator.SetShiftTenderLine(currentShift, entity1);
  LAW_ShiftCalculator.SetShiftAccountLines(currentShift, entity1);
  GetShiftTransactionsCountDataRequest countDataRequest = new GetShiftTransactionsCountDataRequest(shiftTerminalId, shiftId);
  Shift entity2 = context.Runtime.Execute>((Request)countDataRequest, context).Entity;
  LAW_ShiftCalculator.SetRetailTransactionCount(currentShift, entity2);
  GetShiftTenderedAmountDataRequest amountDataRequest = new GetShiftTenderedAmountDataRequest(shiftTerminalId, shiftId, QueryResultSettings.AllRecords);
  ReadOnlyCollection results = context.Runtime.Execute>((Request)amountDataRequest, context).PagedEntityCollection.Results;
  LAW_ShiftCalculator.SetShiftTenderLineTenderAmounts(currentShift, (IEnumerable)results);
  if (context.GetChannelConfiguration().CountryRegionISOCode != CountryRegionISOCode.SE)
   return;
  GetEndOfDayShiftDetailsSwedenDataRequest swedenDataRequest = new GetEndOfDayShiftDetailsSwedenDataRequest(currentShift.StoreId, shiftTerminalId, shiftId, context.GetChannelConfiguration().PriceIncludesSalesTax);
  Shift entity3 = context.Runtime.Execute>((Request)swedenDataRequest, context).Entity;
  LAW_ShiftCalculator.SetShiftSalesTotals_SE(currentShift, entity3);
  LAW_ShiftCalculator.SetShiftTaxLine(currentShift, entity3);
 }

 private static void SetShiftSalesTotals(Shift currentShift, Shift shiftTotals)
 {
  currentShift.SalesTotal = shiftTotals.SalesTotal;
  currentShift.ReturnsTotal = shiftTotals.ReturnsTotal;
  currentShift.DiscountTotal = shiftTotals.DiscountTotal;
  currentShift.TaxTotal = shiftTotals.TaxTotal;
  currentShift.PaidToAccountTotal = shiftTotals.PaidToAccountTotal;
  currentShift.SuspendedTransactionCount = shiftTotals.SuspendedTransactionCount;
  currentShift.DepositCollected = shiftTotals.DepositCollected;
  currentShift.DepositRedeemed = shiftTotals.DepositRedeemed;
  currentShift.DepositRefunded = shiftTotals.DepositRefunded;
  currentShift.CancellationCharges = shiftTotals.CancellationCharges;
  currentShift.CustomerOrdersPlaced = shiftTotals.CustomerOrdersPlaced;
  currentShift.CustomerOrdersCanceled = shiftTotals.CustomerOrdersCanceled;
  currentShift.CustomerOrdersVoidedLines = shiftTotals.CustomerOrdersVoidedLines;
  currentShift.CustomerOrdersEdited = shiftTotals.CustomerOrdersEdited;
  currentShift.GiftCardsTotal = shiftTotals.GiftCardsTotal;
  currentShift.GiftCardCashOutTotal = shiftTotals.GiftCardCashOutTotal;
  currentShift.VoidedSalesTotal = shiftTotals.VoidedSalesTotal;
  currentShift.ChargeTotal = shiftTotals.ChargeTotal;
 }

 private static void SetShiftSalesTotals_SE(Shift currentShift, Shift shiftTotals)
 {
  currentShift.ReceiptsCount = shiftTotals.ReceiptsCount;
  currentShift.ReturnsCount = shiftTotals.ReturnsCount;
  currentShift.GoodsSoldQty = shiftTotals.GoodsSoldQty;
  currentShift.ServicesSoldQty = shiftTotals.ServicesSoldQty;
  currentShift.ReceiptCopiesCount = shiftTotals.ReceiptCopiesCount;
  currentShift.ReceiptCopiesTotal = shiftTotals.ReceiptCopiesTotal;
  currentShift.PriceOverrideTotal = shiftTotals.PriceOverrideTotal;
  currentShift.SuspendedTotal = shiftTotals.SuspendedTotal;
  currentShift.SalesTotalIncludingTax = shiftTotals.SalesTotalIncludingTax;
  currentShift.SalesTotalExcludingTax = shiftTotals.SalesTotalExcludingTax;
  currentShift.SalesGrandTotal = shiftTotals.SalesGrandTotal;
  currentShift.ReturnsGrandTotal = shiftTotals.ReturnsGrandTotal;
 }

 private static void SetShiftTenderLine(Shift currentShift, Shift endOfDayShiftDetails)
 {
  currentShift.TenderLines.AddRange((IEnumerable)endOfDayShiftDetails.TenderLines);
 }

 private static void SetShiftAccountLines(Shift currentShift, Shift endOfDayShiftDetails)
 {
  currentShift.AccountLines.AddRange((IEnumerable)endOfDayShiftDetails.AccountLines);
 }

 private static void SetShiftTaxLine(Shift currentShift, Shift endOfDayShiftDetails)
 {
  currentShift.TaxLines.AddRange((IEnumerable)endOfDayShiftDetails.TaxLines);
 }

 private static void SetShiftTenderLineTenderAmounts(
   Shift currentShift,
   IEnumerable shiftTenderLines)
 {
  foreach (ShiftTenderLine shiftTenderLine in shiftTenderLines)
  {
   ShiftTenderLine orCreate = currentShift.TenderLines.FindOrCreate(shiftTenderLine);
   orCreate.CountingRequired = shiftTenderLine.CountingRequired;
   orCreate.TenderCurrency = shiftTenderLine.TenderCurrency;
   orCreate.ChangeLine = shiftTenderLine.ChangeLine;
   if (orCreate.ChangeLine)
   {
    orCreate.ChangeAmountOfTenderCurrency = Decimal.Negate(shiftTenderLine.TenderedAmountOfTenderCurrency);
    orCreate.ChangeAmountOfStoreCurrency = Decimal.Negate(shiftTenderLine.TenderedAmountOfStoreCurrency);
   }
   else
   {
    orCreate.TenderedAmountOfTenderCurrency = shiftTenderLine.TenderedAmountOfTenderCurrency;
    orCreate.TenderedAmountOfStoreCurrency = shiftTenderLine.TenderedAmountOfStoreCurrency;
    orCreate.Count = shiftTenderLine.Count;
   }
  }
 }

 private static ShiftTenderLine FindOrCreate(
   this IList shiftTenderLines,
   ShiftTenderLine tenderLine)
 {
  string tenderTypeId = tenderLine.TenderTypeId;
  string tenderCurrency = tenderLine.TenderCurrency;
  string tenderTypeName = tenderLine.TenderTypeName;
  ShiftTenderLine shiftTenderLine = shiftTenderLines.FirstOrDefault((Func)(p =>
  {
   if (p.TenderTypeId == tenderTypeId)
    return p.TenderCurrency == tenderCurrency;
   return false;
  }));
  if (shiftTenderLine == null)
  {
   shiftTenderLine = new ShiftTenderLine()
   {
    TenderTypeId = tenderTypeId,
    CardTypeId = string.Empty,
    TenderCurrency = tenderCurrency,
    TenderTypeName = tenderTypeName
   };
   shiftTenderLines.Add(shiftTenderLine);
  }
  return shiftTenderLine;
 }

 private static void SetRetailTransactionCount(Shift currentShift, Shift endOfDayShift)
 {
  currentShift.VoidTransactionCount = endOfDayShift.VoidTransactionCount;
  currentShift.NoSaleTransactionCount = endOfDayShift.NoSaleTransactionCount;
  currentShift.RoundedAmountTotal = endOfDayShift.RoundedAmountTotal;
  currentShift.TransactionCount = endOfDayShift.TransactionCount;
  currentShift.CustomerCount = endOfDayShift.CustomerCount;
  currentShift.SaleTransactionCount = endOfDayShift.SaleTransactionCount;
 }
}

Create X-Z Report Receipt Service Request By CRT

Create X-Z Report Receipt Service Request in CRT

Song Nghia - Technical Consultant

private GetReceiptServiceRequest CreateXZReportReceiptServiceRequest(GetXAndZReportReceiptRequest request)
{
 ThrowIf.Null(request, nameof(request));
 long shiftId = request.ShiftId;
 ReceiptType receiptType = request.ReceiptType;
 switch (receiptType)
 {
  case ReceiptType.XReport:
  case ReceiptType.ZReport:
   Shift entity;
   if (receiptType == ReceiptType.XReport)
   {
    string shiftTerminalId = request.ShiftTerminalId;
    entity = this.Context.Execute>((Request)new GetShiftDataRequest(shiftTerminalId, shiftId)).Entity;
    if (entity == null || entity.Status != ShiftStatus.Open && entity.Status != ShiftStatus.BlindClosed)
     throw new DataValidationException(DataValidationErrors.Microsoft_Dynamics_Commerce_Runtime_ShiftNotFound, string.Format("No open shift information can be found using the shift Id {0} on terminal {1} for X report.", (object)shiftId, (object)shiftTerminalId));
    LAW_ShiftCalculator.Calculate(this.Context, entity, entity.TerminalId, entity.ShiftId);
   }
   else
   {
    string terminalId = this.Context.GetTerminal().TerminalId;
    entity = this.Context.Execute>((Request)new GetLastClosedShiftDataRequest(terminalId)).Entity;
    if (entity == null || entity.Status != ShiftStatus.Closed)
     throw new DataValidationException(DataValidationErrors.Microsoft_Dynamics_Commerce_Runtime_ShiftNotFound, string.Format("No closed shift information can be found using the shift Id {0} on terminal {1} for Z report.", (object)shiftId, (object)terminalId));
   }
   return new GetReceiptServiceRequest(entity, new List()
     {
    receiptType
     }.AsReadOnly(), request.HardwareProfileId);
  default:
   throw new DataValidationException(DataValidationErrors.Microsoft_Dynamics_Commerce_Runtime_ReceiptTypeNotSupported, "Only receipt types for X or Z reports are expected.");
 }
}
Print another receipt use PrePrintReceiptCopyTrigger

Print another receipt use PrePrintReceiptCopyTrigger

Song Nghia - Technical Consultant

import * as Triggers from "PosApi/Extend/Triggers/PrintingTriggers";
import { ClientEntities, ProxyEntities } from "PosApi/Entities";
import { PrinterPrintRequest, PrinterPrintResponse } from "PosApi/Consume/Peripherals";
import { ObjectExtensions } from "PosApi/TypeExtensions";
import { GetHardwareProfileClientRequest, GetHardwareProfileClientResponse } from "PosApi/Consume/Device";
import { GetReceiptsClientRequest, GetReceiptsClientResponse } from "PosApi/Consume/SalesOrders";

export default class PrePrintReceiptCopyTrigger extends Triggers.PrePrintReceiptCopyTrigger {
    public execute(options: Triggers.IPrePrintReceiptCopyTriggerOptions): Promise> {
        this.context.logger.logVerbose("Executing PreProductSaleTrigger with options " + JSON.stringify(options) + " at " + new Date().getTime() + ".");

        if (ObjectExtensions.isNullOrUndefined(options)) {

            // This will never happen, but is included to demonstrate how to return a rejected promise when validation fails.
            //ABC
            let error: ClientEntities.ExtensionError
                = new ClientEntities.ExtensionError("The options provided to the PostSuspendTransactionTrigger were invalid.");
            return Promise.reject(error);
        } else {
            return this.context.runtime.executeAsync(new GetHardwareProfileClientRequest())
                .then((response: ClientEntities.ICancelableDataResult)
                    : Promise> => {
                    let hardwareProfile: ProxyEntities.HardwareProfile = response.data.result;
                    // Gets the receipts.
                    let salesOrderId: string = options.salesOrder.Id;
                    let receiptRetrievalCriteria: ProxyEntities.ReceiptRetrievalCriteria = {
                        IsCopy: false,
                        IsRemoteTransaction: false,
                        IsPreview: false,
                        QueryBySalesId: true,
                        ReceiptTypeValue: ProxyEntities.ReceiptType.CustomReceipt6,
                        HardwareProfileId: hardwareProfile.ProfileId
                    };
                    let getReceiptsClientRequest: GetReceiptsClientRequest =
                        new GetReceiptsClientRequest(salesOrderId, receiptRetrievalCriteria);
                    return this.context.runtime.executeAsync(getReceiptsClientRequest);
                })
                .then((response: ClientEntities.ICancelableDataResult)
                    : Promise> => {
                    let receipts: ProxyEntities.Receipt[] = response.data.result;
                    // Prints the receipts.
                    let printerPrintRequest: PrinterPrintRequest = new PrinterPrintRequest(receipts);
                    return this.context.runtime.executeAsync(printerPrintRequest);
                })
        }
    }
}

Link pre: https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-trigger-printing
Share purchase agreement to franchise company.

Share purchase agreement to franchise company.


Song Nghia - Technical consulant

Idea: Franchise company want to get price from source company, so we can understand that franchise company have default vendor is source company.

class LAW_PurchaseTradeAgreementJournalShare extends RunBaseBatch
{
    DialogField fieldCompany;
    companyId   _companyId;
    CompanyId   _currentCompanyId;
    PriceDiscAdmTable   _currentPriceDiscAdmTable;
    Map mapTableGroupVendor = new Map(Types::String, Types::String);
    public Object dialog()
    {
        Dialog dialog;
        ;
        dialog = super();

        dialog.caption("Select company to share");

        fieldCompany   =  dialog.addField(extendedTypeStr(companyId), "Company Id");

        return dialog;
    }

    public boolean getFromDialog()
    {
        // Retrieve values from Dialog
        _companyId = fieldCompany.value();
        return super();
    }

    public PriceDiscAdmTable parmPriceDiscAdmTable(PriceDiscAdmTable priceDiscAdmTable)
    {
        _currentPriceDiscAdmTable = priceDiscAdmTable;
        return _currentPriceDiscAdmTable;
    }

    public void run()
    {
        PriceDiscAdmTable   destinationDiscAdmTable;
        PriceDiscAdmTrans   priceDiscAdmTrans, priceDiscAdmTransGroup, priceDiscAdmTransOrder, destinationPriceDiscAdmTrans;
        PriceDiscTable      priceDiscTable;
        container           contRecId;
        int i;

        _currentCompanyId = curExt();
        try
        {
            ttsbegin;

            changecompany(_companyId)
            {
                destinationDiscAdmTable = this.createPurchTradeAgreementTable(_currentPriceDiscAdmTable);
            }
        
            if(destinationDiscAdmTable)
            {
                //Get smallest price???

                while select ItemRelation from priceDiscAdmTransGroup
                    group by  priceDiscAdmTransGroup.ItemRelation
                     where priceDiscAdmTransGroup.JournalNum == _currentPriceDiscAdmTable.JournalNum
                {
                    select firstonly priceDiscAdmTransOrder
                        order by priceDiscAdmTransOrder.Amount asc
                        where priceDiscAdmTransOrder.JournalNum == _currentPriceDiscAdmTable.JournalNum
                        && priceDiscAdmTransOrder.ItemRelation == priceDiscAdmTransGroup.ItemRelation;

                    contRecId += priceDiscAdmTransOrder.RecId;
                }
                
                for(i = 1; i <= conLen(contRecId); i++)
                {
                    select firstonly priceDiscAdmTrans
                        where priceDiscAdmTrans.RecId == conPeek(contRecId, i);
                    if(priceDiscAdmTrans.PriceDiscTableRef)
                    {
                        //quay ve
                        select firstonly  priceDiscTable
                        where priceDiscTable.RecId == priceDiscAdmTrans.PriceDiscTableRef;
                    }
                    changecompany(_companyId)
                    {
                        destinationPriceDiscAdmTrans = this.createPurchTradeAgreementTrans(destinationDiscAdmTable, priceDiscAdmTrans, priceDiscTable);
                        this.insertTradeAdmTransMap(priceDiscAdmTrans, destinationPriceDiscAdmTrans);
                    }
                }

                /*while select priceDiscAdmTrans
                where priceDiscAdmTrans.JournalNum == _currentPriceDiscAdmTable.JournalNum
                {
                    if(priceDiscAdmTrans.PriceDiscTableRef)
                    {
                        //quay ve
                        select firstonly  priceDiscTable
                        where priceDiscTable.RecId == priceDiscAdmTrans.PriceDiscTableRef;
                    }
                    changecompany(_companyId)
                    {
                        destinationPriceDiscAdmTrans = this.createPurchTradeAgreementTrans(destinationDiscAdmTable, priceDiscAdmTrans, priceDiscTable);
                        this.insertTradeAdmTransMap(priceDiscAdmTrans, destinationPriceDiscAdmTrans);
                    }
                }*/
                changecompany(_companyId)
                {
                    this.priceDiscAdmCheckPost(destinationDiscAdmTable);
                }
            }

            this.updateSourceTradeAgreement(_currentPriceDiscAdmTable);
           
            ttscommit;
        }
        catch
        {
            throw error("@LAW:LAW_SelectCompany");
        }
    }

    public PriceDiscAdmTrans createPurchTradeAgreementTrans(PriceDiscAdmTable newPriceDiscAdmTable, PriceDiscAdmTrans _priceDiscAdmTrans, PriceDiscTable _sourcePriceDiscTable)
    {
        PriceDiscAdmTrans           priceDiscAdmTrans, originalPriceDiscAdmTrans;
        PriceDiscTable              priceDiscTable;
        LAW_PriceDiscADmTransMap    priceDiscTransShare;
        MapEnumerator       mapEnumerator;
        int i = 1;
        //container contGroup = this.findGroupOfDefaultVendor(_priceDiscAdmTrans.relation);
        //container contDefault = this.findAllDefaultVendor();
        priceDiscAdmTrans.clear();
        priceDiscAdmTrans.JournalNum    = newPriceDiscAdmTable.JournalNum;

        //Relation same source company
        priceDiscAdmTrans.relation      = _priceDiscAdmTrans.relation;
        
        priceDiscAdmTrans.ItemCode      = _priceDiscAdmTrans.ItemCode;
        priceDiscAdmTrans.ItemRelation  = _priceDiscAdmTrans.ItemRelation;
        priceDiscAdmTrans.Amount        = _priceDiscAdmTrans.Amount;
        priceDiscAdmTrans.FromDate      = _priceDiscAdmTrans.FromDate;
        priceDiscAdmTrans.Currency      = _priceDiscAdmTrans.Currency;
        priceDiscAdmTrans.UnitId        = _priceDiscAdmTrans.UnitId;
        priceDiscAdmTrans.PriceUnit     = _priceDiscAdmTrans.PriceUnit;
        priceDiscAdmTrans.InventDimId   = _priceDiscAdmTrans.InventDimId;
        priceDiscAdmTrans.Agreement   = _priceDiscAdmTrans.Agreement;
        priceDiscAdmTrans.AgreementHeaderExt_RU   = _priceDiscAdmTrans.AgreementHeaderExt_RU;
        priceDiscAdmTrans.AllocateMarkup   = _priceDiscAdmTrans.AllocateMarkup;
        priceDiscAdmTrans.CalendarDays   = _priceDiscAdmTrans.CalendarDays;
        priceDiscAdmTrans.DeliveryTime   = _priceDiscAdmTrans.DeliveryTime;
        priceDiscAdmTrans.DifferentFromPosted   = _priceDiscAdmTrans.DifferentFromPosted;
        priceDiscAdmTrans.DisregardLeadTime   = _priceDiscAdmTrans.DisregardLeadTime;
        priceDiscAdmTrans.GenericCurrency   = _priceDiscAdmTrans.GenericCurrency;
        priceDiscAdmTrans.InventBaileeFreeDays_RU   = _priceDiscAdmTrans.InventBaileeFreeDays_RU;
        //priceDiscAdmTrans.LineNum   = _priceDiscAdmTrans.LineNum;
        priceDiscAdmTrans.Log   = _priceDiscAdmTrans.Log;
        priceDiscAdmTrans.Markup   = _priceDiscAdmTrans.Markup;
        priceDiscAdmTrans.MaximumRetailPrice_IN   = _priceDiscAdmTrans.MaximumRetailPrice_IN;
        priceDiscAdmTrans.MustBeDeleted   = _priceDiscAdmTrans.MustBeDeleted;
        priceDiscAdmTrans.PDSCalculationId   = _priceDiscAdmTrans.PDSCalculationId;
        priceDiscAdmTrans.Percent1   = _priceDiscAdmTrans.Percent1;
        priceDiscAdmTrans.Percent2   = _priceDiscAdmTrans.Percent2;
        priceDiscAdmTrans.QuantityAmountFrom   = _priceDiscAdmTrans.QuantityAmountFrom;
        priceDiscAdmTrans.QuantityAmountTo   = _priceDiscAdmTrans.QuantityAmountTo;
        priceDiscAdmTrans.ToDate   = _priceDiscAdmTrans.ToDate;


        //Check if case edit from another trade.
        if(_priceDiscAdmTrans.PriceDiscTableRef)
        {
            select firstonly priceDiscTransShare
                where priceDiscTransShare.SourceRecId == _sourcePriceDiscTable.OriginalPriceDiscAdmTransRecId;

            if(priceDiscTransShare)
            {
                select firstonly originalPriceDiscAdmTrans
                    where originalPriceDiscAdmTrans.RecId == priceDiscTransShare.DestinationRecId;

                if(originalPriceDiscAdmTrans)
                {
                    select firstonly   priceDiscTable
                        where priceDiscTable.OriginalPriceDiscAdmTransRecId == originalPriceDiscAdmTrans.RecId;

                    if(priceDiscTable)
                    {
                        priceDiscAdmTrans.PriceDiscTableRef = priceDiscTable.RecId;
                    }
                }
            }
            else
            {
                throw error("@LAW:LAW_ShareFailBecauseShared");
            }
            //find PriceDisTable

        }
        //case all => share price to all party
        //if(_priceDiscAdmTrans.AccountCode == PriceDiscPartyCodeType::All)
        //{
        //    priceDiscAdmTrans.AccountCode       = _priceDiscAdmTrans.AccountCode;
        //    priceDiscAdmTrans.AccountRelation   = _priceDiscAdmTrans.AccountRelation;
        //}
        //if(_priceDiscAdmTrans.AccountCode == PriceDiscPartyCodeType::GroupId)
        //{
        //    priceDiscAdmTrans.AccountCode       = _priceDiscAdmTrans.AccountCode;
        //    priceDiscAdmTrans.AccountRelation   = _priceDiscAdmTrans.AccountRelation;
        //}

        //Auto group all default vendor of store to group
        //If only default customer for all destination store
        /*if(conLen(contDefault) == 1 && contDefault)
        {
            priceDiscAdmTrans.AccountCode       = PriceDiscPartyCodeType::Table;
            priceDiscAdmTrans.AccountRelation   = conPeek(contDefault, 1);
            priceDiscAdmTrans.insert();
        }
        else
        {
            if(conLen(contGroup) >= 1)
            {
                for(i = 1 ; i< conLen(contGroup); i++)
                {
                    priceDiscAdmTrans.AccountCode       = PriceDiscPartyCodeType::GroupId;
                    priceDiscAdmTrans.AccountRelation   = conPeek(contGroup, i);
                    priceDiscAdmTrans.insert();
                }
            }
            else
            {
                for( i = 0; i < conLen(contDefault); i++)
                {
                    //priceDiscAdmTrans.AccountCode == PriceDiscPartyCodeType::Table;
                }
            }
        }*/

        this.findTableGroupOfDefaultVendor(_priceDiscAdmTrans.relation);
        mapEnumerator = mapTableGroupVendor.getEnumerator();

        while (mapEnumerator.moveNext())
        {
            if(mapEnumerator.currentValue() == "Table")
            {
                priceDiscAdmTrans.AccountCode       = PriceDiscPartyCodeType::Table;
                priceDiscAdmTrans.AccountRelation   = mapEnumerator.currentKey();
                priceDiscAdmTrans.insert();
            }
            
            if(mapEnumerator.currentValue() == "Group")
            {
                priceDiscAdmTrans.AccountCode       = PriceDiscPartyCodeType::GroupId;
                priceDiscAdmTrans.AccountRelation   = mapEnumerator.currentKey();
                priceDiscAdmTrans.insert();
            }
        }

        return priceDiscAdmTrans;
    }

    public void insertTradeAdmTransMap(PriceDiscAdmTrans _sourceCompany, PriceDiscAdmTrans _destinationCompany)
    {
        LAW_PriceDiscAdmTransMap    priceDiscAdmsMap;
        //After insert data in destination company, need to map data 2 trade agreement line
        priceDiscAdmsMap.SourceRecId = _sourceCompany.RecId;
        priceDiscAdmsMap.DestinationRecId = _destinationCompany.RecId;
        priceDiscAdmsMap.insert();
        //--end
    }

    public PriceDiscAdmTable createPurchTradeAgreementTable(PriceDiscAdmTable _currentDiscAdmTable)
    {
        PriceDiscTable              priceDiscTable;
        
        PriceDiscAdmTable           priceDiscAdmTable;

        priceDiscAdmTable.clear();
        priceDiscAdmTable.JournalName     = _currentDiscAdmTable.JournalName;
        priceDiscAdmTable.Name            = "@LAW:LAW_InsertTradeDescription";
        priceDiscAdmTable.DefaultRelation = _currentDiscAdmTable.DefaultRelation;
        priceDiscAdmTable.LAW_SourceCompany = _currentCompanyId;
        priceDiscAdmTable.LAW_Shared      = NoYes::Yes;
        priceDiscAdmTable.insert();

        return priceDiscAdmTable;
    }

    public void updateSourceTradeAgreement(PriceDiscAdmTable _currentDiscAdmTable)
    {
        _currentDiscAdmTable.selectForUpdate(true);
        _currentDiscAdmTable.LAW_Shared      =  NoYes::Yes;
        _currentDiscAdmTable.LAW_SourceCompany = curExt();
        _currentDiscAdmTable.LAW_SharedCompany = strFmt("%1,%2",  _currentDiscAdmTable.LAW_SharedCompany, _companyId);
        _currentDiscAdmTable.update();
    }

    public void priceDiscAdmCheckPost(PriceDiscAdmTable priceDiscAdmTable)
    {
        PriceDiscAdmCheckPost   priceDiscAdmCheckPost = new PriceDiscAdmCheckPost(false);
        priceDiscAdmCheckPost.initJournalNum(priceDiscAdmTable.JournalNum);
        priceDiscAdmCheckPost.run();
        
    }

    public container findAllDefaultVendor()
    {
        VendTable venTable;
        RetailStoreTable retailStoreTable;
        
        container   contVendor = conNull();
        //Step 1. get all vendor in all store, check duplicate vendor
        changecompany(_companyId)
        {
            while select retailStoreTable
                where retailStoreTable.LAW_IsFranchise
                    && retailStoreTable.LAW_DefaultVendor
            {
                if(!conFind(contVendor, retailStoreTable.LAW_DefaultVendor))
                {
                    contVendor += retailStoreTable.LAW_DefaultVendor;
                }
            }
        }
        return contVendor;
    }

    public container findTableGroupOfDefaultVendor(PriceType _priceType)
    {
        VendTable venTable;
        RetailStoreTable retailStoreTable;
        container   contVendor = conNull();
        //Step 1. get all vendor in all store, check duplicate vendor
        //mapTableGroupVendor
        changecompany(_companyId)
        {
            while select retailStoreTable
                where retailStoreTable.LAW_IsFranchise
                    && retailStoreTable.LAW_DefaultVendor
            {
                if(_priceType == PriceType::EndDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).EndDisc)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).EndDisc, "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::LineDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).LineDisc)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).LineDisc ,  "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::MultiLineDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).MultiLineDisc)
                        mapTableGroupVendor.insert( VendTable::find(retailStoreTable.LAW_DefaultVendor).MultiLineDisc, "Group");
                    else
                        mapTableGroupVendor.insert( retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::PricePurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).PriceGroup)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).PriceGroup, "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }

                
            }
        }
        return contVendor;
    }

    //public PriceDiscGroup createGroupAndSetPurchaseOrderDetail(PriceType _priceType, ItemId _itemid)
    //{
    //    PriceDiscGroup  priceDiscGroup;

    //    if(_priceType == PriceType::EndDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::EndDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::LineDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::LineDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::MultiLineDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::MultiLineDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::PricePurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::PriceGroup, _itemid);
    //    }

    //    return priceDiscGroup;
    //}

    //public PriceDiscGroup insertPriceDiscGroup(PriceGroupType _PriceGroupType, ItemId _itemId)
    //{
    //    PriceDiscGroup priceDiscGroup;
    //    container contVendorDestnation = this.findAndCreateGroupVendor();
    //    VendTable   vendTable;
    //    int i = 1;
    //    //Step 1: Create price disc group

    //    changecompany(_companyId)
    //    {
    //        try
    //        {
    //            priceDiscGroup.clear();
    //            priceDiscGroup.Module = ModuleInventCustVend::Vend;
    //            priceDiscGroup.Name = strFmt("Share_%1_%2_%3", _companyId, _itemId, guid2Str(newGuid()));
    //            priceDiscGroup.Type = _PriceGroupType;
    //            priceDiscGroup.GroupId = strFmt("Share_%1_%2_%3", _companyId, _itemId, guid2Str(newGuid()));
    //            priceDiscGroup.MCRPriceDiscGroupType = MCRPriceDiscGroupType::Standard;
    //            priceDiscGroup.doInsert();

    //            //Step 2: set puchase order default for vendor
    //            if(priceDiscGroup)
    //            {
    //                for(i = 1; i <= conLen( contVendorDestnation); i++)
    //                {
    //                    while select vendTable
    //                    where vendTable.AccountNum == conPeek(contVendorDestnation, i)
    //                    {
    //                        vendTable.selectForUpdate(true);
    //                        if(_PriceGroupType == PriceGroupType::EndDiscGroup)
    //                        vendTable.EndDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::LineDiscGroup)
    //                        vendTable.LineDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::MultiLineDiscGroup)
    //                        vendTable.MultiLineDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::PriceGroup)
    //                        vendTable.PriceGroup = priceDiscGroup.GroupId;
    //                        vendTable.update();
    //                    }
    //                }
    //            }

    //        }
    //        catch
    //        {
    //            throw error("Can not create proce disc group");
    //        }
    //    }
    //    return priceDiscGroup;
    //}

    public boolean ValidateDataDestinationCompany()
    {
        PriceDiscAdmName   destinationDiscAdmName;
        PriceDiscAdmTrans   priceDiscAdmTrans;
        boolean ret = true;

        changeCompany(_companyId)
        {
            select firstonly destinationDiscAdmName
                where destinationDiscAdmName.JournalName == _currentPriceDiscAdmTable.JournalName;

            if(!destinationDiscAdmName)
                ret = checkFailed("@LAW:LAW_TradeAgreementNotExist");
        }

        while select priceDiscAdmTrans
            where priceDiscAdmTrans.JournalNum == _currentPriceDiscAdmTable.JournalNum
            && priceDiscAdmTrans.ItemRelation
        {
            //Check data in destination company
            changeCompany(_companyId)
            {
                if(//TH1. Table check item still exist in inventtable destination company
                    (!InventTable::find(priceDiscAdmTrans.ItemRelation) && priceDiscAdmTrans.ItemCode == PriceDiscProductCodeType::Table)
                    //TH2. Check Group item relation still exist in destination company
                    || ((!PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::EndDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::LineDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::MCRPostageDisc, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::MultiLineDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::PriceGroup, priceDiscAdmTrans.ItemRelation))
                         && priceDiscAdmTrans.ItemCode == PriceDiscProductCodeType::GroupId))
                    //&& (priceDiscAdmTrans.relation == PriceType::PricePurch || priceDiscAdmTrans.relation == PriceType::LineDiscPurch
                    //|| priceDiscAdmTrans.relation == PriceType::MultiLineDiscPurch||priceDiscAdmTrans.relation == PriceType::EndDiscPurch)))
                {
                    ret = checkFailed(strFmt("@LAW:LAW_ItemShareNotExist", priceDiscAdmTrans.ItemRelation));
                }
            }
        }


        //retrict share current company
        if(_companyId == curExt())
        {
            ret = checkFailed("@LAW:LAW_CannotShareCurrentCom");
        }

        //Only share data if journal had posted

        if(_currentPriceDiscAdmTable.Posted == NoYes::No)
        {
            ret = checkFailed("@LAW:LAW_TradeAgreeNotPost");
        }

        //Can not share data if data shared

        if(_currentPriceDiscAdmTable.LAW_Shared == NoYes::Yes)
        {
            ret = checkFailed("@LAW:LAW_BeenShared");
        }
        return ret;
    }

    public boolean validate(Object calledFrom = null)
    {
        boolean ret;
    
        ret = super(calledFrom);
        if(!_companyId)
            ret = ret && checkFailed('@LAW:LAW_SelectCompany');

        ret = this.ValidateDataDestinationCompany();

        return ret;
    }

    public static void main(Args _args)
    {
        LAW_PurchaseTradeAgreementJournalShare tradeAgreementShare = new LAW_PurchaseTradeAgreementJournalShare();
        if(_args && _args.dataset() == tableNum(PriceDiscAdmTable))
        {
            tradeAgreementShare.parmPriceDiscAdmTable(_args.record());

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

}
Share sales trade agreement journal

Share sales trade agreement journal 


Song Nghia - Technical Consultant

Share sales trade agreement journal 

class LAW_SalesTradeAgreementJournalShare extends RunBaseBatch
{
    DialogField fieldCompany;
    companyId   _companyId, _currentCompany;
    PriceDiscAdmTable   _currentPriceDiscAdmTable;
    Map mapTableGroupVendor = new Map(Types::String, Types::String);
    public Object dialog()
    {
        Dialog dialog;
        ;
        dialog = super();

        dialog.caption("@LAW:LAW_SelectCompany");

        fieldCompany   =  dialog.addField(extendedTypeStr(companyId), "Company Id");

        return dialog;
    }

    public boolean getFromDialog()
    {
        // Retrieve values from Dialog
        _companyId = fieldCompany.value();
        return super();
    }

    public PriceDiscAdmTable parmPriceDiscAdmTable(PriceDiscAdmTable priceDiscAdmTable)
    {
        _currentPriceDiscAdmTable = priceDiscAdmTable;
        return _currentPriceDiscAdmTable;
    }

    public void run()
    {
        PriceDiscAdmTable   destinationDiscAdmTable;
        PriceDiscAdmTrans   priceDiscAdmTrans, priceDiscAdmTransGroup, priceDiscAdmTransOrder, destinationPriceDiscAdmTrans;
        PriceDiscTable      priceDiscTable;
        container           contRecId;
        int i;

        _currentCompany = curExt();
        try
        {
            ttsbegin;

            changecompany(_companyId)
            {
                destinationDiscAdmTable = this.createSalesTradeAgreementTable(_currentPriceDiscAdmTable);
            }
     
            if(destinationDiscAdmTable)
            {
                while select priceDiscAdmTrans
                where priceDiscAdmTrans.JournalNum == _currentPriceDiscAdmTable.JournalNum
                {
                    if(priceDiscAdmTrans.PriceDiscTableRef)
                    {
                        select firstonly  priceDiscTable
                        where priceDiscTable.RecId == priceDiscAdmTrans.PriceDiscTableRef;
                    }
                    changecompany(_companyId)
                    {
                        destinationPriceDiscAdmTrans = this.createSalesTradeAgreementTrans(destinationDiscAdmTable, priceDiscAdmTrans, priceDiscTable);
                        this.insertTradeAdmTransMap(priceDiscAdmTrans, destinationPriceDiscAdmTrans);
                    }
                }
                changecompany(_companyId)
                {
                    this.priceDiscAdmCheckPost(destinationDiscAdmTable);
                }
            }

            this.updateSourceTradeAgreement(_currentPriceDiscAdmTable);
         
            ttscommit;
        }
        catch
        {
            throw error("@LAW:LAW_CanNotShare");
        }
    }

    public PriceDiscAdmTrans createSalesTradeAgreementTrans(PriceDiscAdmTable newPriceDiscAdmTable, PriceDiscAdmTrans _priceDiscAdmTrans, PriceDiscTable _sourcePriceDiscTable)
    {
        PriceDiscAdmTrans           priceDiscAdmTrans, originalPriceDiscAdmTrans;
        PriceDiscTable              priceDiscTable;
        LAW_PriceDiscADmTransMap    priceDiscTransShare;
        MapEnumerator       mapEnumerator;
        int i = 1;
        priceDiscAdmTrans.clear();
        priceDiscAdmTrans.initFromPriceDiscAdmTrans(_priceDiscAdmTrans);
        priceDiscAdmTrans.JournalNum = newPriceDiscAdmTable.JournalNum;
        //Check if case edit from another trade.
        if(_priceDiscAdmTrans.PriceDiscTableRef)
        {
            select firstonly priceDiscTransShare
                where priceDiscTransShare.SourceRecId == _sourcePriceDiscTable.OriginalPriceDiscAdmTransRecId;

            if(priceDiscTransShare)
            {
                select firstonly originalPriceDiscAdmTrans
                    where originalPriceDiscAdmTrans.RecId == priceDiscTransShare.DestinationRecId;

                if(originalPriceDiscAdmTrans)
                {
                    select firstonly   priceDiscTable
                        where priceDiscTable.OriginalPriceDiscAdmTransRecId == originalPriceDiscAdmTrans.RecId;

                    if(priceDiscTable)
                    {
                        priceDiscAdmTrans.PriceDiscTableRef = priceDiscTable.RecId;
                    }
                }
            }
            else
            {
                throw error("@LAW:LAW_OriginalNotShare");
            }
        }

        priceDiscAdmTrans.insert();
        return priceDiscAdmTrans;
    }

    public void insertTradeAdmTransMap(PriceDiscAdmTrans _sourceCompany, PriceDiscAdmTrans _destinationCompany)
    {
        LAW_PriceDiscAdmTransMap    priceDiscAdmsMap;
        //After insert data in destination company, need to map data 2 trade agreement line
        priceDiscAdmsMap.SourceRecId = _sourceCompany.RecId;
        priceDiscAdmsMap.DestinationRecId = _destinationCompany.RecId;
        priceDiscAdmsMap.insert();
        //--end
    }

    public PriceDiscAdmTable createSalesTradeAgreementTable(PriceDiscAdmTable _currentDiscAdmTable)
    {
        PriceDiscTable              priceDiscTable;
     
        PriceDiscAdmTable           priceDiscAdmTable;

        priceDiscAdmTable.clear();
        priceDiscAdmTable.JournalName     = _currentDiscAdmTable.JournalName;
        priceDiscAdmTable.Name            = "@LAW:LAW_InsertTradeDescription";
        priceDiscAdmTable.DefaultRelation = _currentDiscAdmTable.DefaultRelation;
        priceDiscAdmTable.LAW_SourceCompany = _currentCompany;
        priceDiscAdmTable.LAW_Shared     =  NoYes::Yes;
        priceDiscAdmTable.LAW_SharedCompany = strFmt("%1,%2",_currentDiscAdmTable.LAW_SharedCompany, _companyId);
        priceDiscAdmTable.insert();

        return priceDiscAdmTable;
    }

    public void updateSourceTradeAgreement(PriceDiscAdmTable _currentDiscAdmTable)
    {
        _currentDiscAdmTable.selectForUpdate(true);
        _currentDiscAdmTable.LAW_Shared      =  NoYes::Yes;
        _currentDiscAdmTable.LAW_SourceCompany = _currentCompany;
        _currentDiscAdmTable.LAW_SharedCompany = strFmt("%1,%2",  _currentDiscAdmTable.LAW_SharedCompany, _companyId);
        _currentDiscAdmTable.update();
    }

    public void priceDiscAdmCheckPost(PriceDiscAdmTable priceDiscAdmTable)
    {
        PriceDiscAdmCheckPost   priceDiscAdmCheckPost = new PriceDiscAdmCheckPost(false);
        priceDiscAdmCheckPost.initJournalNum(priceDiscAdmTable.JournalNum);
        priceDiscAdmCheckPost.run();
     
    }

    public container findTableGroupOfDefaultVendor(PriceType _priceType)
    {
        VendTable venTable;
        RetailStoreTable retailStoreTable;
        container   contVendor = conNull();
        //Step 1. get all vendor in all store, check duplicate vendor
        //mapTableGroupVendor
        changecompany(_companyId)
        {
            while select retailStoreTable
                where retailStoreTable.LAW_IsFranchise
                    && retailStoreTable.LAW_DefaultVendor
            {
                if(_priceType == PriceType::EndDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).EndDisc)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).EndDisc, "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::LineDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).LineDisc)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).LineDisc ,  "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::MultiLineDiscPurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).MultiLineDisc)
                        mapTableGroupVendor.insert( VendTable::find(retailStoreTable.LAW_DefaultVendor).MultiLineDisc, "Group");
                    else
                        mapTableGroupVendor.insert( retailStoreTable.LAW_DefaultVendor, "Table");
                }
                if(_priceType == PriceType::PricePurch)
                {
                    if(VendTable::find(retailStoreTable.LAW_DefaultVendor).PriceGroup)
                        mapTableGroupVendor.insert(VendTable::find(retailStoreTable.LAW_DefaultVendor).PriceGroup, "Group");
                    else
                        mapTableGroupVendor.insert(retailStoreTable.LAW_DefaultVendor, "Table");
                }

             
            }
        }
        return contVendor;
    }

    //public PriceDiscGroup createGroupAndSetPurchaseOrderDetail(PriceType _priceType, ItemId _itemid)
    //{
    //    PriceDiscGroup  priceDiscGroup;

    //    if(_priceType == PriceType::EndDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::EndDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::LineDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::LineDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::MultiLineDiscPurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::MultiLineDiscGroup, _itemid);
    //    }
    //    if(_priceType == PriceType::PricePurch)
    //    {
    //        priceDiscGroup = this.insertPriceDiscGroup(PriceGroupType::PriceGroup, _itemid);
    //    }

    //    return priceDiscGroup;
    //}

    //public PriceDiscGroup insertPriceDiscGroup(PriceGroupType _PriceGroupType, ItemId _itemId)
    //{
    //    PriceDiscGroup priceDiscGroup;
    //    container contVendorDestnation = this.findAndCreateGroupVendor();
    //    VendTable   vendTable;
    //    int i = 1;
    //    //Step 1: Create price disc group

    //    changecompany(_companyId)
    //    {
    //        try
    //        {
    //            priceDiscGroup.clear();
    //            priceDiscGroup.Module = ModuleInventCustVend::Vend;
    //            priceDiscGroup.Name = strFmt("Share_%1_%2_%3", _companyId, _itemId, guid2Str(newGuid()));
    //            priceDiscGroup.Type = _PriceGroupType;
    //            priceDiscGroup.GroupId = strFmt("Share_%1_%2_%3", _companyId, _itemId, guid2Str(newGuid()));
    //            priceDiscGroup.MCRPriceDiscGroupType = MCRPriceDiscGroupType::Standard;
    //            priceDiscGroup.doInsert();

    //            //Step 2: set puchase order default for vendor
    //            if(priceDiscGroup)
    //            {
    //                for(i = 1; i <= conLen( contVendorDestnation); i++)
    //                {
    //                    while select vendTable
    //                    where vendTable.AccountNum == conPeek(contVendorDestnation, i)
    //                    {
    //                        vendTable.selectForUpdate(true);
    //                        if(_PriceGroupType == PriceGroupType::EndDiscGroup)
    //                        vendTable.EndDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::LineDiscGroup)
    //                        vendTable.LineDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::MultiLineDiscGroup)
    //                        vendTable.MultiLineDisc = priceDiscGroup.GroupId;
    //                        if(_PriceGroupType == PriceGroupType::PriceGroup)
    //                        vendTable.PriceGroup = priceDiscGroup.GroupId;
    //                        vendTable.update();
    //                    }
    //                }
    //            }

    //        }
    //        catch
    //        {
    //            throw error("Can not create proce disc group");
    //        }
    //    }
    //    return priceDiscGroup;
    //}

    public boolean ValidateDataDestinationCompany()
    {
        PriceDiscAdmName   destinationDiscAdmName;
        PriceDiscAdmTrans   priceDiscAdmTrans;
        boolean ret = true;

        changeCompany(_companyId)
        {
            select firstonly destinationDiscAdmName
                where destinationDiscAdmName.JournalName == _currentPriceDiscAdmTable.JournalName;

            if(!destinationDiscAdmName)
                ret = checkFailed("@LAW:LAW_TradeAgreementNotExist");
        }

        while select priceDiscAdmTrans
            where priceDiscAdmTrans.JournalNum == _currentPriceDiscAdmTable.JournalNum
            && priceDiscAdmTrans.ItemRelation
        {
            //Check data in destination company
            changeCompany(_companyId)
            {
                if(//TH1. Table check item still exist in inventtable destination company
                    (!InventTable::find(priceDiscAdmTrans.ItemRelation) && priceDiscAdmTrans.ItemCode == PriceDiscProductCodeType::Table)
                    //TH2. Check Group item relation still exist in destination company
                    || ((!PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::EndDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::LineDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::MCRPostageDisc, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::MultiLineDiscGroup, priceDiscAdmTrans.ItemRelation)
                         || !PriceDiscGroup::find(ModuleInventCustVend::Vend, PriceGroupType::PriceGroup, priceDiscAdmTrans.ItemRelation))
                         && priceDiscAdmTrans.ItemCode == PriceDiscProductCodeType::GroupId))
                    //&& (priceDiscAdmTrans.relation == PriceType::PricePurch || priceDiscAdmTrans.relation == PriceType::LineDiscPurch
                    //|| priceDiscAdmTrans.relation == PriceType::MultiLineDiscPurch||priceDiscAdmTrans.relation == PriceType::EndDiscPurch)))
                {
                    ret = checkFailed(strFmt("@LAW:LAW_ItemShareNotExist", priceDiscAdmTrans.ItemRelation));
                }
            }
        }


        //retrict share current company
        if(_companyId == curExt())
        {
            ret = checkFailed("@LAW:LAW_CannotShareCurrentCom");
        }

        //Only share data if journal had posted

        if(_currentPriceDiscAdmTable.Posted == NoYes::No)
        {
            ret = checkFailed("@LAW:LAW_TradeAgreeNotPost");
        }

        //Can not share data if data shared

        if(_currentPriceDiscAdmTable.LAW_Shared == NoYes::Yes)
        {
            ret = checkFailed("@LAW:LAW_BeenShared");
        }
        return ret;
    }

    public boolean validate(Object calledFrom = null)
    {
        boolean ret;
 
        ret = super(calledFrom);
        if(!_companyId)
            ret = ret && checkFailed('@LAW:LAW_SelectCompany');

        ret = this.ValidateDataDestinationCompany();

        return ret;
    }

    public static void main(Args _args)
    {
        LAW_SalesTradeAgreementJournalShare tradeAgreementShare = new LAW_SalesTradeAgreementJournalShare();
        if(_args && _args.dataset() == tableNum(PriceDiscAdmTable))
        {
            tradeAgreementShare.parmPriceDiscAdmTable(_args.record());

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

}