Snippets Collections
  // ------------NewChanges --------------------------------
      // DW ==> allow navigation if incomplete steps list is empty ==> only in GuardianShip and Full Will
      // if (id === 13 && (willTypeID === FULL_WILL || willTypeID === GUARDIANSHIP_WILL)) {
      //   const steps = await dispatch<any>(fetchAllIncompleteWillsSteps(profileGuid, spouseGuid, serviceId));
      //   if (steps.length === 0) {
      //     dispatch(setHighlightedSteps(getDraftWillStepNumber()));
      //     dispatch(setNavigationIndex(getDraftWillStepNumber()));
      //     dispatch(getNewActiveStep(13));
      //   }
      // }

      // /**
      //  * WILL PREVIEW
      //  * if fullWill || Guardianshipwill => allow navigation to Will Preview if only Draft Will is completed else allow navigation if incomplete steps list is empty
      //  */
      // if (id === 21) {
      //   const steps = await dispatch<any>(fetchAllIncompleteWillsSteps(profileGuid, spouseGuid, serviceId));
      //   if (willTypeID === FULL_WILL || willTypeID === GUARDIANSHIP_WILL) {
      //     if (steps.length === 0 && completedStepNumArray.includes(getDraftWillStepNumber())) {
      //       dispatch(setHighlightedSteps(getWillPreviewStepNumber()));
      //       dispatch(setNavigationIndex(getWillPreviewStepNumber()));
      //       dispatch(getNewActiveStep(21));
      //     } else {
      //       await dispatch<any>(resetErrorState());
      //       await dispatch<any>(setErrorInfo('Please complete Draft will to reach to Will Preview'));
      //     }
      //   }

      //   // All other willTypes
      //   if (willTypeID === PROPERTY_WILL
      //     || willTypeID === BUISINESS_OWNERS_WILL
      //     || willTypeID === FINANCIAL_ASSETS_WILL
      //     || willTypeID === TEMPLATED_FULL_WILL) {
      //     if (steps.length === 0) {
      //       dispatch(setHighlightedSteps(getWillPreviewStepNumber()));
      //       dispatch(setNavigationIndex(getWillPreviewStepNumber()));
      //       dispatch(getNewActiveStep(21));
      //     } else {
      //       await dispatch<any>(resetErrorState());
      //       await dispatch<any>(setErrorInfo('Please complete all steps to preview the will'));
      //     }
      //   }
      // }

      // // Book Appointment ==> allow navigation only if will preview is completed
      // if (id === 9) {
      //   const steps = await dispatch<any>(fetchAllIncompleteWillsSteps(profileGuid, spouseGuid, serviceId));
      //   const condition = steps.length === 0 && completedStepNumArray.includes(getWillPreviewStepNumber());
      //   console.log('step condition', condition);
      //   if (condition) {
      //     dispatch(setHighlightedSteps(getBookAppointmentStepNumber()));
      //     dispatch(setNavigationIndex(getBookAppointmentStepNumber()));
      //     dispatch(getNewActiveStep(9));
      //   } else {
      //     await dispatch<any>(resetErrorState());
      //     await dispatch<any>(setErrorInfo('Please complete all steps to book appointment'));
      //   }
      // }

      // // Payment ==> allow navigation only if book appointment is completed
      // if (id === 10) {
      //   const steps = await dispatch<any>(fetchAllIncompleteWillsSteps(profileGuid, spouseGuid, serviceId));
      //   if (steps.length === 0 && completedStepNumArray.includes(getBookAppointmentStepNumber())) {
      //     dispatch(setHighlightedSteps(getBookAppointmentStepNumber()));
      //     dispatch(setNavigationIndex(getBookAppointmentStepNumber()));
      //     dispatch(getNewActiveStep(10));
      //   }
      // }
      // ------------------New Changes --------------------------------

      // -------------------------------Validations in stepper for all willtypes--------------------------------
      // Will Preview navigation in stepper
      // if (id === 21 && isShowBookAppointment) {
      //   dispatch(setHighlightedSteps(getWillPreviewStepNumber()));
      //   dispatch(setNavigationIndex(getWillPreviewStepNumber()));
      //   dispatch(getNewActiveStep(21));
      // } else if (id === 21 && !isShowBookAppointment) {
      //   // Prevent navigation to will preview if all steps are not completed
      //   dispatch(setHighlightedSteps(highlightedStep));
      //   dispatch(setNavigationIndex(highlightedStep));
      //   dispatch(getNewActiveStep(newActiveStep));
      //   await dispatch<any>(resetErrorState());
      //   await dispatch<any>(setErrorInfo('Please complete all steps to proceed!'));
      // }

      /**
       * Navigation to Book Appointment only if isShowBookAppointment = true && draftWill() && WillPreview Completed
       */
      // if (id === 9 && isShowBookAppointment) {
      //   const { testatorSteps } = await getIncompleteStepsList(
      //     profileGuid,
      //     spouseGuid,
      //     profileGuid,
      //     serviceId,
      //   );

      //   if (testatorSteps.length === 0) {
      //     dispatch(setHighlightedSteps(getBookAppointmentStepNumber()));
      //     dispatch(setNavigationIndex(getBookAppointmentStepNumber()));
      //     dispatch(getNewActiveStep(9));
      //   } else {
      //     await dispatch<any>(resetErrorState());
      //     await dispatch<any>(setErrorInfo('Please complete all steps to proceed!'));
      //   }
      // } else if (id === 9 && !isShowBookAppointment) {
      //   await dispatch<any>(resetErrorState());
      //   await dispatch<any>(setErrorInfo('Please complete all steps to proceed!'));
      // }

      // Navigate to payment only if book appointment is completed and isShowBookAppointment === true
      // if (id === 10 && bookAppointmentCompleted && isShowBookAppointment) {
      //   dispatch(setHighlightedSteps(getPaymentStepNumber()));
      //   dispatch(setNavigationIndex(getPaymentStepNumber()));
      //   dispatch(getNewActiveStep(10));
      // }
      // -------------------------------Validations in stepper --------------------------------
<meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" />
import java.awt.*;
import java.awt.event.*;
public class gui extends Frame{
	private Button red=null;
	private Button green=null;
	public gui(){
	}
	public static void main(String[] args){
		gui f=new gui();
		//f.setLocation(150,150);
		f.setVisible(true);
		//f.setSize(300,300);
		f.setBounds(10,10,500,500);//location and size
		f.add(red);
	}
}
switch (COUNTRY) {
    case 'COUNTRY A':
      return <CountryAWidget />;
    case 'COUNTRY B':
      return <CountryBWidget />;
    default:
      return (
        <CountryCWidget />;
      );
  }
yarn ios-uat id --reset-cache --simulator "iPhone 15 Pro"
sudo letsencrypt certonly --standalone -d [도메인 이름]
#include<stdio.h>
struct Student{
    int id;
    char name[50];
    char session[50];
    float marks;
};
int main()
{
    int i,j;
    struct Student temp;
    struct Student s[10];

    for(i=0;i<10;i++){
        printf("Enter Data for Student %d:\n",i+1);
        scanf("%d%s%s%f",&s[i].id,&s[i].name,&s[i].session,&s[i].marks);
    }
    for(i=0;i<9;i++){
        for(j=0;j<9;j++){
            if(s[j].marks<s[j+1].marks){
                temp = s[j];
                s[j] = s[j+1];
                s[j+1] = temp;
            }
        }
    }
    printf("\n");
    printf("\n");
    printf("---------------------------\n");
    printf("---------------------------\n");
    for(i=0;i<10;i++){
        printf("Data for Student %d:\n",i+1);
        printf("Id:%d\n",s[i].id);
        printf("Name:%s\n",s[i].name);
        printf("Session:%s\n",s[i].session);
        printf("Marks:%.2f\n",s[i].marks);
    }


    return 0;
}
Sub RemoveFormulasFromExcel()
Dim Xws As Worksheet
For Each Xws In Worksheets
Xws.UsedRange.Value = Xws.UsedRange.Value
Next
End Sub
for(var i =0;i<50;i++){

var cart = new sn_sc.CartJS();

var request =
{
  'sysparm_id': 'e995bb921bcbf15476ccbbb88b4bcb79', //sys id of catalog item
  'sysparm_quantity': '1',
  'variables':{
  }
}

var gr = new GlideRecord('sc_req_item');
if (gr.get('0f7cbb001bd33d1076ccbbb88b4bcb8d')) {
   var vars = Object.keys(gr.variables);
  
  
  vars.forEach(function(e){
  request.variables[e]= gr.variables[e].toString();
  
  
  })
}
var cartDetails = cart.orderNow(request);
gs.info(cartDetails);
cartDetails
}
var express = require('express');
var router = express.Router();
const multer  = require('multer');
const Teacher = require('../model/teacher_register');
const fs = require('fs')

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/'); // Store uploaded images in the 'uploads' directory
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + '-' + file.originalname);
    },
  });
  
const upload = multer({ storage: storage });

const TeacherRegister = async (req, res, next) => {
    try {
        
        const teacher = new Teacher({
            tea_fname: req.body.tea_fname,
            tea_lname: req.body.tea_lname,
            tea_email: req.body.tea_email,
            tea_number: req.body.tea_number,
            tea_address: req.body.tea_address,
            tea_subject: req.body.tea_subject,
            tea_image: req.file.filename,
        })

        const teacher_data = await teacher.save();
        let teacher_id = teacher_data._id;

        res.json({
            status: 200,
            message: "Teacher Register Successfully",
            teacher_id: teacher_id,
            destination: "Please Save your Teacher id Becoses login time is required"

        })

    } catch (error) {

    fs.unlinkSync(req.file.path);
    
    res.json({
        status: 400,
        message: "Please Rechake Your Details",
        hint: "Some information is Duplicate"
    })
        
    }
}



const GetTeacherId = async (req, res , next) => {
  try {

    let teachermail = req.body.Teacheremail;

    const data = await Teacher.aggregate([
    {
      $match: {
        tea_email: teachermail
      }
    },
    {
      $project: {
        _id: 1
      }
    }
  
  ])
  
    res.json({
      status: 200,
      message: "Get Teacher Id Successfully",
      data: data
    })
    
  } catch (error) {

    res.json({
      status: 400,
      message: "Please check email address",
    })
    
  }
}


router.post("/register",upload.single('tea_image'), TeacherRegister); // TeacherRegister
router.get("/getid", GetTeacherId); // TeacherRegister
module.exports = router;
Basic Form Abandonment Script in JavaScript
Here's a basic JavaScript script that tracks form abandonment:

JavaScript
(function() {
  // Variables
  const forms = document.querySelectorAll('form'); // Select all forms on the page
  const abandonmentTime = 3000; // Time in milliseconds before considering abandonment (adjust as needed)

  // Track user activity
  window.addEventListener('beforeunload', (event) => {
    for (const form of forms) {
      if (!form.elementsHaveInteraction()) { // Check if any form element has been interacted with
        event.returnValue = 'Are you sure you want to leave without completing the form?'; // Prompts before leaving
      }
    }
  });

  // Function to check if any form element has been interacted with
  function formElementsHaveInteraction() {
    for (const element of this.elements) {
      if (element.value || element.checked) {
        return true;
      }
    }
    return false;
  }

  // Apply function to all forms
  for (const form of forms) {
    form.elementsHaveInteraction = formElementsHaveInteraction.bind(form);
  }
})();
#include<stdio.h>
// this code is for the recursive implementation of ternary search 
int ternarysearch(int l, int r, int key,int ar[])
{
    if(r >= 1){
        int mid1 = l + (r-1)/3;
        int mid2 = r - (r-1)/3;
        
        if (ar[mid1] == key){
            return mid1;
        }
        if (ar[mid2] == key){
            return mid2;
        }
        if(key < ar[mid1]){
            return ternarysearch(1, mid1-1,key,ar);
        }
        else if(key > ar[mid2]){
            return ternarysearch(mid2+1, mid2-1,key,ar);
        }
    }

    return -1;    

}

int main()
{
    int l,r,p,key;
//sort the array if the array is not sorted
    int ar[] = {1,2,3,4,5,6,7,8,9,10};

    l=0;

    r=9;

    key= 5;

    p= ternarysearch(l, r,key,ar);

    printf("index of %d is%d\n", key,p);

    key = 50;

    p= ternarysearch(l, r, key, ar);

    printf("index of %d is %d",key , p);
}
version: "1.0"

name: ChannelNetwork

# All actions

actions:
  - name: VIEW
  - name: UPDATE

# All resources

resources:
  # UI Resource for access to kpis tab
  - name: ProductKpiTab
    actions: [VIEW]

    ### Begin productKpi fields

  - name: ProductKpi
    group: productKpi
    actions: [VIEW]

  - name: ProductKpi/*
    group: productKpi
    actions: [VIEW]

    ### End productKpi fields

    ### Begin salesKpi fields

  - name: SalesKpi
    group: salesKpi
    actions: [VIEW]

  - name: SalesKpi/*
    group: salesKpi
    actions: [VIEW]

    ### End salesKpi fields

    ### Begin inventoryKpi fields

  - name: InventoryKpi
    group: inventoryKpi
    actions: [VIEW]

  - name: InventoryKpi/*
    group: inventoryKpi
    actions: [VIEW]

    ### End inventoryKpi fields

    ### Begin filesKpi fields

  - name: FilesKpi
    group: filesKpi
    actions: [VIEW]

  - name: FilesKpi/*
    group: filesKpi
    actions: [VIEW]

    ### End filesKpi fields

    ### Begin ssKpi fields

  - name: SSKpi
    group: ssKpi
    actions: [VIEW]

  - name: SSKpi/*
    group: ssKpi
    actions: [VIEW]

    ### End ssKpi fields


    # UI Resource for access to Products tab
  - name: ProductTab
    actions: [VIEW, UPDATE]

    ### Begin Product Fields

  - name: Product
    group: product
    actions: [VIEW, UPDATE]

  - name: Product/sid
    group: product
    actions: [VIEW]

  - name: Product/createDate
    group: product
    actions: [VIEW]

  - name: Product/updateDate
    group: product
    actions: [VIEW]

  - name: Product/customerSid
    group: product-internal
    actions: [VIEW]

  - name: Product/sku
    group: product
    actions: [VIEW]

  - name: Product/name
    group: product
    actions: [VIEW]

  - name: Product/description
    group: product
    actions: [VIEW]

  - name: Product/productFamily
    group: product
    actions: [VIEW]

  - name: Product/productLine
    group: product
    actions: [VIEW]

  - name: Product/startDate
    group: product
    actions: [VIEW]

  - name: Product/endDate
    group: product
    actions: [VIEW]

  - name: Product/serialized
    group: product-internal
    actions: [VIEW]

  - name: Product/aggregation
    group: product-pos-aggr
    actions: [VIEW]

  - name: Product/aggregation/totalSalesLineCount
    group: product-pos-aggr
    actions: [VIEW]

  - name: Product/aggregation/totalSalesQuantity
    group: product-pos-aggr
    actions: [VIEW]

  - name: Product/aggregation/oldestInvoiceDate
    group: product-pos-aggr
    actions: [VIEW]

    ## Begin Product Dynamic Attrs


  - name: Product/dynamicAttrs
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/sid
    group: product-dynamicAttrs-internal
    actions: [VIEW]
  - name: Product/dynamicAttrs/updateDate
    group: product-dynamicAttrs-internal
    actions: [VIEW]
  - name: Product/dynamicAttrs/createDate
    group: product-dynamicAttrs-internal
    actions: [VIEW]
  - name: Product/dynamicAttrs/attributeType
    group: product-dynamicAttrs-internal
    actions: [VIEW]
  - name: Product/dynamicAttrs/STRING_COL_1
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_2
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_3
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_4
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_5
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_6
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_7
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_8
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_9
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_10
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_11
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_12
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_13
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_14
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_15
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_16
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_17
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_18
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_19
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_20
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_21
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_22
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_23
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_24
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_25
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_26
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_27
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_28
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_29
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/STRING_COL_30
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]

  - name: Product/dynamicAttrs/NUM_COL_1
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_2
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_3
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_4
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_5
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_6
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_7
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_8
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_9
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
  - name: Product/dynamicAttrs/NUM_COL_10
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]

  - name: Product/dynamicAttrs/DATE_COL_1
    group: product-dynamicAttrs
    actions: [VIEW, UPDATE]
    ## End Product Dynamic Attrs

    ### End Product Fields

    # UI Resource for access to POS tab
  - name: SalesTab
    actions: [VIEW, UPDATE]

    ### Begin POS Fields

  - name: Sales
    group: sales
    actions: [VIEW, UPDATE]

  - name: Sales/sid
    group: sales
    actions: [VIEW]

  - name: Sales/createDate
    group: sales
    actions: [VIEW]

  - name: Sales/updateDate
    group: sales
    actions: [VIEW]

  - name: Sales/customerSid
    group: sales-internal
    actions: [VIEW]

  - name: Sales/deleted
    group: sales-internal
    actions: [VIEW]

  - name: Sales/branchId
    group: sales
    actions: [VIEW]

  - name: Sales/invoiceNumber
    group: sales
    actions: [VIEW]

  - name: Sales/invoiceDate
    group: sales
    actions: [VIEW]

  - name: Sales/quantity
    group: sales
    actions: [VIEW]

  - name: Sales/reportedSku
    group: sales
    actions: [VIEW, UPDATE]

  - name: Sales/productDescription
    group: sales
    actions: [VIEW]

  - name: Sales/transactionId
    group: sales-internal
    actions: [VIEW]

  - name: Sales/vendorPartNumber
    group: sales
    actions: [VIEW]

  - name: Sales/accountRepresentative
    group: sales
    actions: [VIEW]

  - name: Sales/acquisitionExtendedPrice
    group: sales
    actions: [VIEW]

  - name: Sales/acquisitionUnitPrice
    group: sales
    actions: [VIEW]

  - name: Sales/boolExtendedPrice
    group: sales
    actions: [VIEW]

  - name: Sales/bookUnitPrice
    group: sales
    actions: [VIEW]

  - name: Sales/customerOrderNumber
    group: sales
    actions: [VIEW]

  - name: Sales/debitExtendedPrice
    group: sales
    actions: [VIEW]

  - name: Sales/debitUnitPrice
    group: sales
    actions: [VIEW]

  - name: Sales/designRegistrationNumber
    group: sales
    actions: [VIEW]

  - name: Sales/distributorId
    group: sales
    actions: [VIEW]

  - name: Sales/distributorName
    group: sales
    actions: [VIEW]

  - name: Sales/distributorShipmentNumber
    group: sales
    actions: [VIEW]

  - name: Sales/distributorWarehouseId
    group: sales
    actions: [VIEW]

  - name: Sales/exchangeDate
    group: sales
    actions: [VIEW]

  - name: Sales/exchangeRate
    group: sales
    actions: [VIEW]

  - name: Sales/globalProductClassCode
    group: sales
    actions: [VIEW]

  - name: Sales/legacySalesRecordId
    group: sales
    actions: [VIEW]

  - name: Sales/lengthOfProduction
    group: sales
    actions: [VIEW]

  - name: Sales/manufactureId
    group: sales
    actions: [VIEW]

  - name: Sales/manufactureName
    group: sales
    actions: [VIEW]

  - name: Sales/manufacturerShipmentNumber
    group: sales
    actions: [VIEW]

  - name: Sales/orderNumber
    group: sales
    actions: [VIEW]

  - name: Sales/originalId
    group: sales
    actions: [VIEW]

  - name: Sales/price
    group: sales
    actions: [VIEW]

  - name: Sales/purchaseOrderNumber
    group: sales
    actions: [VIEW]

  - name: Sales/r2rDuplicateType
    group: sales
    actions: [VIEW]

  - name: Sales/regionTerritory
    group: sales
    actions: [VIEW]

  - name: Sales/reportEndingDate
    group: sales
    actions: [VIEW]

  - name: Sales/reportType
    group: sales
    actions: [VIEW]

  - name: Sales/resaleExtendedPrice
    group: sales
    actions: [VIEW]

  - name: Sales/resaeExtension
    group: sales
    actions: [VIEW]

  - name: Sales/resaleUnitPrice
    group: sales
    actions: [VIEW]

  - name: Sales/resubmitted
    group: sales
    actions: [VIEW]

  - name: Sales/reportedProductFamily
    group: sales
    actions: [VIEW]

  - name: Sales/reportedProductLine
    group: sales
    actions: [VIEW]

  - name: Sales/reportedProductName
    group: sales
    actions: [VIEW]

  - name: Sales/shipDate
    group: sales
    actions: [VIEW]

  - name: Sales/shipDebitNumber
    group: sales
    actions: [VIEW]

  - name: Sales/shippingMethod
    group: sales
    actions: [VIEW]

  - name: Sales/spaNumber
    group: sales
    actions: [VIEW]

  - name: Sales/tier
    group: sales
    actions: [VIEW]

  - name: Sales/transactionType
    group: sales
    actions: [VIEW]

  - name: Sales/unitOfMeasure
    group: sales
    actions: [VIEW]

  - name: Sales/vendorPartDescription
    group: sales
    actions: [VIEW]

  - name: Sales/validationCodes
    group: sales
    actions: [VIEW]

  - name: Sales/serialNumbers
    group: sales
    actions: [VIEW]

    # Bill to address


  - name: Sales/billToAddress
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/billToAddress/entityName
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/street1
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/street2
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/city
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/stateProvince
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/postalCode
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/reportedCountry
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/country
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/country/name
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/country/twoCharCode
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddress/country/threeCharCode
    group: sales-bill-to
    actions: [VIEW]

  - name: Sales/billToAddressExternalId
    group: sales-bill-to
    actions: [VIEW]

    # sold to address

  - name: Sales/soldToAddress
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/soldToAddress/entityName
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/street1
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/street2
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/city
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/stateProvince
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/postalCode
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/reportedCountry
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/country
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/country/name
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/country/twoCharCode
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddress/country/threeCharCode
    group: sales-sold-to
    actions: [VIEW]

  - name: Sales/soldToAddressExternalId
    group: sales-sold-to
    actions: [VIEW]

    # ship to address

  - name: Sales/shipToAddress
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/shipToAddress/entityName
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/street1
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/street2
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/city
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/stateProvince
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/postalCode
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/reportedCountry
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/country
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/country/name
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/country/twoCharCode
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddress/country/threeCharCode
    group: sales-ship-to
    actions: [VIEW]

  - name: Sales/shipToAddressExternalId
    group: sales-ship-to
    actions: [VIEW]

    # sell from address

  - name: Sales/sellFromAddress
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/sellFromAddress/entityName
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/street1
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/street2
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/city
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/stateProvince
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/postalCode
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/reportedCountry
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/country
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/country/name
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/country/twoCharCode
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddress/country/threeCharCode
    group: sales-sell-from
    actions: [VIEW]

  - name: Sales/sellFromAddressExternalId
    group: sales-sell-from
    actions: [VIEW]

    # ship from address

  - name: Sales/shipFromAddress
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/shipFromAddress/entityName
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/street1
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/street2
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/city
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/stateProvince
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/postalCode
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/reportedCountry
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/country
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/country/name
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/country/twoCharCode
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddress/country/threeCharCode
    group: sales-ship-from
    actions: [VIEW]

  - name: Sales/shipFromAddressExternalId
    group: sales-ship-from
    actions: [VIEW]

    # sales in address

  - name: Sales/salesInAddress
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/salesInAddress/entityName
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/street1
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/street2
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/city
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/stateProvince
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/postalCode
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/reportedCountry
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/country
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/country/name
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/country/twoCharCode
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddress/country/threeCharCode
    group: sales-sales-in
    actions: [VIEW]

  - name: Sales/salesInAddressExternalId
    group: sales-sales-in
    actions: [VIEW]

    # purchasing customer address

  - name: Sales/purchasingCustomerAddress
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/entityName
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/street1
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/street2
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/city
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/stateProvince
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/postalCode
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/reportedCountry
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/country
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/country/name
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/country/twoCharCode
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerAddress/country/threeCharCode
    group: sales-purchasing-customer
    actions: [VIEW]

  - name: Sales/purchasingCustomerExternalId
    group: sales-purchasing-customer
    actions: [VIEW]

    # derived end customer address

  - name: Sales/derivedEndCustomerAddress
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/entityName
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/street1
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/street2
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/city
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/stateProvince
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/postalCode
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/reportedCountry
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/country
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/country/name
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/country/twoCharCode
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddress/country/threeCharCode
    group: sales-derived-end-customer
    actions: [VIEW]

  - name: Sales/derivedEndCustomerAddressExternalId
    group: sales-derived-end-customer
    actions: [VIEW]

    # data file

  - name: Sales/dataFile
    group: sales-data-file
    actions: [VIEW]

  - name: Sales/dataFile/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/dataFile/loadDate
    group: sales-data-file
    actions: [VIEW]

  - name: Sales/dataFile/reportDate
    group: sales-data-file
    actions: [VIEW]

  - name: Sales/dataFile/id
    group: sales-data-file
    actions: [VIEW]

  - name: Sales/dataFile/fileName
    group: sales-data-file
    actions: [VIEW]

  - name: Sales/dataFile/recordCount
    group: sales-data-file
    actions: [VIEW]

    # match info

  - name: Sales/productMatchInfo
    group: sales-product-match-info
    actions: [VIEW]

  - name: Sales/productMatchInfo/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/productMatchInfo/matchedProduct
    group: sales-product-match-info
    actions: [VIEW]

  - name: Sales/productMatchInfo/matchedProduct/sku
    group: sales-product-match-info
    actions: [VIEW]

    # reporting partner

  - name: Sales/reportingPartner
    group: sales-reporting-partner
    actions: [VIEW]

  - name: Sales/reportingPartner/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/reportingPartner/gsNumbers
    group: sales-reporting-partner
    actions: [VIEW]

  - name: Sales/reportingPartner/gsNumbers/value
    group: sales-reporting-partner
    actions: [VIEW]

    # currency

  - name: Sales/currency
    group: sales-currency
    actions: [VIEW]

  - name: Sales/currency/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/currency/name
    group: sales-currency
    actions: [VIEW]

    # resale currency

  - name: Sales/resaleCurrency
    group: sales-resale-currency
    actions: [VIEW]

  - name: Sales/resaleCurrency/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/resaleCurrency/name
    group: sales-resale-currency
    actions: [VIEW]

    # debit currency

  - name: Sales/debtCurrency
    group: sales-debit-currency
    actions: [VIEW]

  - name: Sales/debtCurrency/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/debtCurrency/name
    group: sales-debit-currency
    actions: [VIEW]

    # book currency

  - name: Sales/bookCurrency
    group: sales-book-currency
    actions: [VIEW]

  - name: Sales/bookCurrency/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/bookCurrency/name
    group: sales-book-currency
    actions: [VIEW]

    # acquisition currency

  - name: Sales/acquisitionCurrency
    group: sales-acquisition-currency
    actions: [VIEW]

  - name: Sales/acquisitionCurrency/*
    group: sales-internal
    actions: [VIEW]

  - name: Sales/acquisitionCurrency/name
    group: sales-acquisition-currency
    actions: [VIEW]

    ## Begin POS Dynamic Attrs

  - name: Sales/dynamicAttrs
    group: sales-dynamic-attrs
    actions: [VIEW, UPDATE]

  - name: Sales/dynamicAttrs/*
    group: sales-dynamic-attrs
    actions: [VIEW, UPDATE]

  - name: Sales/dynamicAttrs/STRING_COL_1
    group: sales-dynamic-attrs
    actions: [VIEW, UPDATE]

    ## End POS Dynamic Attrs

    ### End POS Fields

    # UI Resource for access to INV tab
  - name: InventoryTab
    actions: [VIEW, UPDATE]

    ### Begin INV Fields

  - name: Inventory
    group: inventory
    actions: [VIEW, UPDATE]

  - name: Inventory/sid
    group: inventory
    actions: [VIEW]

  - name: Inventory/createDate
    group: inventory
    actions: [VIEW]

  - name: Inventory/updateDate
    group: inventory
    actions: [VIEW]

  - name: Inventory/customerSid
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/deleted
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/productName
    group: inventory
    actions: [VIEW]

  - name: Inventory/clientDescription
    group: inventory
    actions: [VIEW]

  - name: Inventory/clientSku
    group: inventory
    actions: [VIEW, UPDATE]

  - name: Inventory/reportedSku
    group: inventory
    actions: [VIEW]

  - name: Inventory/inventoryDate
    group: inventory
    actions: [VIEW]

  - name: Inventory/unitOfMeasure
    group: inventory
    actions: [VIEW]

  - name: Inventory/id
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/originalId
    group: inventory
    actions: [VIEW]

  - name: Inventory/lineNumber
    group: inventory-internal
    actions: [VIEW]

    # data file

  - name: Inventory/dataFile
    group: inventory-data-file
    actions: [VIEW]

  - name: Inventory/dataFile/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/dataFile/loadDate
    group: inventory-data-file
    actions: [VIEW]

  - name: Inventory/dataFile/reportDate
    group: inventory-data-file
    actions: [VIEW]

  - name: Inventory/dataFile/id
    group: inventory-data-file
    actions: [VIEW]

  - name: Inventory/dataFile/fileName
    group: inventory-data-file
    actions: [VIEW]

  - name: Inventory/dataFile/recordCount
    group: inventory-data-file
    actions: [VIEW]

    # reporting partner

  - name: Inventory/reportingPartner
    group: inventory-reporting-partner
    actions: [VIEW]

  - name: Inventory/reportingPartner/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/reportingPartner/gsNumbers
    group: inventory-reporting-partner
    actions: [VIEW]

  - name: Inventory/reportingPartner/gsNumbers/value
    group: inventory-reporting-partner
    actions: [VIEW]

    # submission period

  - name: Inventory/submissionPeriod
    group: inventory-submission-period
    actions: [VIEW]

  - name: Inventory/submissionPeriod/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/submissionPeriod/expectedDate
    group: inventory-submission-period
    actions: [VIEW]

  - name: Inventory/submissionPeriod/periodStartDate
    group: inventory-submission-period
    actions: [VIEW]

  - name: Inventory/submissionPeriod/periodEndDate
    group: inventory-submission-period
    actions: [VIEW]

    # quantities

  - name: Inventory/inventoryQuantities
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/inventoryQuantities/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/onHandQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/onHandQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/onHandQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/onOrderQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/onOrderQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/onOrderQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/committedQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/committedQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/committedQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/floatQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/floatQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/floatQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/backorderedQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/backorderedQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/backorderedQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/returnedQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/returnedQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/returnedQuantity/value
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/inTransitQuantity
    group: inventory-quantity
    actions: [VIEW]

  - name: Inventory/inTransitQuantity/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/inTransitQuantity/value
    group: inventory-quantity
    actions: [VIEW]

    # prices

  - name: Inventory/inventoryPrices
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/inventoryPrices/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/unitPrice
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/unitPrice/*
    group: inventory-internal
    actions: [VIEW]

  - name: Inventory/unitPrice/price
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/unitPrice/fromCurrency
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/unitPrice/fromCurrency/name
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/unitPrice/toCurrency
    group: inventory-price
    actions: [VIEW]

  - name: Inventory/unitPrice/toCurrency/name
    group: inventory-price
    actions: [VIEW]

    ## Begin INV Dynamic Attrs

  - name: Inventory/dynamicAttrs
    group: inventory-dynamic-attrs
    actions: [VIEW]

  - name: Inventory/dynamicAttrs/*
    group: inventory-dynamic-attrs
    actions: [VIEW]

    ## End INV Dynamic Attrs

    ### End INV Fields

  # UI Resource for access to File Tab
  - name: FilesTab
    actions: [VIEW, UPDATE]

  ## Begin Partner

  - name: Partner
    group: reporting-partner
    actions: [VIEW]

  - name: Partner/*
    group: reporting-partner
    actions: [VIEW]

  ## End Partner

  # Begin File fields
  - name: DataFile
    group: file-management
    actions: [VIEW, UPDATE]

  - name: DataFile/sid
    group: file-management
    actions: [VIEW]

  - name: DataFile/loadDate
    group: file-management
    actions: [VIEW]

  - name: DataFile/reportDate
    group: file-management
    actions: [VIEW]

  - name: DataFile/fileName
    group: file-management
    actions: [VIEW]

  - name: DataFile/fileType
    group: file-management
    actions: [VIEW]

  - name: DataFile/dataType
    group: file-management
    actions: [VIEW]

  - name: DataFile/id
    group: file-management
    actions: [VIEW]

  - name: DataFile/fileSize
    group: file-management
    actions: [VIEW]

  - name: DataFile/source
    group: file-management
    actions: [VIEW]

  - name: DataFile/recordCount
    group: file-management
    actions: [VIEW]

  - name: DataFile/deletedLines
    group: file-management
    actions: [VIEW]

  - name: DataFile/download
    group: file-download
    actions: [VIEW]

  - name: DataFile/validationDownload
    group: file-validation-download
    actions: [VIEW]

  - name: DataFile/upload
    group: file-upload
    actions: [VIEW]

  - name: DataFile/uploadDataTypes
    group: file-upload
    actions: [VIEW]

  - name: DataFile/uploadFileTypes
    group: file-upload
    actions: [VIEW]

  - name: DataFile/reportingPartner
    group: file-reporting-partner
    actions: [VIEW]

  - name: DataFile/reportingPartner/*
    group: file-reporting-partner
    actions: [VIEW]

  - name: DataFile/reportingPartner/partnerOverlayView
    group: file-reporting-partner
    actions: [VIEW]

  - name: DataFile/reportingPartner/partnerOverlayView/*
    group: file-reporting-partner
    actions: [VIEW]

  - name: DataFile/dataFileState
    group: file-data-file-state
    actions: [VIEW]

  - name: DataFile/dataFileState/*
    group: file-data-file-state
    actions: [VIEW]

  - name: DataFile/dataFileState/sid
    group: file-data-file-state
    actions: [VIEW]

  - name: DataFile/dataFileState/createDate
    group: file-data-file-state
    actions: [VIEW]

  - name: DataFile/dataFileState/updateDate
    group: file-data-file-state
    actions: [VIEW]

  - name: DataFile/parserAttempt
    group: file-parser-attempt
    actions: [VIEW]

  - name: DataFile/parserAttempt/*
    group: file-parser-attempt
    actions: [VIEW]

  # End of File fields
  
  # UI Resource for access to Submission Schedule
  - name: SubmissionTrackingTab
    actions: [VIEW, UPDATE]

  - name: SubmissionResultsTab
    actions: [VIEW, UPDATE]

  # Begin Submission Schedule 
  - name: SubmissionSchedule
    group: submission-schedule
    actions: [VIEW, UPDATE]

  - name: SubmissionSchedule/sid
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/createDate
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/updateDate
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/name
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/reportingPartner
    group: ss-reporting-partner
    actions: [VIEW]

  - name: SubmissionSchedule/reportingPartner/*
    group: ss-reporting-partner
    actions: [VIEW]

  - name: SubmissionSchedule/reportingPartner/partnerOverlayView
    group: ss-reporting-partner
    actions: [VIEW]

  - name: SubmissionSchedule/reportingPartner/partnerOverlayView/*
    group: ss-reporting-partner
    actions: [VIEW]

  - name: SubmissionSchedule/dataType
    group: ss-data-type
    actions: [VIEW]

  - name: SubmissionSchedule/dataType/*
    group: ss-data-type
    actions: [VIEW]

  - name: SubmissionSchedule/periodRule
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/expectedDay
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/startDate
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/endDate
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/isInPeriodReporter
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/weekOfMonth
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/monthOfQuarter
    group: submission-schedule
    actions: [VIEW]

  - name: SubmissionSchedule/workingDays
    group: submission-schedule
    actions: [VIEW]

  # End Submission Schedule 

  # Begin Submission Schedule Notification
  - name: SubmissionScheduleNotification
    group: submission-schedule-notification
    actions: [VIEW]
  
  - name: SubmissionScheduleNotification/*
    group: submission-schedule-notification
    actions: [VIEW]

  - name: SubmissionScheduleNotification/notificationType
    group: submission-schedule-notification
    actions: [VIEW]

  - name: SubmissionScheduleNotification/notificationType/*
    group: submission-schedule-notification
    actions: [VIEW]

  - name: SubmissionScheduleNotification/serviceUser
    group: submission-schedule-notification
    actions: [VIEW]

  - name: SubmissionScheduleNotification/serviceUser/*
    group: submission-schedule-notification
    actions: [VIEW]

  # END Submission Schedule Notification

  # Begin Submission Period
  - name: SubmissionPeriod
    group: submission-period-update
    actions: [VIEW, UPDATE]

  - name: SubmissionPeriod/sid
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/expectedDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/periodStartDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/periodEndDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/createDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/updateDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/noData
    group: submission-period-update
    actions: [VIEW, UPDATE]

  - name: SubmissionPeriod/noDataReason
    group: submission-period-update
    actions: [VIEW, UPDATE]

  - name: SubmissionPeriod/noDataCreateDate
    group: submission-period-update
    actions: [VIEW, UPDATE]

  - name: SubmissionPeriod/onTimeOverride
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/expectedDay
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/workingDays
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/isInPeriodReporter
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/trackingLevel
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/status
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/reportedFlag
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/fileIds
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/firstFileName
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/firstFileCreateDate
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/firstFileId
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/deleted
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/noDataServiceUser
    group: submission-period-update
    actions: [VIEW, UPDATE]

  - name: SubmissionPeriod/noDataServiceUser/sid
    group: sp-no-data-user
    actions: [VIEW]

  - name: SubmissionPeriod/noDataServiceUser/firstName
    group: sp-no-data-user
    actions: [VIEW]

  - name: SubmissionPeriod/noDataServiceUser/lastName
    group: sp-no-data-user
    actions: [VIEW]

  - name: SubmissionPeriod/noDataServiceUser/email
    group: sp-no-data-user
    actions: [VIEW]

  - name: SubmissionPeriod/submissionPeriodLineItemView
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/submissionPeriodLineItemView/*
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/dataFileSummaryInfo
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/dataFileSummaryInfo/*
    group: submission-period
    actions: [VIEW]
    
  - name: SubmissionPeriod/submissionSchedule
    group: submission-period
    actions: [VIEW]
    
  - name: SubmissionPeriod/submissionSchedule/sid
    group: submission-period
    actions: [VIEW]
    
  - name: SubmissionPeriod/submissionSchedule/name
    group: submission-period
    actions: [VIEW]
    
  - name: SubmissionPeriod/submissionSchedule/periodRule
    group: submission-period
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/reportingPartner
    group: sp-reporting-partner
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/reportingPartner/*
    group: sp-reporting-partner
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/reportingPartner/partnerOverlayView
    group: sp-reporting-partner
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/reportingPartner/partnerOverlayView/*
    group: sp-reporting-partner
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/dataType
    group: sp-data-type
    actions: [VIEW]

  - name: SubmissionPeriod/submissionSchedule/dataType/*
    group: sp-data-type
    actions: [VIEW]

  # End Submission Period

  # Begin Export Request

  - name: ExportRequest
    group: export
    actions: [VIEW, UPDATE]

  - name: ExportRequest/*
    group: export
    actions: [VIEW, UPDATE]

  # End Export Request

  ### Begin Base resources

  - name: About
    group: about
    actions: [VIEW]

  - name: About/*
    group: about
    actions: [VIEW]

  - name: UserEvent
    group: user-event
    actions: [VIEW, UPDATE]

  - name: UserEvent/*
    group: user-event
    actions: [VIEW, UPDATE]

  - name: ObjectLock
    group: object-lock
    actions: [VIEW, UPDATE]

  - name: ObjectLock/*
    group: object-lock
    actions: [VIEW, UPDATE]

  - name: ObjectLockResponse
    group: object-lock-response
    actions: [VIEW]

  - name: ObjectLockResponse/*
    group: object-lock-response
    actions: [VIEW]

  - name: MutationResponse
    group: mutation-response
    actions: [VIEW]

  - name: MutationResponse/*
    group: mutation-response
    actions: [VIEW]

  - name: DynamicAttrMetadata
    group: attr-metadata
    actions: [VIEW]

  - name: DynamicAttrMetadata/*
    group: attr-metadata
    actions: [VIEW]
    

  ### End Base resources

  ### Begin mutation resources

  - name: Product/mutation/*
    group: product-update
    actions: [UPDATE]

  - name: Sales/mutation/*
    group: sales-update
    actions: [UPDATE]

  - name: Inventory/mutation/*
    group: inventory-update
    actions: [UPDATE]

  - name: ExportRequest/mutation/*
    group: export
    actions: [UPDATE]

  - name: SubmissionPeriod/mutation/*
    group: submission-period-mutation
    actions: [UPDATE]

    ### End mutation resources

    ### Begin Customer Resources

  - name: INT
    actions: [VIEW]

  - name: ACS
    actions: [VIEW]

  - name: CAMB
    actions: [VIEW]

  - name: CYBERDYNE
    actions: [VIEW]

  - name: COR
    actions: [VIEW]

  - name: INT_CCD
    actions: [VIEW]

  - name: ACS_CCD
    actions: [VIEW]

  - name: CAMB_CCD
    actions: [VIEW]

  - name: QCOM_CCD
    actions: [VIEW]

  - name: COR_CCD
    actions: [VIEW]

    ### End Customer Resources

# Common permissions for all tenants
permissions:

  - name: BasicViewUpdate
    displayName: Background Permissions
    description: Every User needs this permission
    resource-actions:
      - about:[VIEW]
      - user-event:[VIEW, UPDATE]
      - object-lock:[VIEW, UPDATE]
      - object-lock-response:[VIEW]
      - mutation-response:[VIEW]
      - attr-metadata:[VIEW]

  - name: KpiView
    displayName: KPI Tab
    description: KPI Permission Set
    resource-actions:
      - ProductKpiTab:[VIEW]

  - name: SSKpiFields
    displayName: Submission KPI Fields
    description: Submission KPI Fields Permission Set
    resource-actions:
      - ssKpi:[VIEW]

  - name: FilesKpiFields
    displayName: Files KPI Fields
    description: Files KPI Fields Permission Set
    resource-actions:
      - filesKpi:[VIEW]

  - name: FileTab
    displayName: File Tab
    description: File Permission Set
    resource-actions:
      - FilesTab:[VIEW]

  - name: FileUploadPartner
    displayName: File Upload for Partner
    description: File Upload Permission Set
    resource-actions:
      - DataFile:[VIEW, UPDATE] 
      - file-upload:[VIEW]     

  - name: FileUpload
    displayName: File Upload 
    description: File Upload Permission Set
    resource-actions:
      - DataFile:[VIEW]
      - file-upload:[VIEW]
      - reporting-partner:[VIEW]

  - name: FileDownload
    displayName: File Download
    description: File Download Permission Set
    resource-actions:
      - DataFile:[VIEW]
      - file-download:[VIEW]
      - file-validation-download:[VIEW]

  - name: SubmissionTab
    displayName: Submission Tab
    description: File Permission Set
    resource-actions:
      - SubmissionTrackingTab:[VIEW]
      - SubmissionResultsTab:[VIEW]

  - name: FileManufactureView
    displayName: File Admin View
    description: File Admin Permission Set
    resource-actions:
      - file-management:[VIEW]
      - file-reporting-partner:[VIEW]
      - file-data-file-state:[VIEW]
      - file-parser-attempt:[VIEW]

  - name: FilePartnerView
    displayName: File Partner View
    description: File Partner Permission Set
    resource-actions:
      - file-management:[VIEW]
      - file-data-file-state:[VIEW]
      - file-parser-attempt:[VIEW]

  - name: SubmissionManufactureView
    displayName: Submission Admin View
    description: Submission Full Permission Set
    resource-actions:
      - submission-schedule:[VIEW]
      - submission-schedule-notification:[VIEW]
      - ss-reporting-partner:[VIEW]
      - ss-data-type:[VIEW]
      - submission-period:[VIEW]
      - sp-reporting-partner:[VIEW]
      - sp-data-type:[VIEW]
      - sp-no-data-user:[VIEW]
      - submission-period-update:[VIEW]

  - name: SubmissionPartnerView
    displayName: Submission Partner View
    description: Submission Full Permission Set
    resource-actions:
      - submission-schedule:[VIEW]
      - submission-schedule-notification:[VIEW]
      - ss-data-type:[VIEW]
      - submission-period:[VIEW]
      - sp-data-type:[VIEW]
      - sp-no-data-user:[VIEW]
      - submission-period-update:[VIEW]

  - name: SubmissionPartnerUpdate
    displayName: Submission Partner Update
    description: Submission Update Permission Set
    resource-actions:
      - submission-period-update:[UPDATE]
      - submission-period-mutation:[UPDATE]

  - name: SubmissionUpdate
    displayName: Submission Update 
    description: Submission Update Permission Set
    resource-actions:
      - submission-period-update:[UPDATE]
      - submission-period-mutation:[UPDATE]
export const SubmissionDef = `
  type Query {
    submissionPeriods(
      offset: Float, 
      limit: Float,
      filters: SubmissionPeriodFilters,
      sort: SubmissionPeriodSort
    ): [SubmissionPeriod]
    submissionSchedules(
      offset: Float, 
      limit: Float,
      filters: SubmissionScheduleFilters, 
      sort: SubmissionScheduleSort
    ): [SubmissionSchedule]
    submissionScheduleNotifications(
      submissionScheduleSid: ID,
      offset: Float,
      limit: Float,
      filters: SubmissionScheduleNotificationFilters,
      sort: SubmissionScheduleNotificationSort
    ): [SubmissionScheduleNotification]
  }

  type Mutation {
    markNoData(data: [NoDataInput]): [MutationResponse] @auth(object: SubmissionPeriod)
  }

  type SubmissionPeriod {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    expectedDate: Date
    periodStartDate: Date
    periodEndDate: Date
    noData: Boolean
    noDataReason: String
    noDataCreateDate: Date
    onTimeOverride: Boolean
    expectedDay: String
    workingDays: String
    isInPeriodReporter: Float
    trackingLevel: String
    submissionSchedule: SubmissionSchedule
    status: String
    reportedFlag: Boolean
    numberOfFiles: Float
    dataFileSummaryInfo: DataFileSummaryInfo
    submissionPeriodInfoView: SubmissionPeriodInfoView
    submissionPeriodLineItemView: SubmissionPeriodLineItemView
    noDataServiceUser: ServiceUser
  }

  type SubmissionPeriodLineItemView {
    salesLineItemCount: Float
    invLineItemCount: Float
    earliestFileSubmissionDate: Date
  }

  type SubmissionPeriodInfoView {
    numberOfInventoryLines: Float
    numberOfPOSLines:Float
    fileName: String
    fileId: Float
  }

  type DataFileSummaryInfo{
    numberOfPOSLines: Float
    numberOfInventoryLines: Float
    submissionPeriodSid: Float
  }
  
  type SubmissionSchedule {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    dataType: DataType    
    reportingPartner: Partner
    periodRule: String
    name: String
    startDate: Date
    endDate: Date
    expectedDay: String
    workingDays: String
    isInPeriodReporter: Boolean
    weekOfMonth: Float
    monthOfQuarter: Float
  }

  type DataType {
    sid: ID
    createDate: Date
    updateDate: Date
    type: String
  }

  type SubmissionScheduleNotification {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    submissionScheduleSid: ID
    notificationType: NotificationType
    serviceUser: ServiceUser
  }

  enum NotificationType {
    PARSE_SUCCESS
    LATE
    PARSE_FAIL
    EXPECTED
  }

  input SubmissionPeriodFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    expectedDate: DateFilter
    periodStartDate: DateFilter
    periodEndDate: DateFilter
    submissionSchedule: SubmissionScheduleFilters
    status: StringFilter
    reportedFlag: BooleanFilter
    submissionPeriodLineItemView: SubmissionPeriodLineItemViewFilter
    numberOfFiles: NumberFilter
  }
  
  input SubmissionPeriodLineItemViewFilter {
    salesLineItemCount: NumberFilter
    invLineItemCount: NumberFilter
    earliestFileSubmissionDate: DateFilter
  }

  input SubmissionScheduleFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    reportingPartner: PartnerFilter
    name: StringFilter
    dataType: DataTypeFilter
    periodRule: StringFilter
    expectedDay: StringFilter
    workingDays: StringFilter
    startDate: DateFilter
    endDate: DateFilter
    isInPeriodReporter: BooleanFilter
    weekOfMonth: NumberFilter
    monthOfQuarter: NumberFilter
  }

  input DataTypeFilter {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    type: StringFilter
  }

  input SubmissionScheduleNotificationFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    submissionScheduleSid: IDFilter
    notificationType: StringFilter
    serviceUser: ServiceUserFilters
  }

  input SubmissionPeriodSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    expectedDate: SortOption
    periodStartDate: SortOption
    periodEndDate: SortOption
    submissionSchedule: SubmissionScheduleSort
    status: SortOption
    reportedFlag: SortOption
    submissionPeriodLineItemView: SubmissionPeriodLineItemViewSort
    numberOfFiles: SortOption
  }
  
  input SubmissionPeriodLineItemViewSort {
    salesLineItemCount: SortOption
    invLineItemCount: SortOption
    earliestFileSubmissionDate: SortOption
  }

  input SubmissionScheduleSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    customerSid: SortOption
    dataType: DataTypeSort
    reportingPartner: PartnerSort
    periodRule: SortOption
    name: SortOption
    startDate: SortOption
    endDate: SortOption
    expectedDay: SortOption
    workingDays: SortOption
    isInPeriodReporter: SortOption
    weekOfMonth: SortOption
    monthOfQuarter: SortOption
  }

  input DataTypeSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    type: SortOption
  }

  input SubmissionScheduleNotificationSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    notificationType: SortOption
    serviceUser: ServiceUserSort
  }

  input NoDataInput {
    sid: ID!
    noDataReason: String
  }
`;
import { Inject, Service } from 'typedi';
import { FindOptions } from '../base/FindOptions';
import { PartnerService } from '../partner/PartnerService';
import { SubmissionPeriod } from './SubmissionPeriod';
import { SubmissionPeriodInput } from './SubmissionPeriodInput';
import { Operator } from '../base/filters/Operator';
import { ServiceError } from '../base/ServiceError';
import { User } from '../user/User';
import { AuditEventService } from '../event/AuditEventService';
import { CustomerDomainEntityService } from '../base/CustomerDomainEntityService';
import { SubmissionScheduleAuditService } from './SubmissionScheduleAuditService';
import { AuditEvent } from '../event/AuditEvent';
import { ServiceUserService } from '../user/ServiceUserService';
import { AuditTypeService } from '../event/AuditTypeService';
import { SubmissionScheduleAudit } from './SubmissionScheduleAudit';
import { AuditType } from '../event/AuditType';

export const NO_DATA_ACTION_TYPE = 'SubmissionScheduleNoDataReported';

@Service()
export class SubmissionPeriodService extends CustomerDomainEntityService<SubmissionPeriod> {
  @Inject()
  protected partnerService: PartnerService;

  @Inject()
  protected auditEventService: AuditEventService;

  @Inject()
  protected submissionScheduleAuditService: SubmissionScheduleAuditService;

  @Inject()
  protected serviceUserService: ServiceUserService;

  @Inject()
  protected auditTypeService: AuditTypeService;

  constructor() {
    super(SubmissionPeriod);
  }

  getServiceName() {
    return 'SubmissionPeriod';
  }

  async findSubmissionPeriods(
    customerId: string,
    partnerId: string,
    options: FindOptions = new FindOptions()
  ): Promise<SubmissionPeriod[]> {
    const customer = await this.customerService.findOneById(customerId);
    const partner = await this.partnerService.findOneById(partnerId);
    const { offset, limit, filters = {}, sort } = options;

    // return empty array if customer or partner is invalid
    if (!customer || (!partner && !PartnerService.isAll(partnerId))) {
      console.error(
        'Customer ' + customerId + ' or partner ' + partnerId + ' are invalid'
      );
      return [];
    }

    const query = this.repository
      .createQueryBuilder('sp')
      .innerJoinAndSelect(
        'sp.submissionSchedule',
        'ss',
        '"sp"."CUSTOMER_SID" = "ss"."CUSTOMER_SID"'
      )
      .innerJoinAndSelect('ss.dataType', 'dt')
      .innerJoinAndSelect('ss.reportingPartner', 'rp')
      .innerJoinAndSelect('rp.partnerOverlayView', 'csr')
      .leftJoinAndSelect(
        'sp.submissionPeriodLineItemView',
        'spli',
        '"sp"."CUSTOMER_SID" = "spli"."CUSTOMER_SID"'
      )
      .leftJoinAndSelect(
        'sp.dataFileSummaryInfo',
        'dfsi',
        '"sp"."CUSTOMER_SID" = "dfsi"."CUSTOMER_SID"'
      )
      .offset(offset)
      .limit(limit);

    this.buildWhere(filters, query);

    query.andWhere(`"sp"."CUSTOMER_SID" = ${customer.sid}`)
      .andWhere(`"sp"."DELETED" = 0`)
      .andWhere(`"csr"."CUSTOMER_SID" = ${customer.sid}`);

    if (partner) {
      query.andWhere('"ss"."REPORTING_PARTNER_SID" = ' + partner.sid);
    }
    this.addOrderBys(query, sort ?? {});
    let periods: SubmissionPeriod[] = await query.getMany();
    periods = periods.map((period) => {
      if (period.fileIds) {
        period.firstFileId = period.fileIds.split(',')[0];
      }
      return period;
    });

    periods = await this.loadFirstFileFields(customer.sid, periods);

    return periods;
  }

  async loadFirstFileFields(
    customerSid: number,
    periods: SubmissionPeriod[]
  ): Promise<SubmissionPeriod[]> {

    if (periods.length === 0) return periods;

    // construct SQL
    const sql =
      ` select ID "id", FILE_NAME "file_name", CREATE_DATE "create_date" 
        from data_file 
        where customer_sid = ${customerSid} and id in (:ids) `;

    // execute SQL
    let rows = new Map();

    for (let i = 0; i < periods.length; i += 1000) {
      let subSet = periods.slice(i, i + 1000);
      let dfIds = [];
      for (let j = 0; j < subSet.length; j++) {
        if (subSet[j].firstFileId) {
          dfIds.push(`'${subSet[j].firstFileId}'`);
        }
      }
      if (dfIds.length === 0) continue;
      //not a param to avoid bind var peaking
      let inListSql = sql.replace(':ids', dfIds.join(','));

      let results = await this.repository.query(inListSql);
      results.map((r) => {
        rows.set(r.id, r);
      });
    }
    // map SQL result
    return periods.map((period) => {
      if (period.firstFileId) {
        period.firstFileName = rows.get(period.firstFileId).file_name;
        period.firstFileCreateDate = rows.get(period.firstFileId).create_date;
      }
      return period;
    });
  }

  async markNoData(
    customerId: string,
    user: User,
    data: Partial<SubmissionPeriodInput>[]
  ): Promise<ServiceError[]> {
    let sids: number[] = data.map((input: SubmissionPeriodInput) => {
      return input.sid;
    });

    const options: FindOptions = {
      offset: 0,
      limit: 1000,
      filters: {
        sid: {
          operator: Operator.IN,
          values: sids
        }
      }
    };

    const submissionPeriods = await this.findSubmissionPeriods(
      customerId,
      user.partnerId,
      options
    );

    if (submissionPeriods.length <= 0) {
      throw new Error(`Customer ${customerId} or partner ${user.partnerId} are invalid`);
    }

    const serviceUser = await this.serviceUserService.findByLogin(user.nucleusUsername);
    if (!serviceUser) {
      throw new Error(`Service user not found for login ${user.id}`);
    }

    const auditType = await this.auditTypeService.findOneByName(
      NO_DATA_ACTION_TYPE
    );

    let errors: Array<ServiceError> = [];
    let submissionPeriodMap: Map<Number, SubmissionPeriod> = new Map();
    let validInput: Partial<SubmissionPeriodInput>[] = [];

    submissionPeriods.forEach((submissionPeriod) => {
      submissionPeriodMap.set(Number(submissionPeriod.sid), submissionPeriod);
    });

    data.forEach((submissionPeriodInput) => {
      submissionPeriodInput.noData = true;
      submissionPeriodInput.noDataCreateDate = new Date();
      submissionPeriodInput.noDataServiceUserSid = serviceUser.sid;

      let submissionPeriod = submissionPeriodMap.get(Number(submissionPeriodInput.sid))
      let err = submissionPeriod ? this.validateForMarkNoData(submissionPeriod) : null;
      if (submissionPeriod && !err) validInput.push(submissionPeriodInput);
      errors.push(err);
    });

    if (validInput.length === 0) return errors;

    const updateServiceErrors: Array<ServiceError> = await this.updateSubmissionPeriods(
      customerId,
      user,
      validInput,
      auditType
    );

    let dataIndex = 0;
    let validDataIndex = 0;
    data.forEach((submissionPeriodInput) => {
      if (validDataIndex < validInput.length && submissionPeriodInput.sid == validInput[validDataIndex].sid) {
        if (!errors[dataIndex]) {
          errors[dataIndex++] = updateServiceErrors[validDataIndex++];
        }
      } else {
        dataIndex++;
      }
    });

    return errors;
  }

  validateForMarkNoData(submissionPeriod: SubmissionPeriod): ServiceError | null {
    let comparisonDate: Date = new Date();
    comparisonDate.setDate(comparisonDate.getDate() - 31);
    if (submissionPeriod.reportedFlag) {
      return new ServiceError('REPORTED_DATA_ERROR', 'Submission Period already has reported data, so No-Data-To-Report is not applicable.');
    } else if (submissionPeriod.noDataReason != null) {
      return new ServiceError('ALREAD_MARKED_NO_DATA_ERROR', 'Submission Period is already marked as No-Data-To-Report.');
    } else if (submissionPeriod.fileIds) {
      return new ServiceError('LINE_COUNT_ERROR', 'Submission Period already has line items count, so No-Data-To-Report is not applicable.');
    } else if (submissionPeriod.periodEndDate.getTime() < comparisonDate.getTime()) {
      return new ServiceError('GRACE_PERIOD_ERROR', 'Submission Period is beyond the grace period to mark as No-Data-To-Report.');
    }
    return null;
  }

  async updateSubmissionPeriods(
    customerId: string,
    user: User,
    data: Partial<SubmissionPeriodInput>[],
    auditType?: AuditType,
  ): Promise<ServiceError[]> {
    const customer = await this.customerService.findOneById(customerId);
    const partner = await this.partnerService.findOneById(user.partnerId);
    const serviceUser = await this.serviceUserService.findByLogin(user.nucleusUsername);

    if (!serviceUser || serviceUser.sid === 0) {
      throw new Error(`Service user not found for login ${user.id}`);
    }

    let sids: number[] = data.map((input: SubmissionPeriodInput) => {
      return input.sid;
    });

    const options: FindOptions = {
      offset: 0,
      limit: 1000,
      filters: {
        sid: {
          operator: Operator.IN,
          values: sids
        }
      }
    };

    const submissionPeriods = await this.findSubmissionPeriods(
      customerId,
      user.partnerId,
      options
    );

    let submissionPeriodMap = new Map<number, SubmissionPeriod>();
    submissionPeriods.map((submissionPeriod) => {
      submissionPeriodMap.set(Number(submissionPeriod.sid), submissionPeriod);
    });

    return await Promise.all(
      data.map(async (submissionPeriodInput) => {
        try {
          const submissionPeriod = submissionPeriodMap.get(
            Number(submissionPeriodInput.sid)
          );
          if (submissionPeriod) {
            await this.update(
              submissionPeriod.sid,
              Object.assign({}, submissionPeriodInput)
            );
          }

          if (auditType) {
            let auditEvent = new AuditEvent();
            auditEvent = await this.auditEventService.createAuditEvent(
              Object.assign({}, auditEvent, {
                serviceUserSid: serviceUser.sid,
                eventTimeStamp: new Date(),
                customerSid: customer.sid,
                reportingPartnerSid: partner ? partner.sid : null,
                auditTypeSid: auditType.sid,
                parentSid: null,
                createDate: new Date()
              })
            );

            const submissionScheduleAudit = new SubmissionScheduleAudit();
            await this.submissionScheduleAuditService.createSubmissionScheduleAudit(
              Object.assign({}, submissionScheduleAudit, {
                submissionPeriodSid: submissionPeriod.sid,
                submissionScheduleSid: submissionPeriod.submissionScheduleSid,
                customerSid: customer.sid,
                details: null,
                auditEventSid: auditEvent.sid,
                createDate: new Date()
              })
            );
          }

          return null;
        } catch (err) {
          console.log(err);
          return new ServiceError(
            'SUBMISSION_PERIOD_ERR',
            `Submission period could not be updated for : ${submissionPeriodInput.sid}`
          );
        }
      })
    );
  }
}
import { ViewEntity, ViewColumn } from 'typeorm';

@ViewEntity({
  name: 'SUBMISSION_PERIOD_INFO_VIEW',
  expression: `
    SELECT
      ss1.SID AS submissionScheduleId,
      df.ID AS fileId,
      df.FILE_NAME AS fileName,
      df.CREATE_DATE AS fileCreateDate,
      dfsi.NUM_SLIS AS numberOfPOSLines,
      dfsi.NUM_ILIS AS numberOfInventoryLines
    FROM
      SUBMISSION_SCHEDULE ss1
      LEFT JOIN DATA_FILE_SUMMARY_INFO dfsi ON dfsi.SUBMISSION_PERIOD_SID = :sid AND dfsi.CUSTOMER_SID = :cs
      LEFT JOIN DATA_TYPE dt1 ON ss1.DATA_TYPE_SID = dt1.SID
      LEFT JOIN DATA_FILE df ON dfsi.CUSTOMER_SID = df.CUSTOMER_SID AND dfsi.DATA_FILE_SID = df.SID
                              AND df.DELETED = 0 AND df.DATA_TYPE = dt1.TYPE
    WHERE
      ss1.SID = :spssd AND ss1.CUSTOMER_SID = :cs AND df.ID IS NOT NULL
  `,
})
export class SubmissionPeriodInfoView {
  @ViewColumn()
  submissionScheduleId: number;

  @ViewColumn()
  fileId: number;

  @ViewColumn()
  fileName: string;

  @ViewColumn()
  fileCreateDate: Date;

  @ViewColumn()
  numberOfPOSLines: number;

  @ViewColumn()
  numberOfInventoryLines: number;
}
import { Entity, Column, JoinColumn, OneToOne, VirtualColumn, OneToMany } from 'typeorm';
import { CustomerDomainEntity } from '../base/CustomerDomainEntity';
import {
  returnsSubmissionPeriodLineItemView,
  SubmissionPeriodLineItemView
} from './SubmissionPeriodLineItemView';
import {
  reportedFlagSql,
  statusSql,
  fileIdsSql,
  filesCountSql,
  filesDataSql
} from './SubmissionPeriodSql';
import {
  returnsSubmissionSchedule,
  SubmissionSchedule
} from './SubmissionSchedule';
import { ServiceUser, returnsServiceUser } from '../user/ServiceUser';
import { DataFileSummaryInfo, returnsDataFileSummaryInfo } from '../datafile/DataFileSummaryInfo';
import { SubmissionPeriodInfoView } from './SubmissionPeriodInfoView';


export const returnsSubmissionPeriod = () => SubmissionPeriod;
export const dataFileSummaryInfoInverseSide = (dataFileSummaryInfo) =>
  dataFileSummaryInfo.submissionPeriod;

@Entity({ name: 'SUBMISSION_PERIOD' })
export class SubmissionPeriod extends CustomerDomainEntity {
  @Column({ name: 'EXPECTED_DATE' })
  expectedDate: Date;

  @Column({ name: 'PERIOD_START_DATE' })
  periodStartDate: Date;

  @Column({ name: 'PERIOD_END_DATE' })
  periodEndDate: Date;

  @Column({ name: 'SUBMISSION_SCHEDULE_SID', select: false })
  submissionScheduleSid: number;

  @Column({ name: 'ON_TIME_OVERRIDE' })
  onTimeOverride: boolean;

  @Column({ name: 'NO_DATA' })
  noData: boolean;

  @Column({ name: 'NO_DATA_REASON' })
  noDataReason: string;

  @Column({ name: 'NO_DATA_CREATE_DATE' })
  noDataCreateDate: Date;

  @Column({ name: 'NO_DATA_SERVICE_USER_SID', select: false })
  noDataServiceUserSid: number;

  @OneToOne(returnsServiceUser)
  @JoinColumn({ name: 'NO_DATA_SERVICE_USER_SID' })
  noDataServiceUser: Promise<ServiceUser>;

  @Column({ name: 'TRACKING_LEVEL' })
  trackingLevel: string;

  @Column({ name: 'EXPECTED_DAY' })
  expectedDay: number;

  @Column({ name: 'WORKING_DAYS' })
  workingDays: string;

  @Column({ name: 'IS_IN_PERIOD_REPORTER' })
  isInPeriodReporter: number;

  @Column({ name: 'DELETED' })
  deleted: boolean;

  @OneToOne(returnsSubmissionSchedule)
  @JoinColumn({ name: 'SUBMISSION_SCHEDULE_SID' })
  submissionSchedule?: Promise<SubmissionSchedule>;

  @VirtualColumn({ query: statusSql })
  status?: string;

  @VirtualColumn({ query: reportedFlagSql })
  reportedFlag: boolean;

  @VirtualColumn( {query : fileIdsSql} )
  fileIds?: string;

  firstFileId?: string;

  firstFileName?: string;

  firstFileCreateDate?: Date;

  @VirtualColumn( {query : filesCountSql} )
  numberOfFiles?: number;

  @OneToMany(() => SubmissionPeriodInfoView, submissionPeriodInfoView => submissionPeriodInfoView.submissionScheduleId)
  submissionPeriodInfoView?: SubmissionPeriodInfoView[];

  @OneToOne(returnsDataFileSummaryInfo)
  @JoinColumn({ name: 'SID', referencedColumnName: 'submissionPeriodSid' })
  dataFileSummaryInfo?: Promise<DataFileSummaryInfo>;

  @OneToOne(returnsSubmissionPeriodLineItemView)
  @JoinColumn({ name: 'SID', referencedColumnName: 'submissionPeriodSid' })
  submissionPeriodLineItemView?: Promise<SubmissionPeriodLineItemView>;

}
import { DomainEntityService } from '../base/DomainEntityService';
import { Inventory } from './Inventory';
import { Service, Inject } from 'typedi';
import { FindOptions } from '../base/FindOptions';
import { Equal, In } from 'typeorm';
import { ConfigurationService } from '../configuration/ConfigurationService';
import { CustomerService } from '../customer/CustomerService';
import { PartnerService } from '../partner/PartnerService';
import { DynamicAttrsService } from '../attribute/DynamicAttrsService';
import { DataFileService } from '../datafile/DataFileService';
import { SubmissionPeriodService } from '../submission/SubmissionPeriodService';
import { InventoryQuantityService } from './InventoryQuantityService';
import { InventoryPriceService } from './InventoryPriceService';
import { Writer } from '../../writer/Writer';
import { InventoryInput } from './InventoryInput';
import { ServiceError } from '../base/ServiceError';
import { Operator } from '../base/filters/Operator';
import { AppDataSource } from '../../platform/DataSource';

@Service()
export class InventoryService extends DomainEntityService<Inventory> {
  @Inject()
  protected configurationService: ConfigurationService;

  @Inject()
  protected customerService: CustomerService;

  @Inject()
  protected partnerService: PartnerService;

  @Inject()
  protected dynamicAttrsService: DynamicAttrsService;

  @Inject()
  protected dataFileService: DataFileService;

  @Inject()
  protected submissionPeriodService: SubmissionPeriodService;

  @Inject()
  protected inventoryQuantityService: InventoryQuantityService;

  @Inject()
  protected inventoryPriceService: InventoryPriceService;

  @Inject('Writer')
  protected writer: Writer;

  constructor() {
    super(Inventory);
  }

  getServiceName(): string {
    return 'Inventory';
  }

  async findNeedCorrectionInventory(
    customerId: string,
    partnerId: string,
    options: FindOptions = new FindOptions()
  ): Promise<Inventory[]> {
    const customer = await this.customerService.findOneById(customerId);
    const partner = await this.partnerService.findOneById(partnerId);
    const { offset, limit, filters = {}, sort } = options;

    if (!customer || (!partner && !PartnerService.isAll(partnerId))) {
      return Promise.resolve([]);
    }
    const config = await this.configurationService.getConfiguration(customerId);
    const queueName = config.get('needCorrectionInventoryQueueName', 'resign');
    const maxAge = config.get('nmiMaxAgeInDays', '30');

    const query = this.repository
      .createQueryBuilder('inv')
      .leftJoinAndSelect(
        'inv.dynamicAttrs',
        'da',
        '"da"."ATTRIBUTE_TYPE" = \'IL\' and "da"."CUSTOMER_SID" = "inv"."CUSTOMER_SID"'
      )
      .innerJoinAndSelect(
        'inv.dataFile',
        'df',
        '"df"."CUSTOMER_SID" = "inv"."CUSTOMER_SID"'
      )
      .leftJoinAndSelect(
        'inv.submissionPeriod',
        'sp',
        '"sp"."CUSTOMER_SID" = "inv"."CUSTOMER_SID"'
      )      
      .leftJoinAndSelect(
        'sp.submissionSchedule',
        'ss',
        '"sp"."CUSTOMER_SID" = "ss"."CUSTOMER_SID"'
      )
      .leftJoinAndSelect('ss.dataType', 'dt')
      .leftJoinAndSelect(
        'sp.submissionPeriodLineItemView',
        'spli',
        '"sp"."CUSTOMER_SID" = "spli"."CUSTOMER_SID"'
      )
      .leftJoinAndSelect(
        'sp.dataFileSummaryInfo',
        'dfsi',
        '"sp"."CUSTOMER_SID" = "dfsi"."CUSTOMER_SID"'
      )
      .leftJoinAndMapOne(
        'inv.onHandQuantity',
        'inv.inventoryQuantities',
        'onHandInvQuantity',
        '"onHandInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'ON HAND\')'
      )
      .leftJoinAndMapOne(
        'inv.onOrderQuantity',
        'inv.inventoryQuantities',
        'onOrderInvQuantity',
        '"onOrderInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'ON ORDER\')'
      )
      .leftJoinAndMapOne(
        'inv.committedQuantity',
        'inv.inventoryQuantities',
        'committedInvQuantity',
        '"committedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'COMMITTED\')'
      )
      .leftJoinAndMapOne(
        'inv.floatQuantity',
        'inv.inventoryQuantities',
        'floatInvQuantity',
        '"floatInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'FLOAT\')'
      )
      .leftJoinAndMapOne(
        'inv.backorderedQuantity',
        'inv.inventoryQuantities',
        'backorderedInvQuantity',
        '"backorderedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'BACKORDERED\')'
      )
      .leftJoinAndMapOne(
        'inv.returnedQuantity',
        'inv.inventoryQuantities',
        'returnedInvQuantity',
        '"returnedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'RETURNED\')'
      )
      .leftJoinAndMapOne(
        'inv.inTransitQuantity',
        'inv.inventoryQuantities',
        'inTransitInvQuantity',
        '"inTransitInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'TRANSIT\')'
      )
      .leftJoinAndMapOne(
        'inv.unitPrice',
        'inv.inventoryPrices',
        'invPrice',
        '"invPrice"."PRICE_TYPE_SID" = ( SELECT SID FROM PRICE_TYPE WHERE ' +
          'NAME = \'REPORTED_PRICE\') AND "invPrice"."DELETED" = 0'
      )
      .innerJoin(
        'PEH_INV_QUEUE',
        'piq',
        '"piq"."CLIENT_SKU" = "inv"."CLIENT_SKU" and "piq"."INV_LINE_ITEM_SID" = "inv"."SID" ' +
          'and "piq"."CUSTOMER_SID" = "inv"."CUSTOMER_SID"'
      )
      .offset(offset)
      .limit(limit);    

    // add filters for quantity filters
    let quantityFiltersMap = new Map();
    quantityFiltersMap.set('onOrderQuantity', 'onOrderInvQuantity');
    quantityFiltersMap.set('onHandQuantity', 'onHandInvQuantity');
    quantityFiltersMap.set('committedQuantity', 'committedInvQuantity');
    quantityFiltersMap.set('floatQuantity', 'floatInvQuantity');
    quantityFiltersMap.set('backorderedQuantity', 'backorderedInvQuantity');
    quantityFiltersMap.set('returnedQuantity', 'returnedInvQuantity');
    quantityFiltersMap.set('inTransitQuantity', 'inTransitInvQuantity');

    for (let [key, value] of quantityFiltersMap) {
      const quantityFilters = filters[key];
      delete filters[key];
      if (quantityFilters) {
        const quantityWhere =
          this.inventoryQuantityService.buildWhereExpression(
            quantityFilters,
            value
          );
        query.andWhere(quantityWhere);
      }
    }    

    // add unit price condition
    const unitPriceFilters = filters['unitPrice'];
    delete filters['unitPrice'];
    if (unitPriceFilters) {
      const unitPriceWhere = this.inventoryPriceService.buildWhereExpression(
        unitPriceFilters,
        'invPrice'
      );
      query.andWhere(unitPriceWhere);
    }    

    this.buildWhere(filters, query);
    query.andWhere('"inv"."CUSTOMER_SID" = ' + customer.sid)
    .andWhere('"inv"."INVENTORY_DATE" >= sysdate - ' + maxAge)
    .andWhere('"piq"."QUEUE_NAME" = \'' + queueName + "'")
    .andWhere( { 'deleted' : Equal(0) } );

    if (!PartnerService.isAll(partnerId)) {
      query.andWhere('"inv"."REPORTING_PARTNER_SID" = ' + partner.sid);
    }
    
    // add order by
    this.addOrderBys(query, sort);

    return query.getMany();
  }

  async updateInventory(
    customerId: string,
    partnerId: string,
    data: InventoryInput[]
  ): Promise<ServiceError[]> {
    let inventoryToCreate: Inventory[] = [];
    let sids: number[] = data.map((input: InventoryInput) => {
      return input.sid;
    });
    let errors: ServiceError[] = [];

    // Check if partner has access to ili
    let options: FindOptions = {
      offset: 0,
      limit: 1000,
      filters: {
        sid: {
          operator: Operator.IN,
          values: sids
        }
      }
    };
    let inventory: Inventory[] = await this.findNeedCorrectionInventory(
      customerId,
      partnerId,
      options
    );

    let sidsToUpdate: number[] = [];
    errors = sids.map((sid) => {
      if (inventory) {
        let s: Inventory = inventory.find((inv: Inventory) => {
          return inv.sid.toString() === sid.toString();
        });
        if (s) {
          sidsToUpdate.push(sid);
          return null;
        }
      }
      return new ServiceError(
        'INVENTORY_NOT_FOUND',
        `Inventory line sid : ${sid} not found`
      );
    });

    if (inventory && inventory.length > 0) {
      let invLineItems: Inventory[] = await this.repository
        .createQueryBuilder('inv')
        // load partner and gs number
        .innerJoinAndSelect('inv.reportingPartner', 'rp')
        .leftJoinAndSelect('rp.gsNumbers', 'gs')
        // load dynamic attrs
        .leftJoinAndSelect('inv.dynamicAttrs', 'da')
        .leftJoinAndMapOne(
          'inv.onHandQuantity',
          'inv.inventoryQuantities',
          'onHandInvQuantity',
          '"onHandInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'ON HAND\')'
        )
        .leftJoinAndMapOne(
          'inv.onOrderQuantity',
          'inv.inventoryQuantities',
          'onOrderInvQuantity',
          '"onOrderInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'ON ORDER\')'
        )
        .leftJoinAndMapOne(
          'inv.committedQuantity',
          'inv.inventoryQuantities',
          'committedInvQuantity',
          '"committedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'COMMITTED\')'
        )
        .leftJoinAndMapOne(
          'inv.floatQuantity',
          'inv.inventoryQuantities',
          'floatInvQuantity',
          '"floatInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'FLOAT\')'
        )
        .leftJoinAndMapOne(
          'inv.backorderedQuantity',
          'inv.inventoryQuantities',
          'backorderedInvQuantity',
          '"backorderedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'BACKORDERED\')'
        )
        .leftJoinAndMapOne(
          'inv.returnedQuantity',
          'inv.inventoryQuantities',
          'returnedInvQuantity',
          '"returnedInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'RETURNED\')'
        )
        .leftJoinAndMapOne(
          'inv.inTransitQuantity',
          'inv.inventoryQuantities',
          'inTransitInvQuantity',
          '"inTransitInvQuantity"."QUANTITY_TYPE_SID" = ( SELECT SID FROM QUANTITY_TYPE WHERE QUANTITY_TYPE = \'TRANSIT\')'
        )
        .leftJoinAndMapOne(
          'inv.unitPrice',
          'inv.inventoryPrices',
          'invPrice',
          '"invPrice"."PRICE_TYPE_SID" = ( SELECT SID FROM PRICE_TYPE WHERE NAME = \'REPORTED_PRICE\') AND "invPrice"."DELETED" = 0'
        )
        .where({ sid: In(sidsToUpdate) })
        .andWhere('"gs"."CUSTOMER_SID" = :customerSid', {
          customerSid: inventory[0].customerSid
        })
        .getMany();

      await Promise.all(
        invLineItems.map(async (invLineItem) => {
          // load serial numbers

          let input: InventoryInput = data.find((inv: InventoryInput) => {
            return inv.sid.toString() === invLineItem.sid.toString();
          });

          invLineItem = Object.assign({}, invLineItem, input);

          // add inv line to list to write to S3.
          inventoryToCreate.push(invLineItem);
        })
      );

      console.log(`Inventory to write to S3 : ${inventoryToCreate.length}`);
      // Write to S3
      if (inventoryToCreate.length > 0) {
        await this.writer.write(
          customerId,
          partnerId,
          this.getServiceName(),
          inventoryToCreate
        );
      }

      // It is safe to delete from PEH after writing to S3, just in case if delete fails,
      // the inv will still be deleted from PEH the json file from S3 is loaded into nucleus.
      // If we delete first and for some reason the writing to S3 fails, there is no way to roll back the db update.
      await Promise.all(
        inventoryToCreate.map(async (invLineItem) => {
          try {
            // delete inventory line from PEH
            await AppDataSource.query(
              'delete from peh_inv_queue where inv_line_item_sid = :sid',
              [invLineItem.sid]
            );
            console.log(`Deleted line item : ${invLineItem.sid} from PEH`);
          } catch (e) {
            console.log(
              `Error while deleting from PEH for inv line : ${JSON.stringify(
                invLineItem
              )} for Customer : ${customerId}`
            );
            console.error(e);
            // eat the error as if delete fails, the only con is User will still be able to see the inv line
            // until the file on S3 is loaded into nucleus
          }
        })
      );
    }

    return errors;
  }
}
import { Inject, Service } from 'typedi';
import { DomainEntityService } from '../base/DomainEntityService';
import { DataFileSummaryInfo } from './DataFileSummaryInfo';
import { CustomerService } from '../customer/CustomerService';
import { SubmissionPeriodService } from '../submission/SubmissionPeriodService';

@Service()
export class DataFileSummaryInfoService extends DomainEntityService<DataFileSummaryInfo> {
  @Inject()
  protected customerService: CustomerService;

  @Inject()
  protected submissionPeriodService: SubmissionPeriodService;

  constructor() {
    super(DataFileSummaryInfo);
  }

  getServiceName() {
    return 'DataFileSummaryInfo';
  }

  async createDataFileSummaryInfo(
    custId: string,
    submissionPeriodSid: number,
    dataFileSid: number,
    numberOfPOSLines: number,
    numberOfInventoryLines: number
  ) {
    const cust = await this.customerService.findOneById(custId);

    await this.create({
      customerSid: cust.sid,
      submissionPeriodSid: submissionPeriodSid,
      dataFileSid: dataFileSid,
      numberOfPOSLines: numberOfPOSLines,
      numberOfInventoryLines: numberOfInventoryLines,
    });
}

}
import { Entity, Column, ManyToOne, JoinColumn} from 'typeorm';
import { CustomerDomainEntity } from '../base/CustomerDomainEntity';
import { returnsSubmissionPeriod } from '../submission/SubmissionPeriod';
import { SubmissionPeriod } from '../submission/SubmissionPeriod';

export const returnsDataFileSummaryInfo = () => DataFileSummaryInfo;
export const returnsSubmissionPeriods = (submissionPeriod) => submissionPeriod.filesData;

@Entity({ name: 'DATA_FILE_SUMMARY_INFO' })
export class DataFileSummaryInfo extends CustomerDomainEntity {

    @ManyToOne(() => SubmissionPeriod)
    @JoinColumn([
        { name: 'SUBMISSION_PERIOD_SID', referencedColumnName: 'sid' },
        { name: 'CUSTOMER_SID', referencedColumnName: 'customerSid' }
    ])
    submissionPeriod: SubmissionPeriod;

    @Column({name:'DATA_FILE_SID'})
    dataFileSid: number;

    @Column({name:'NUM_SLIS'})
    numberOfPOSLines: number;

    @Column({name:'NUM_ILIS'})
    numberOfInventoryLines: number;
    
    // Specify that submissionPeriodSid can be null
    @Column({ name: 'SUBMISSION_PERIOD_SID', nullable: true })
    submissionPeriodSid: number;
}

import { Entity, Column, ManyToOne, JoinColumn} from 'typeorm';
import { CustomerDomainEntity } from '../base/CustomerDomainEntity';
import { returnsSubmissionPeriod } from '../submission/SubmissionPeriod';
import { SubmissionPeriod } from '../submission/SubmissionPeriod';

export const returnsDataFileSummaryInfo = () => DataFileSummaryInfo;
export const returnsSubmissionPeriods = (submissionPeriod) => submissionPeriod.filesData;

@Entity({ name: 'DATA_FILE_SUMMARY_INFO' })
export class DataFileSummaryInfo extends CustomerDomainEntity {

    @ManyToOne(() => SubmissionPeriod)
    @JoinColumn([
        { name: 'SUBMISSION_PERIOD_SID', referencedColumnName: 'sid' },
        { name: 'CUSTOMER_SID', referencedColumnName: 'customerSid' }
    ])
    submissionPeriod: SubmissionPeriod;

    @Column({name:'DATA_FILE_SID'})
    dataFileSid: number;

    @Column({name:'NUM_SLIS'})
    numberOfPOSLines: number;

    @Column({name:'NUM_ILIS'})
    numberOfInventoryLines: number;
    
    // Specify that submissionPeriodSid can be null
    @Column({ name: 'SUBMISSION_PERIOD_SID', nullable: true })
    submissionPeriodSid: number;
}

Certainly! The animation property in CSS is used to apply animations to elements on a webpage. Here is a basic example of how to use it:




.element {
  animation-name: slide-in;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes slide-in {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}




In the above example, we define an animation called slide-in using the @keyframes rule. We then apply this animation to the .element class using the animation-name property. The animation-duration property specifies how long the animation should take, the animation-delay property adds a delay before the animation starts, the animation-iteration-count property specifies how many times the animation should repeat, and the animation-direction property specifies the direction of the animation.

Within the @keyframes rule, we define the different stages of the animation using percentage values. In this example, we start with the element translated to the left by 100% (transform: translateX(-100%)) and end with the element at its original position (transform: translateX(0)).

You can customize the animation by adjusting these properties and the @keyframes rule to achieve different effects.


https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4454200103.html#Related-Topics
f"""
                            <html>
                            <head>
                                <style>
                                    table {{
                                        width: 100%;
                                        border-collapse: collapse;
                                        font-family: Arial, sans-serif;
                                    }}

                                    th, td {{
                                        padding: 12px;
                                        text-align: left;
                                        border-bottom: 1px solid #ddd;
                                    }}

                                    th {{
                                        background-color: #f2f2f2;
                                    }}

                                    tr:hover {{
                                        background-color: #f5f5f5;
                                    }}
                                </style>
                            </head>
                            <body>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Tag Name</th>
                                            <th>Tag Comment</th>
                                            <th>Tag Value</th>
                                            <th>Unit</th>
                                            <th>Time Stamp</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>Tag 1</td>
                                            <td>Comment 1</td>
                                            <td>Value 1</td>
                                            <td>Unit 1</td>
                                            <td>2023-12-19 10:00:00</td>
                                        </tr>
                                        <tr>
                                            <td>Tag 2</td>
                                            <td>Comment 2</td>
                                            <td>Value 2</td>
                                            <td>Unit 2</td>
                                            <td>2023-12-19 10:15:00</td>
                                        </tr>
                                        <tr>
                                            <td>Tag 3</td>
                                            <td>Comment 3</td>
                                            <td>Value 3</td>
                                            <td>Unit 3</td>
                                            <td>2023-12-19 10:30:00</td>
                                        </tr>
                                        <!-- Add more rows as needed -->
                                    </tbody>
                                </table>
                            </body>
                            </html>
                            """
#include<stdio.h>
int sentilinearsearch(int arr[], int size, int target)
{
    int last = arr[size-1];
    arr[size - 1] = target;
    int i=0;
    while(arr[i] !=target){
        i++;
    }
    arr[size-1] = last;
    if(i < size-1 || arr[size - 1]== target){
        return i;
    }
    else{
        return -1;
    }
}
int main()
{
    int arr[] = {3,5,1,8,2};
    int size = sizeof(arr)/sizeof(arr[0]);
    int target = 8;

    int result = sentilinearsearch(arr , size, target);

    if (result != -1){
        printf("element %d is found at index%d\n", target,result);
    }
    else{
        printf("element %d is not fopund", target);
    }
    return 0 ;
}
function woodmart_post_date( $args ) {
	$has_title = get_the_title() != '';
	$attr      = '';
	if ( ! $has_title && ! is_single() ) {
		$url  = get_the_permalink();
		$attr = 'window.location=\'' . $url . '\';';
	}
	$classes  = '';
	$classes .= ' ' . $args['style'];
	$classes .= woodmart_get_old_classes( ' woodmart-post-date' );
	?>
		<div class="post-date wd-post-date<?php echo esc_attr( $classes ); ?>" onclick="<?php echo esc_attr( $attr ); ?>">
			<span class="post-date-day">
				<?php echo get_the_time( 'd' ); ?>
			</span>
			<span class="post-date-month">
				<?php echo get_the_time( 'M' ); ?>
			</span>
			<span class="post-date-year">
				<?php echo get_the_time( 'Y' ); ?>
			</span>
		</div>
	<?php
}
/* eslint-disable func-names */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
/* eslint-disable no-alert */
/* eslint-disable no-unreachable-loop */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-dupe-else-if */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-confusing-arrow */
/* eslint-disable no-nested-ternary */
/* eslint-disable no-fallthrough */
/* eslint-disable consistent-return */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable @typescript-eslint/comma-spacing */
/* eslint-disable array-callback-return */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react/prop-types */
/* eslint-disable max-len */
/* eslint-disable react/no-array-index-key */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react/destructuring-assignment */
import * as React from 'react';
import './styles.scss';
// MUI imports
import { styled } from '@mui/material/styles';
import Stack from '@mui/material/Stack';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';
import StepDoneIcon from '@mui/icons-material/Done';
import StepConnector, {
  stepConnectorClasses,
} from '@mui/material/StepConnector';
import { StepIconProps } from '@mui/material/StepIcon';
// import Button from '@mui/material/Button';
// import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

// Package imports
import {
  useParams, useNavigate, useLocation, Navigate,
} from 'react-router';
import { useSelector, useDispatch } from 'react-redux';
import { Modal, Button } from 'react-bootstrap';
import { trackPromise } from 'react-promise-tracker';

// Redux Reducers import
import {
  WillStepState,
  fetchWillStepList,
  willStepSelector,
} from '@redux/slices/wills-steps-list';
import {
  WillBeneficiaryShareStateaftersave,
  fetchWillBeneficiaryShareStateaftersave,
  willBeneficiaryShareListSelector,
} from '@redux/slices/wills-getbeneficiary-sharelist';
import {
  WillBeneficiaryState,
  fetchWillBeneficiaryState,
  willBeneficiaryListSelector,
} from '@redux/slices/wills-shares-estate';
import {
  WillBeneficiaryShareState,
  fetchGetAllPropertyDetailsDetailsByProfileID,
  willBeneficiaryListShareSelector,
  fetchGetBeneficiaryShareList,
} from '@redux/slices/wills-specific-estate';
import {
  fetchPersonalInformationByGuid,
  getServiceId,
  resetErrorState,
  setErrorInfo,
  setIsSpouseSelected,
  setShowSpouseDetails,
  setTestatorName,
  willPersonalInformationSelector,
} from '@redux/slices/will-personal-information';
import {
  WillBookState,
  fetchWillBookState,
  willBookSelector,
} from '@redux/slices/wills-book-appointment';

import {
  WillSubstituteBeneficiaryState,
  fetchWillSubsitituteBeneficiaryState,
  willSubstituteBeneficiaryListSelector,
} from '@redux/slices/will-substitute-beneficiarylist';

import {
  checkMirrorWillSelected,
  checkSingleWillSelected,
  checkVirtualSelected,
  clearSelectedDistribution,
  clearSelectedWillType,
  disableNavigation,
  fetchIncompleteSteps,
  getIncompleteSteps,
  getNewActiveStep,
  setCompletedStepList,
  setCompletedSteps,
  setHighlightedSteps,
  setHusbandCompletedSteps,
  setIsChangeService,
  setIsCompleteWillInfo,
  setIsTestatorStepsCompleted,
  setIsUpgradeWill,
  setNavigationIndex,
  setShowIncompleteStepsModal,
  setSpouseCompletedSteps,
  setStepFlow,
  setWillPreviewCompleted,
  setWillTypeID,
  storeActiveStep,
  willsValidatorSelector,
} from '@redux/slices/willsValidator';
import {
  setPropertyAdded,
  willRealEstateSelector,
} from '@redux/slices/will-realEstate';
import { setBeneficiaryAdded, willBeneficiaryDataSelector } from '@redux/slices/wills-beneficiary-details';
import { clearState } from '@redux/reducers/actions';

import {
  fetchActiveServices,
  fetchLawyerDraftWills,
  setIsModifyWill,
  setModifyAppointment,
  willActiveServiceSelector,
} from '@redux/slices/will-active-service';
import {
  setFromWillPreview,
  willPreviewSelector,
} from '@redux/slices/will-preview';
import {
  setFromUploadDocs,
  willDocumentUploadSelector,
} from '@redux/slices/will-documents-upload';
import { willAccountInformationSelector } from '@redux/slices/wills-financial-Accounts';
import { willCompanyShareInformationSelector } from '@redux/slices/will-company-share-information';

// Assets Import
import tickIcon from '@assets/tick.svg';
import closeIcon from '@assets/Group 151.svg';
import sticker from '@assets/Rectangle 786.png';

// Components Import
import WillTypeSelection from '@components/WillTypeSelection';
import WillPayment from '@components/WillPayment';
import WillRealEstateDetail from '@components/WillRealEstateDetail';
import WillBookAppointment from '@components/WillBookAppointment';
import CompanyShareInfo from '@components/CompanyShareInfo';
import RegistrationStepper from '@components/RegistrationStepper';
import WillBeneficiaryDetail from '@components/WillBeneficiaryDetail';
import WillsMinorChildren from '@components/WillsMinorChildern';
import WillExecutorDetail from '@components/WillExecutorDetail';
import WillRealEstateDistribution from '@components/WillRealEstateDistribution';
import WillBySpecificRealEstate from '@components/WillBySpecificRealEstate';
import WillBySpecificRealEstateBusinessOwners from '@components/WillBySpecificRealEstateBusinessOwners';
import WillBySpecificRealEstateFinancialAssets from '@components/WillBySpecificRealEstateFinancialAssets';
import WillBySharesOfEstate from '@components/WillBySharesOfEstate';
import DocumentManager from '@components/DocumentManager';
import WillPersonalInformation from '@components/WillPersonalInformation';
import WillDraftDetail from '@components/WillDraftDetail';
import WillWitnessDetails from '@components/WillWitnessDetails';
import WillInterimGuardianDetail from '@components/WillInterimGuardianDetail';
import WillGuardianDetail from '@components/WillGuardianDetail';
import WillGuardianInformation from '@components/WillGuardianInformation';
import AccountsInformation from '@components/AccountsInformation';
import MovableAndImmovableProperty from '@components/MovableAndImmovableProperty';
import WillLocationTypeSelection from '@components/WillLocationTypeSelection';
import WillPreview from '@components/WillPreview';
import ScaffoldingIcons from '@components/ScaffoldingIcons';
import QuickBookingWarningModal from '@components/QuickBookingWarningModal';
import { dropDownSelector } from '@redux/slices/dropDowns';
import { willPaymentDetailSelector } from '@redux/slices/will-payment-detail';
import {
  BUISINESS_OWNERS_WILL, FINANCIAL_ASSETS_WILL, FULL_WILL, GUARDIANSHIP_WILL, PROPERTY_WILL, TEMPLATED_FULL_WILL,
} from '@utils/config';
import useWillsIncompleteSteps from '@utils/hooks/useWillsIncompleteSteps';
import getIncompleteStepsList from '@utils/getIncompleteSteps';
import getThirdStepName from '@utils/getThirdStepName';
import useHandleReload from '@utils/hooks/useHandleReload';
import useWillsCompletedSteps from '@utils/hooks/useWillsCompletedSteps';
import { loginSelector } from '@redux/slices/login-flow';
import IncompleteStepsModal from './incompleteStepsModal';
// API
import api from '../../api';

// import DeleteConfirmationModal from '@components/DeleteConfirmationModal';
const DeleteConfirmationModal = React.lazy(
  () => import('@components/DeleteConfirmationModal'),
);

const ColorlibConnector = styled(StepConnector)(({ theme }) => ({
  [`&.${stepConnectorClasses.alternativeLabel}`]: {
    top: 22,
  },
  [`&.${stepConnectorClasses.active}`]: {
    [`& .${stepConnectorClasses.line}`]: {
      height: 3,
      border: 0,
      backgroundColor:
        theme.palette.mode === 'dark' ? theme.palette.grey[800] : '#eaeaf0',
      borderRadius: 1,
    },
  },
  [`&.${stepConnectorClasses.completed}`]: {
    [`& .${stepConnectorClasses.line}`]: {
      height: 3,
      border: 0,
      backgroundColor:
        theme.palette.mode === 'dark' ? theme.palette.grey[800] : '#eaeaf0',
      borderRadius: 1,
    },
  },
  [`& .${stepConnectorClasses.line}`]: {
    height: 3,
    border: 0,
    backgroundColor:
      theme.palette.mode === 'dark' ? theme.palette.grey[800] : '#eaeaf0',
    borderRadius: 1,
  },
}));

const ColorlibStepIconRoot = styled('div')<{
  ownerState: { completed?: boolean; active?: boolean };
}>(({ theme, ownerState }) => ({
  backgroundColor:
    theme.palette.mode === 'dark' ? theme.palette.grey[700] : '#1B202D',
  zIndex: 1,
  color: '#fff',
  width: 60,
  height: 60,
  display: 'flex',
  borderRadius: '50%',
  justifyContent: 'center',
  alignItems: 'center',
  // marginRight: (ownerState.completed || ownerState.active) ? 327 : 0,
  ...(ownerState.active && {
    backgroundColor: '#023979',
    boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
  }),
  ...(ownerState.completed && {
    backgroundColor: '#3ECDAB',
  }),
}));

function ColorlibStepIcon(
  props: StepIconProps & {
    stepNumber: Array<number>;
    currentIndex: number;
    data: Array<string>;
  },
) {
  // , data: Array<string>, currentIndex: number
  const {
    active, completed, className, currentIndex, stepNumber, icon, data,
  } = props;
  // console.log('props',props);
  const { currentStep } = useSelector(willsValidatorSelector);

  const selectedNum = currentIndex - 1;

  // console.log('currentIndex', currentIndex);
  // console.log('stepNumber', stepNumber);

  // console.log('currentStep from selector in custom comp', currentStep);

  const icons: { [index: string]: React.ReactElement | any } = {
    1: completed ? <StepDoneIcon /> : null,
    2: completed ? <StepDoneIcon /> : null,
    3: completed ? <StepDoneIcon /> : null,
    4: completed ? <StepDoneIcon /> : null,
    5: completed ? <StepDoneIcon /> : null,
    6: completed ? <StepDoneIcon /> : null,
    7: completed ? <StepDoneIcon /> : null,
    8: completed ? <StepDoneIcon /> : null,
    9: completed ? <StepDoneIcon /> : null,
    10: completed ? <StepDoneIcon /> : null,
    11: completed ? <StepDoneIcon /> : null,
    12: completed ? <StepDoneIcon /> : null,
    13: completed ? <StepDoneIcon /> : null,
    14: completed ? <StepDoneIcon /> : null,
    15: completed ? <StepDoneIcon /> : null,
    16: completed ? <StepDoneIcon /> : null,
  };

  return (
    <ColorlibStepIconRoot
      ownerState={{ completed, active }}
      className={className}
    >
      {icons[String(props.icon)] ? icons[String(icon)] : icon}
    </ColorlibStepIconRoot>
  );
}
export interface CustomizedSteppersProps {
  data: Array<string>;
  currentIndex: number;
  setCurrentIndex: React.Dispatch<React.SetStateAction<number>>;
}

// eslint-disable-next-line max-len, react/function-component-definition
const CustomizedSteppers: React.FC<CustomizedSteppersProps> = () => {
  const [activeStep, setActiveStep] = React.useState(0);
  const [skipped, setSkipped] = React.useState(new Set<number>());
  // const [completedSteps, setCompletedSteps] = React.useState([]);
  const [num1, setNum1] = React.useState(0);
  const [num2, setNum2] = React.useState(1);
  const [currentBtnStep, setCurrentBtnStep] = React.useState<number>();
  const [iconNum1, setIconNum1] = React.useState(0);
  const [iconNum2, setIconNum2] = React.useState(3);
  const [childData, setChildData] = React.useState('');
  const [childData1, setChildData1] = React.useState('');
  const [currentIndex, setCurrentIndex] = React.useState(0);
  const [data, setdata] = React.useState<string>();
  const [newCompletedSteps, setNewCompletedSteps] = React.useState([]);
  // const [incompleteSteps, setIncompleteSteps] = React.useState([]);
  const [isShowBookAppointment, setIsShowBookAppointment] = React.useState(false);
  const [currentSelectedStep, setCurrentSelectedStep] = React.useState<number>(null);
  // Will Preview Reached
  const [willPreviewReached, setWillPreviewReached] = React.useState<boolean>(false);
  // Skip to bookAppointment flag
  const [showSkipToAppointmentModal, setShowSkipToAppointmentModal] = React.useState<boolean>(false);
  const [stepLabel, setStepLabel] = React.useState([]);
  // Steps to map in the modal (incomplete steps)
  const [steps, setSteps] = React.useState<any>([]);
  const [spouseIncomplete, setSpouseIncomplete] = React.useState<any>([]);
  const [husbandIncomplete, setHusbandIncomplete] = React.useState<any>([]);
  const [show, setShow] = React.useState<boolean>(false);

  // Router Navigation
  const navigate = useNavigate();
  const { state } = useLocation();
  console.log('state', state);

  // Params
  const { parameterGuid } = useParams();
  // Will type ID (For identifying willTypes)
  // const willTypeID = Number(parameterGuid);

  // Dispatch actions using dispatch
  const dispatch = useDispatch();

  // Store Subscriptions
  const {
    mirrorWillCheck,
    singleWillCheck,
    currentStep,
    newActiveStep,
    navigationEnabled,
    navigationIndex,
    isQuickBooking,
    guardianShipWill,
    byShareCheck,
    bySpecificCheck,
    isVirtual,
    isInPerson,
    incompleteSteps,
    spouseCompletedSteps,
    husbandCompletedSteps,
    willPreviewCompleted,
    isCompleteWillInfo,
    isChangeService,
    willTypeID, // Will type ID (For identifying willTypes)
    isUpgradeWill,
    showIncompleteStepsModal,
    highlightedStep,
    distributionCompleted,
    isMirrorWill,
  } = useSelector(willsValidatorSelector);

  // Will Personal Informations
  const {
    profileGuid, isSpouseSelected, spouseGuid, serviceId,
  } = useSelector(
    willPersonalInformationSelector,
  );

  // User loggedIn Slice
  const { userData } = useSelector(loginSelector);

  const { lawyerDraftWills } = useSelector(willActiveServiceSelector);

  // Step List
  const { results, loading, hasErrors } = useSelector<unknown, WillStepState>(
    willStepSelector,
  );

  // States to handle incompleteSteps Modal
  const { fromWillPreview } = useSelector(willPreviewSelector);
  const { fromUploadDocs,isDocumentsChanged } = useSelector(willDocumentUploadSelector);

  // Active service
  const { activeService, isModifyWill, modifyAppointment } = useSelector(
    willActiveServiceSelector,
  );

  // Distribution of Shares Enabling conditions
  const { propertyAdded, propertyList, isPropertyChanged } = useSelector(
    willRealEstateSelector,
  );
  const { beneficiaryAdded, isBeneficiaryChanged,beneficiaryList } = useSelector(
    willBeneficiaryDataSelector,
  );

  const { accountList, isaddAccountInformation } = useSelector(
    willAccountInformationSelector,
  );
  const { companyShareInformationList, isCompanyShareInformationChanged } = useSelector(willCompanyShareInformationSelector);

  const { selectedEmiratesList } = useSelector(dropDownSelector);

  const { handleRedirectEvent } = useSelector(willPaymentDetailSelector);

  const willTypeNumber = localStorage.getItem('willTypeID');
  const willTypeId = Number(willTypeNumber);

  const handleChildData = (data: string) => {
    setChildData(data);
  };
  const handleDataFromChild = (data: string) => {
    setChildData1(data);
  };
  const [showModal, setShowModal] = React.useState(false);
  const [draftSActiveService, setDraftSActiveService] = React.useState<any>([]);

  console.log('draftSActiveService', draftSActiveService);

  React.useEffect(() => {
    switch (activeService?.length) {
      case 2:
        // There is a modify will service available in active services
        setDraftSActiveService(activeService[1]);
        break;
      case 1:
        // There is only one active service in active services API
        setDraftSActiveService(activeService[0]);
        break;
      default:
      // Do nothing
    }
  }, [activeService]);

  // Custom hook to handle Reload when on forms => Wills,Registrations,Cases etc
  useHandleReload(activeService,'/wills');

  /**
   * Handles showing the incomplete steps modal.
   *
   * @param {string} stepName - The name of the step.
   * @return {void} This function does not return anything.
   */
  const handleShowIncompleteStepsModal = (stepName?: string): void => {
    setShowModal(true);
  };

  /**
   * Handles closing of the incomplete steps modal.
   *
   * @return {void} This function does not return anything.
   */
  const handleCloseModal = (): void => {
    setShowModal(false);
    dispatch(setShowIncompleteStepsModal(false));
  };

  const isStepSkipped = (step: number) => skipped.has(step);

  /**
   * Retrieves the list of completed steps for a given user profile.
   *
   * @return {Promise<void>} This function does not return anything.
   */
  const getCompletedSteps = React.useCallback(async () => {
    const completedSteps = await trackPromise(
      api.getCompletedStepsListByGUID(
        isSpouseSelected ? spouseGuid : profileGuid,
      ),
    );
    const completedStepNumbers = completedSteps?.data?.Output;
    const steps = completedStepNumbers.map((stepNumber: any) => Number(stepNumber.stepNumber));
    setNewCompletedSteps(steps);
  }, [isSpouseSelected, spouseGuid, profileGuid]);

  React.useEffect(() => {
    const condition = willTypeID === TEMPLATED_FULL_WILL || willTypeID === FINANCIAL_ASSETS_WILL || willTypeID === PROPERTY_WILL || willTypeID === BUISINESS_OWNERS_WILL;
    if (condition) {
      if (newCompletedSteps.includes(3) && newCompletedSteps.includes(5)) {
        dispatch(setPropertyAdded(true));
        dispatch(setBeneficiaryAdded(true));
      } else {
        dispatch(setPropertyAdded(false));
        dispatch(setBeneficiaryAdded(false));
      }
    }
  },[newCompletedSteps,willTypeID]);

  // Clear all states here (global && local)
  // Page Mount LifeCycle
  React.useEffect(() => {
    dispatch<any>(fetchActiveServices());
    window.scrollTo(0, 0);
    dispatch(clearState());
    // dispatch(storeActiveStep(0));
    // Set activeStep (stepID) === 1(willTypeSelection) on initial page mount
    dispatch(getNewActiveStep(1));
    dispatch(clearSelectedWillType());
    // Set Default step as will type selection
    dispatch(storeActiveStep(0));
    // Set highlighted step to 1
    dispatch(setHighlightedSteps(1));
    dispatch(resetErrorState());
    setNewCompletedSteps([]);
    window.addEventListener('popstate', () => {
      window.location.reload();
    });

    return () => {
      window.removeEventListener('popstate', () => console.log('listner removed'));
      // setNewCompletedSteps([]);
    };
  }, []);

  // If user is a draftsman fetch draftsman details here
  React.useEffect(() => {
    if (userData.DraftsmanGuid) {
      dispatch<any>(fetchLawyerDraftWills());
    }
  },[userData]);

  //  if the selected lawyer from the Draftman list is mirrorWill then set the mirrorwill flag to true
  React.useEffect(() => {
    setTimeout(() => {
      if (isMirrorWill) {
        dispatch(checkMirrorWillSelected());
      }
    },100);
  },[]);

  // Redirect to wills page if the dummy url is entered by the user
  React.useEffect(() => {
    if (state === null) {
      navigate('/wills');
    }
  }, [state]);

  // Fetch completedSteps each time the switcher is changed or Beneficiary or (account/property/company) is added || removed && if document is uploaded or removed (in any case)
  const getCompletedStepsCallback = React.useCallback(() => getCompletedSteps(), [
    isSpouseSelected,
    isBeneficiaryChanged,
    isPropertyChanged,
    isCompanyShareInformationChanged,
    isaddAccountInformation,
    isDocumentsChanged,
  ]);

  React.useEffect(() => {
    getCompletedStepsCallback();
  }, [getCompletedStepsCallback]);

  // If accountList is present && propertyList is present && companyShareInformationList is present ==> enable condition to allow Distribution Of Shares/Accounts
  React.useEffect(() => {
    if (
      accountList?.length !== 0
      || propertyList?.length !== 0
      || companyShareInformationList?.length !== 0
      || selectedEmiratesList?.length !== 0
    ) {
      dispatch(setPropertyAdded(true));
    } else {
      dispatch(setPropertyAdded(false));
    }
  }, [accountList, propertyList, companyShareInformationList,selectedEmiratesList]);

  React.useEffect(() => {
    if (beneficiaryList.length > 0) {
      dispatch(setBeneficiaryAdded(true));
    } else {
      dispatch(setBeneficiaryAdded(false));
    }
  },[beneficiaryList]);

  // If stepNumber === 3 OR 5 is not present in completedSteps response && activeStep === Distribution Of Shares ==> TODO ==> Redirection to any other step ?
  React.useEffect(() => {
    if (
      (!newCompletedSteps.includes(3) || !newCompletedSteps.includes(5))
      && (newActiveStep === 18 || newActiveStep === 6)
    ) {
      setShow(true);
      // const result = window.confirm('Please complete accounts/property/company && beneficiary steps');
      // if (result) {
      //   // Navigate to step 4 for now ==> change later on
      //   dispatch(setHighlightedSteps(5));
      //   dispatch(setNavigationIndex(5));
      //   dispatch(getNewActiveStep(5));
      // } else {
      //   dispatch(setHighlightedSteps(5));
      //   dispatch(setNavigationIndex(5));
      //   dispatch(getNewActiveStep(5));
      // }
    }
  }, [newCompletedSteps, newActiveStep]);

  // If activeServices present && changeService is true && has willTypeID ==> set willTypeID from activeServices here
  React.useEffect(() => {
    if (isChangeService && draftSActiveService?.willTypeID) {
      dispatch(setWillTypeID(draftSActiveService?.willTypeID));
    }
  }, [activeService, isChangeService]);

  // Set willtypeID here if lawyerDetails have willtypeID and changeService is true ==>  to change dynamically
  // React.useEffect(() => {
  //   if (isChangeService && lawyerDraftWills[0]?.willTypeID) {
  //     dispatch(setWillTypeID(lawyerDraftWills[0]?.willTypeID));
  //   }
  // },[lawyerDraftWills]);

  /**
   * Handles Complete Will Info Functionality
   *
   * @return {Promise<void>} A promise that resolves when the function completes.
   */
  const handleCompleteWillInfo = async (): Promise<void> => {
    try {
      // Get Completed Steps list and enable tick mark condition in the stepper
      await getCompletedSteps();
      // dispatch(setShowSpouseDetails(false));

      const {
        stepID,stepNumber,steps,testatorSteps,spouseSteps,
      } = await getIncompleteStepsList(
        profileGuid,
        spouseGuid,
        isSpouseSelected ? spouseGuid : profileGuid,
        serviceId,
      );
      console.log('totalSteps',steps);
      console.log('spouseSteps',spouseSteps);
      console.log('testatorSteps',testatorSteps);
      // dispatch(setIsSpouseSelected(!!spouseSteps)); need clarity here

      const getStepID = () => testatorSteps.length > 0 ? testatorSteps[0].stepID : spouseSteps[0].stepID;

      const getStepNumber = () => testatorSteps.length > 0 ? Number(testatorSteps[0].stepNumber) : Number(spouseSteps[0].stepNumber);

      if (steps?.length === 0) {
        if (willTypeID === 1) {
          // Full Will
          dispatch(getNewActiveStep(9)); // Book Appointment
          dispatch(setHighlightedSteps(11));
          dispatch(setNavigationIndex(11));
        } else if (willTypeID === 2) {
          // GuardianShip Will
          dispatch(getNewActiveStep(9)); // Book Appointment
          dispatch(setHighlightedSteps(9));
          dispatch(setNavigationIndex(9));
        } else {
          // All other wills
          dispatch(getNewActiveStep(21)); // Will Preview
          dispatch(setHighlightedSteps(9));
          dispatch(setNavigationIndex(9));
        }
      } else {
        /* use this condition to check spouseGUID is present in activeServices Mirror Will
         * if Not ==> redirect all navigation to Personal Details step
         * else ==> redirect to first incomplete step as normal */
        const condition = draftSActiveService?.isMirrorWill
          && draftSActiveService?.spouseProfileGUID === null;
        console.log('draftSActiveServiceincompletewillinfo',draftSActiveService);

        if (singleWillCheck) {
          dispatch(getNewActiveStep(condition ? 2 : getStepID()));
          dispatch(setHighlightedSteps(condition ? 2 : getStepNumber()));
          dispatch(setNavigationIndex(condition ? 2 : getStepNumber()));
        } else if (mirrorWillCheck) {
          dispatch(setIsSpouseSelected(testatorSteps.length === 0));
          dispatch(getNewActiveStep(spouseGuid === null ? 2 : getStepID()));
          dispatch(setHighlightedSteps(spouseGuid === null ? 2 : getStepNumber()));
          dispatch(setNavigationIndex(spouseGuid === null ? 2 : getStepNumber()));
        }
      }
    } catch (error) {
      dispatch(resetErrorState());
      dispatch(setErrorInfo('Some Error occured !'));
    }
  };

  const handleChangeService = async () => {
    dispatch<any>(fetchActiveServices());
    dispatch(setIsCompleteWillInfo(false));
    dispatch(getNewActiveStep(2));
    dispatch(setHighlightedSteps(2));
    dispatch(setNavigationIndex(2));
    // Get Completed Steps list and enable tick mark condition in the stepper
    await getCompletedSteps();
  };

  const handleUpgradeWill = async () => {
    // dispatch(storeActiveStep(1));
    dispatch(setHighlightedSteps(2));
    dispatch(setNavigationIndex(2));
    // dispatch(getNewActiveStep(2));
    // Get Completed Steps list and enable tick mark condition in the stepper
    await getCompletedSteps();
  };

  const handleModifyAppointment = () => {
    if (willTypeID === FULL_WILL) {
      dispatch(getNewActiveStep(9));
      dispatch(setHighlightedSteps(11));
      dispatch(setNavigationIndex(11));
      dispatch(checkVirtualSelected());
    } else if (willTypeID === GUARDIANSHIP_WILL) {
      dispatch(getNewActiveStep(9));
      dispatch(setHighlightedSteps(9));
      dispatch(setNavigationIndex(9));
      dispatch(checkVirtualSelected());
    } else {
      dispatch(getNewActiveStep(9));
      dispatch(setHighlightedSteps(10));
      dispatch(setNavigationIndex(10));
      dispatch(checkVirtualSelected());
    }
  };

  const handleModifyWill = async () => {
    dispatch(storeActiveStep(1));
    dispatch(setHighlightedSteps(2));
    dispatch(setNavigationIndex(2));
    dispatch(getNewActiveStep(2));
  };

  // Complete Will Info Functionality Handled in this useEffect
  React.useEffect(() => {
    if (isCompleteWillInfo) {
      handleCompleteWillInfo();
    }
  }, [isCompleteWillInfo]);

  // If Active Service is present
  React.useEffect(() => {
    if (draftSActiveService?.isMirrorWill) {
      dispatch(checkMirrorWillSelected());
      dispatch(setIsSpouseSelected(false));
    } else {
      dispatch(checkSingleWillSelected());
    }
  }, [activeService, isChangeService]);

  // Change Service functionality
  React.useEffect(() => {
    if (isChangeService) {
      handleChangeService();
    }
  }, [isChangeService]);

  React.useEffect(() => {
    if (isUpgradeWill) {
      dispatch(setWillTypeID(1));
      // TODO ==> complete API integration for upgrade will and check for isUpgradeWill Flag in the response; Use the new profileGUID for fetching completed steps
      handleUpgradeWill();
    }
  }, [isUpgradeWill]);

  // Modify Appointment Functionality ==> Here ==> Navigates to Book Appointment step
  React.useEffect(() => {
    if (modifyAppointment) {
      handleModifyAppointment();
    }
  },[modifyAppointment]);

  // If modifyWill is selected ==> navigate to Personal Details
  /*
  if single will ==> navigate to Personal Details  ==> Done
  if mirror will
          ==> Testator ==> Yes ==> navigate to Personal Details
                       ==> No ==> navigate to Personal Details (change to Single Will)
          ==> Spouse ==> Yes ==> navigate to Personal Details (change to Single Will)
                     ==> Cancel ==> Do Nothing (Close Modal)
  */
  React.useEffect(() => {
    if (isModifyWill) {
      handleModifyWill();
    }
  },[isModifyWill]);

  // Check if property && beneficiary are added for navigation to Real Estate Distribution

  const dateSelected = childData;

  // Fetch all steps list
  React.useEffect(() => {
    dispatch<any>(fetchWillStepList(willTypeID || willTypeId)); // from LocalStorage && Redux
  }, [dispatch, willTypeID, dateSelected, isSpouseSelected,willTypeId]);

  // React.useEffect(() => {
  //   dispatch<any>(fetchWillBookState(dateSelected));
  // }, [dispatch, dateSelected]);

  // Map stepID(Number) to the array
  const stepNumber: any = results?.map((d: any) => d.stepID);
  // Map stepNumber(string) to the array
  const stepNumArray: any = results?.map((d: any) => Number(d.stepNumber));

  // Check draft and remaining will steps here---------------------------------
  const isDraft: boolean = false;

  // if (incompleteSteps.length > 0) {
  //   isDraft = true;
  // } else {
  //   isDraft = false;
  // }

  // test response steps
  const responseSteps = [8, 9];
  const finishedSteps: any = [];
  stepNumber.forEach((s: any) => {
    // Use incompletSteps array here
    if (!responseSteps.includes(s)) {
      finishedSteps.push(s);
    }
  });

  /**
   * Handle continue in incomplete steps modal
   *
   * @param {any} id - stepNumber ()
   * @param {number} number - stepId
   * @return {void} The function does not return anything.
   */
  const handleContinue = async (id: any, number: number): Promise<void> => {
    window.scrollTo(0, 0);
    dispatch(setShowIncompleteStepsModal(false));
    setShowModal(false);

    // Optimization
    if (singleWillCheck) { // TODO ==> Check Single will condition
      dispatch(setNavigationIndex(id));
      dispatch(setHighlightedSteps(id)); // PS:: This is stepNumber
      dispatch(getNewActiveStep(number)); // PS:: This is stepID
    } else if (mirrorWillCheck) {
      if (fromUploadDocs) {
        dispatch(setNavigationIndex(id));
        dispatch(setHighlightedSteps(id)); // PS:: This is stepNumber
        dispatch(getNewActiveStep(number)); // PS:: This is stepID
      }
      if (fromWillPreview) {
        await getCompletedSteps(); // Get completed Steps of the testator/spouse
        await dispatch(setIsSpouseSelected(!isSpouseSelected));
        dispatch(setNavigationIndex(id));
        dispatch(setHighlightedSteps(id)); // PS:: This is stepNumber
        dispatch(getNewActiveStep(number)); // PS:: This is stepID
      }

      // Handle continue case from Submit Button for ModifyAppointment
      // dispatch(setNavigationIndex(id));
      // dispatch(setHighlightedSteps(id)); // PS:: This is stepNumber
      // dispatch(getNewActiveStep(number)); // PS:: This is stepID
    }

    // Set states to initial state/false here after the function is executed
    dispatch(setFromUploadDocs(false));
    dispatch(setFromWillPreview(false));
  };

  const getIncompleteStepsByGuid = (step: any) => {
    const husbandIncompleteSteps = step?.filter(
      (s: any) => s?.bookedForProfileGuid === profileGuid,
    );
    const spouseIncompleteSteps = step?.filter(
      (s: any) => s?.bookedForProfileGuid === spouseGuid,
    );
    setSpouseIncomplete(spouseIncompleteSteps);
    setHusbandIncomplete(husbandIncompleteSteps);
    if (willPreviewCompleted) {
      setSteps(spouseIncompleteSteps);
    } else {
      setSteps(husbandIncompleteSteps);
    }
  };

  React.useEffect(() => {
    if (incompleteSteps?.length !== 0) {
      getIncompleteStepsByGuid(incompleteSteps);
    }
  }, [incompleteSteps]);

  console.log('isShowBookAppointment',isShowBookAppointment);

  // Get StepID when navigating from Beneficiary Details using next button
  const getStepIDFromBeneficiaryStep = (willType: number): number => {
    switch (willType) {
      case PROPERTY_WILL:
        return 6;
      case FINANCIAL_ASSETS_WILL:
      case BUISINESS_OWNERS_WILL:
      case TEMPLATED_FULL_WILL:
        return 18;
      case FULL_WILL:
        return 12;
      default:
        return 0;
    }
  };

  /**
   * Handles the next step in the process.
   *
   * @param {number} step - The current step number.
   * @param {any} stepName - The name of the current step.
   * @param {boolean} completed - Indicates if the step is completed.
   */
  const handleNext = async (
    step: number,
    stepName?: any,
    completed?: boolean,
  ) => {
    console.log('STEPNUMBER', step);
    console.log('COMPLETED', completed);
    window.scrollTo(0, 0);
    setCurrentSelectedStep(step);
    // Revert Active Service Funtionalities back to initial state on first handleNext Step
    dispatch(setIsChangeService(false));
    // dispatch(setIsCompleteWillInfo(false));
    dispatch(setModifyAppointment(false));
    // dispatch(setIsUpgradeWill(false));
    dispatch(setIsModifyWill(false));

    // Set upgradeWill flag to false if next clicked from Personal Details
    if (stepName === 'personal') {
      dispatch(setIsUpgradeWill(false));
    }

    // Show selection option in Real Estate Distribution for Property Will up on next from beneficiary Details
    if (step === 5) {
      dispatch(clearSelectedDistribution());
    }

    // If quick booking is enabled
    if (isQuickBooking && stepName !== 'willTypeSelection') {
      setActiveStep(8);
      if (stepName === 'bookAppointment') {
        setActiveStep((prev) => prev + 1);
      }
    } else if (!isQuickBooking && stepName !== 'willTypeSelection') {
      // setActiveStep(3);
    }

    if (stepName === 'personal' && isQuickBooking) {
      setShowSkipToAppointmentModal(true);
    }

    // If upload documents is active and Book appointment is visible
    if (stepName === 'upload' && !isShowBookAppointment) {
      // Incomplete steps API called here
      try {
        const response = await trackPromise(
          api.validateWillSteps(
            profileGuid,
            spouseGuid,
            isSpouseSelected ? spouseGuid : profileGuid,
            serviceId,
          ),
        );
        // Save incomplete steps list in store (redux)

        const incompletedSteps = response?.data?.Output;
        const testatorIncompleteSteps = incompletedSteps.filter((step:any) => step.bookedForProfileGuid === profileGuid);
        const spouseIncompleteSteps = incompletedSteps.filter((step:any) => step.bookedForProfileGuid === spouseGuid);
        console.log('testatorIncompleteSteps', testatorIncompleteSteps);
        console.log('spouseIncompleteSteps', spouseIncompleteSteps);

        dispatch(getIncompleteSteps(isSpouseSelected ? spouseIncompleteSteps : testatorIncompleteSteps));

        // Mirror Will && Testator
        if (mirrorWillCheck && !isSpouseSelected) {
          if (testatorIncompleteSteps.length !== 0) {
            handleShowIncompleteStepsModal();
          } else {
            // alert('go to next step');
            dispatch(setHighlightedSteps(9));
            dispatch(setNavigationIndex(9));
            dispatch(getNewActiveStep(13));
          }
        } else if (mirrorWillCheck && isSpouseSelected) { // Mirror Will && Spouse
          if (spouseIncompleteSteps.length !== 0) {
            handleShowIncompleteStepsModal();
          } else {
            dispatch(setHighlightedSteps(9));
            dispatch(setNavigationIndex(9));
            dispatch(getNewActiveStep(13));
          }
        }

        if (singleWillCheck) {
          // Show incomplete steps Modal only if the response is not empty
          if (incompletedSteps.length !== 0) {
            handleShowIncompleteStepsModal();
          } else {
          // Ask for confirmation on this functionality
            setIsShowBookAppointment(true);
            // Set View component, highlighted step in stepper and icon
            dispatch(setHighlightedSteps(9));
            dispatch(setNavigationIndex(9));
            dispatch(getNewActiveStep(21));
            setNewCompletedSteps((prev: any) => [...prev, 3, 4, 5, 6, 7, 8]);
          // dispatch(storeActiveStep(9));
          }
        }
      } catch (error) {
        console.log(error);
      }
    } else if (stepName === 'beneficiary-details' && willTypeID !== 1) {
      // Not needed for Full Will
      // If property and beneficiray is added then only we can navigate or go next to Real Estate Distribution
      if (propertyAdded && beneficiaryAdded) {
        dispatch(setHighlightedSteps(6));
        dispatch(getNewActiveStep(getStepIDFromBeneficiaryStep(willTypeID)));
        dispatch(setNavigationIndex(null));
        // // Highlighted step handled here
        // dispatch(setHighlightedSteps(step + 1));
        // // Set Current step number
        // dispatch(disableNavigation());
        // setCurrentSelectedStep(step);
        // // getWillStep(step);
        // const nextIndex = (currentIndex + 1) % stepNumber.length;
        // setCurrentIndex(nextIndex);

        // // setActiveStep((prevActiveStep) => prevActiveStep + 1);
        // // Need more testing here
        // setCurrentBtnStep(step + 1);
        // setActiveStep((prevActiveStep) => prevActiveStep + 1);
        // dispatch(storeActiveStep(step));
        // dispatch(getNewActiveStep(0));
        // dispatch(setNavigationIndex(null));
      } else {
        await dispatch<any>(resetErrorState());
        await dispatch<any>(setErrorInfo(`Please complete Beneficiary Details and ${getThirdStepName(willTypeID)}`));
      }
    } else {
      // ----------------------------------------------------------------
      // Highlighted step handled here
      // dispatch(setHighlightedSteps(step + 1));
      // // Test case
      // // getWillStep(step);
      // dispatch(disableNavigation());
      // const nextIndex = (currentIndex + 1) % stepNumber.length;
      // setCurrentIndex(nextIndex);
      // // dispatch(storeActiveStep(activeStep + 1));

      // // Get stepNumber list from the stepList array
      // const stepNumberList: any = results?.map((res) => Number(res?.stepNumber));

      // // // Handling ICONS navigation in handleNext()
      // if (step === 3) {
      //   setIconNum1(3);
      //   setIconNum2(6);
      // } else if (step === 6) {
      //   setIconNum1(6);
      //   setIconNum2(9);
      // } else if (step === 9) {
      //   if (willTypeID === 2) {
      //     // Guardianship Will
      //     setIconNum1(7);
      //     setIconNum2(10);
      //   } else {
      //     setIconNum1(8);
      //     setIconNum2(11);
      //   }
      // } else if (step > stepNumberList[stepNumberList.length - 2]) {
      //   // setIconNum1(8);
      //   // setIconNum2(11);
      //   navigate('/wills');
      // }

      // // Handle distribution of shares/Real estate distribution in ICONS
      // if (step === 7) {
      //   setIconNum1(6);
      //   setIconNum2(9);
      // }

      // // Set current step to pass as a prop to the further components to use
      // //  the handleNext method in those respective components
      // // NB:increment the step number by 1 to get correct list of completed steps
      // setCurrentBtnStep(step + 1);

      // let newSkipped = skipped;
      // if (isStepSkipped(activeStep)) {
      //   newSkipped = new Set(newSkipped.values());
      //   newSkipped.delete(activeStep);
      // }
      // // Increment activestep from state
      // setActiveStep((prevActiveStep) => prevActiveStep + 1);
      // // Increment currentStep from store state
      // dispatch(storeActiveStep(step));
      // dispatch(setStepFlow());
      // setSkipped(newSkipped);
      // dispatch(getNewActiveStep(0));
      // dispatch(setNavigationIndex(null));

      // if (navigationEnabled) {
      //   setNewCompletedSteps((prevSteps: any) => [
      //     ...prevSteps,
      //     completed ? navigationIndex : null,
      //   ]);
      //   dispatch(setCompletedStepList(completed ? navigationIndex : null));
      //   dispatch(storeActiveStep(navigationIndex));
      //   setActiveStep(navigationIndex);
      // } else {
      //   setNewCompletedSteps((prevStep: any) => [
      //     ...prevStep,
      //     completed ? step : null,
      //   ]);
      //   dispatch(setCompletedStepList(completed ? step : null));
      //   // setNewCompletedSteps((prevStep: any) => [...prevStep,step]);
      // }

      // ----------------------------------------------------------------

      // Stepper/Next Optimisations
      dispatch(setHighlightedSteps(step + 1));
      dispatch(storeActiveStep(step));
      dispatch(getNewActiveStep(0));
      dispatch(setNavigationIndex(step + 1));
      // dispatch(setNavigationIndex(null));

      setNewCompletedSteps((prev:any) => [...prev,completed ? step : null]);
    }
  };

  console.log('stepNumArray', stepNumArray);

  // Stepper Icons (scaffolding Icons) Optimisation
  React.useEffect(() => {
    if (highlightedStep !== 1) {
      if (stepNumArray.length === highlightedStep) {
        setIconNum1(highlightedStep - 3);
        setIconNum2(highlightedStep);
      } else {
        setIconNum1(highlightedStep - 2);
        setIconNum2(highlightedStep + 1);
      }
    }
  },[highlightedStep]);

  React.useEffect(() => {
    if (newActiveStep === 9 && isQuickBooking) {
      setIconNum1(8);
      setIconNum2(11);
    }
    if (willTypeID === 2 && guardianShipWill) {
      // Guardianship Will
      setIconNum1(navigationIndex === 2 ? 0 : 6);
      setIconNum2(navigationIndex === 2 ? 3 : 9);
    }
  }, [newActiveStep, isQuickBooking, guardianShipWill]);

  // Common function for enabling book appointment if all steps are completed
  const checkAllStepsCompleted = (completedSteps:number[],completedStepsList:number[]) => {
    const isAllStepsCompleted = completedSteps.every((step:number) => completedStepsList.includes(step));
    setIsShowBookAppointment(isAllStepsCompleted);
  };

  React.useEffect(() => {
    if (willTypeID === GUARDIANSHIP_WILL) {
      const completedSteps = [1,2,4,5,6];
      checkAllStepsCompleted(completedSteps,newCompletedSteps);
    } else if (willTypeID === FULL_WILL) {
      const completedSteps = [1,2,3,4,7,8];
      checkAllStepsCompleted(completedSteps,newCompletedSteps);
    } else {
      const completedSteps = [1,2,3,4,5,6,7,8];
      checkAllStepsCompleted(completedSteps,newCompletedSteps);
    }
  },[newCompletedSteps]);

  React.useEffect(() => {
    getCompletedSteps();
  },[isShowBookAppointment]);

  const handleBack = () => {
    const activeStepInBack = activeStep - 1;
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
    setNum1((prevState) => prevState - 1);
    setNum2((prevState) => prevState - 1);
    if (
      activeStepInBack === 2
      || activeStepInBack === 5
      || activeStepInBack === 8
      || activeStepInBack === 11
    ) {
      setIconNum1((prevState) => prevState - 3);
      setIconNum2((prevState: any) => prevState - 3);
    }
  };

  const clearRealEstateShareOption = () => {
    dispatch(clearSelectedDistribution());
  };

  const getRealEstateOption = () => {
    if (willTypeID === 5 || willTypeID === 4) {
      // FAW && BOW
      return (
        <WillBySpecificRealEstate
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={clearRealEstateShareOption}
          // parameterGuid={parameterGuid}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }

    if (willTypeID === 6) {
      // Templated Full Will
      return (
        <WillBySharesOfEstate
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={clearRealEstateShareOption}
          parameterGuid={parameterGuid}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }

    if (!byShareCheck && !bySpecificCheck) {
      return (
        <WillRealEstateDistribution
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={handleBack}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }
    if (byShareCheck) {
      return (
        <WillBySharesOfEstate
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={clearRealEstateShareOption}
          parameterGuid={parameterGuid}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }
    if (bySpecificCheck) {
      return (
        <WillBySpecificRealEstate
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={clearRealEstateShareOption}
          // parameterGuid={parameterGuid}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }
  };
  const getRealEstateOptionforfinancial = () => {
    if (willTypeID === 4) {
      // BOW
      return (
        <WillBySpecificRealEstateBusinessOwners
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={handleBack}
          parameterGuid={parameterGuid}
        />
      );
    }
    if (willTypeID === 5) {
      // FAW
      return (
        <WillBySpecificRealEstateFinancialAssets
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={handleBack}
          parameterGuid={parameterGuid}
        />
      );
    }
  };
  const getLocationType = () => {
    if (!isVirtual && !isInPerson) {
      return <WillLocationTypeSelection />;
    }
    if (isVirtual) {
      return (
        <WillBookAppointment
          handleNext={handleNext}
          currentBtnStep={currentBtnStep}
          handleBack={handleBack}
          willTypeID={willTypeID}
          setNewCompletedSteps={setNewCompletedSteps}
          newCompletedSteps={newCompletedSteps}
        />
      );
    }
  };

  React.useEffect(() => {
    getWillStep(currentStep);
    getRealEstateOption();
    getRealEstateOptionforfinancial();
  }, [byShareCheck, bySpecificCheck]);

  React.useEffect(() => {
    getWillStep(currentStep);
    getLocationType();
  }, [isVirtual, isInPerson]);
  const getWillStep = (step: number) => {
    let stepID;
    if (isDraft) {
      // Change responseSteps to incompleteSteps ahen using api
      stepID = responseSteps[step];
    } else {
      stepID = stepNumber[step];
    }
    // console.log('stepIndex', stepID);
    switch (newActiveStep !== 0 ? newActiveStep : stepID) {
      // switch (newActiveStep !== 0 ? newActiveStep : step + 1) {
      case 1:
        return <WillTypeSelection />;
      // return <WillLocationTypeSelection />;
      case 2:
        return (
          <WillPersonalInformation
            willTypeID={willTypeID}
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 3:
        return (
          <WillRealEstateDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
          // <WillGuardianInformation
          //   handleNext={handleNext}
          //   currentBtnStep={currentBtnStep}
          //   handleBack={handleBack}
          // />
        );
      case 4:
        return (
          <WillExecutorDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            willTypeID={willTypeID}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
            // setNewCompletedSteps={setNewCompletedSteps}
          />
        );
      case 5:
        return (
          <WillBeneficiaryDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
            willTypeID={willTypeID}
          />
        );
      case 6:
        return getRealEstateOption();
      case 7:
        return (
          <WillWitnessDetails
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            willTypeID={willTypeID}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 8:
        return (
          <DocumentManager
            willTypeID={willTypeID}
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 9:
        return getLocationType();
      case 10:
        return (
          <WillPayment
            willTypeID={willTypeID}
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
          />
        );
      case 11:
        return (
          <WillGuardianInformation
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            // willTypeID={parameterGuid}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 12:
        return (
          <WillsMinorChildren
            // willTypeGuid={parameterGuid}
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 13:
        return (
          <WillDraftDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            willTypeID={willTypeID}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 15:
        return (
          <WillInterimGuardianDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            // willTypeID={parameterGuid}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 16:
        // Permanent Guardian Details
        return (
          <WillGuardianDetail
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            // willTypeID={parameterGuid}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );

      case 17:
        return (
          <CompanyShareInfo
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 18:
        return getRealEstateOption();
      case 19:
        return (
          <AccountsInformation
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 20:
        return (
          <MovableAndImmovableProperty
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );
      case 21:
        return (
          <WillPreview
            handleNext={handleNext}
            currentBtnStep={currentBtnStep}
            handleBack={handleBack}
            // parameterGuid={parameterGuid}
            handleShowIncompleteStepsModal={handleShowIncompleteStepsModal}
            handleCloseModal={handleCloseModal}
            setNewCompletedSteps={setNewCompletedSteps}
            newCompletedSteps={newCompletedSteps}
          />
        );

      default:
        break;
    }
  };

  // const recievedData = (single:any,mirror:any) => {
  //   console.log('data',single,mirror);
  // };

  return (
    <div className="main">
      <div className="case-details d-flex flex-column">
        <div className="row title-row ">
          <div className="col-lg-3 col-md-3 col-sm-12 col-xs-8 back-col-new">
            <RegistrationStepper
              activeStep={activeStep + 1}
              parameterGuid={parameterGuid}
              results={results}
              stepNumber={stepNumber}
              finishedSteps={finishedSteps}
              isDraft={isDraft}
              stepNumArray={stepNumArray}
              completedStepNumArray={newCompletedSteps.filter(
                (value, index, self) => self.indexOf(value) === index,
              )} // Remove Duplicates
              currentSelectedStep={currentSelectedStep}
              setCurrentSelectedStep={setCurrentSelectedStep}
              isShowBookAppointment={isShowBookAppointment}
              willTypeID={willTypeID}
              setNewCompletedSteps={setNewCompletedSteps}
            />
          </div>
          <div className="col-lg-9 col-md-9 col-sm-12 col-xs-12 title-col">
            <Stack sx={{ width: '100%' }} spacing={4}>
              <Stepper
                activeStep={activeStep}
                alternativeLabel
                connector={<ColorlibConnector />}
              >
                <div className="line" />
                <div className="scaffolding">
                  {results?.slice(iconNum1, iconNum2)?.map((label, index) => (
                    <ScaffoldingIcons
                      stepNumber={label?.stepNumber}
                      stepName={label?.stepName.toUpperCase()}
                      completed={newCompletedSteps.includes(
                        Number(label.stepNumber),
                      )}
                    />
                  ))}
                </div>
              </Stepper>
              {/* {getWillStep(newActiveStep !== 0 ? newActiveStep : currentStep)} */}
              <div className="stepsDiv">
                {(isUpgradeWill || isModifyWill)
                && (newActiveStep === 1 || newActiveStep === 0)
                  ? (
                    <WillPersonalInformation
                      willTypeID={willTypeID}
                      handleNext={handleNext}
                      currentBtnStep={currentBtnStep}
                      handleBack={handleBack}
                      setNewCompletedSteps={setNewCompletedSteps}
                      newCompletedSteps={newCompletedSteps}
                    />
                  ) : (
                    getWillStep(currentStep)
                  )}
              </div>
              {/* Revert back */}
              {newActiveStep === 1 && !isUpgradeWill && (
                <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
                  <button
                    type="button"
                    // Removed activeStep(state variable) from the parameter
                    onClick={() => handleNext(1, 'willTypeSelection', true)}
                    className={
                      !(mirrorWillCheck || singleWillCheck)
                        ? 'next-btn-disabled'
                        : 'next-btn'
                    }
                    disabled={!(mirrorWillCheck || singleWillCheck)}
                  >
                    Next Step
                  </button>
                </Box>
              )}
            </Stack>
          </div>
        </div>
      </div>
      {/* Modal for showing incomplete steps */}
      <IncompleteStepsModal
        showModal={showModal || showIncompleteStepsModal}
        handleCloseModal={handleCloseModal}
        steps={incompleteSteps}
        handleContinue={handleContinue}
      />

      {/* Modal if quickBooking is true */}
      <QuickBookingWarningModal
        showModal={showSkipToAppointmentModal}
        handleCloseModal={() => setShowSkipToAppointmentModal(false)}
      />

      <React.Suspense fallback={<div>Loading...</div>}>
        <DeleteConfirmationModal
          show={show}
          handleClose={() => {
            setShow(false);
            dispatch(setHighlightedSteps(5));
            dispatch(setNavigationIndex(5));
            dispatch(getNewActiveStep(5));
          }}
          handleContinue={() => {
            setShow(false);
            dispatch(setHighlightedSteps(5));
            dispatch(setNavigationIndex(5));
            dispatch(getNewActiveStep(5));
          }}
          type="Test"
          fromShares
        />
      </React.Suspense>
    </div>
  );
};

export default CustomizedSteppers;

/**
 * If navigation is enabled then we need to call a different function instead of handleNext(say:handleNavigateNext)
 * else we use the normal handleNext function and complete the navigation
 *
 */
#include<stdio.h>
int search(int arr[],int N,int x)
{
    for(int i=0; i< N; i++)
    if(arr[i] == x)
    return i;
    return -1;
    }
    int main(void)
    {
        int arr[]={2,3,4,5,10,40};
        int x = 10;
        int N = sizeof(arr) / sizeof(arr[0]);

        int result = search(arr,N,x);
        (result == -1)
        ? printf("element is not present in array")
        :printf("element is present at index %d",result);
        return 0; 
    }
prompt='以下是普通话的句子'
result = model.transcribe(audioFile, task='translate',language='zh',verbose=True,initial_prompt=prompt)
Relationship seems tougher when it comes to one-side efforts, adjustments, miscommunication, or even non-communication with your partner. Sometimes lack of sufficient time and attention also causes a glass-break in love. This may lead to the distance in their bond. In such cases, Couple apps are lovers' ultimate companions because they contribute endless ideas to romanticize your partner, such as remaindering your partner’s favorite things to explore, notifying your special dates, and ideas to express your love and feel with your partner. The solution is there are plenty of apps out there, let me list out the top ten best apps for couples to implement. Check out and revamp your relationship! 
$("button").click(function(){
  $("div").animate({
    left: '250px',
    opacity: '0.5',
    height: '150px',
    width: '150px'
  });
}); 
 const handleOnInputChange = (reason?: string, id?: string | null) => {
    if (!id) {
      setPreviewUrl(null);
      setValue("type", 2);
      reset({ type: 2 });
      if (feeType === FeeType.sameFees) {
        const editCourtValueReset: FormProps = {
          ...getAllValues,
          name: "",
          gameId: "",
          courtId: "",
          midNight: "",
          morning: "",
          evening: "",
          night: "",
          image: "",
        };
        // setValue("midNight", "");
        // setValue("morning", "");
        // setValue("evening", "");
        // setValue("night", "");
        // setValue("courtId", "");

        reset(editCourtValueReset);
      } else {
        setValue("type", 2);
        const dayWiseValues = {
          ...getAllValues,
          name: "",
          // gameId: "",
          // courtId: "",
          midNight: "",
          morning: "",
          evening: "",
          night: "",
          image: "",
          // fees: DAYWISE_FEE,
          type: 2,
        };
        setFeeType(2);
        setDayWiseFeesData(DAYWISE_FEE);
        reset(dayWiseValues);
      }
    }
  };
import { Entity, Column, ManyToOne, JoinColumn} from 'typeorm';
import { CustomerDomainEntity } from '../base/CustomerDomainEntity';
import { returnsSubmissionPeriod } from '../submission/SubmissionPeriod';

export const returnsDataFileSummaryInfo = () => DataFileSummaryInfo;
export const returnsSubmissionPeriods = (submissionPeriod) => submissionPeriod.filesData;

@Entity({ name: 'DATA_FILE_SUMMARY_INFO' })
export class DataFileSummaryInfo extends CustomerDomainEntity {

    @ManyToOne(returnsSubmissionPeriod, returnsSubmissionPeriods)
    @JoinColumn([
        { name: 'SUBMISSION_PERIOD_SID', referencedColumnName: 'sid' },
        { name: 'CUSTOMER_SID', referencedColumnName: 'customerSid' }
    ])
    submissionPeriodSid: number;

    @Column({name:'DATA_FILE_SID'})
    dataFileSid: number;

    @Column({name:'NUM_SLIS'})
    numberOfPOSLines: number;

    @Column({name:'NUM_ILIS'})
    numberOfInventoryLines: number;
    
}

import { Entity, Column, JoinColumn, OneToOne, VirtualColumn, OneToMany } from 'typeorm';
import { CustomerDomainEntity } from '../base/CustomerDomainEntity';
import {
  returnsSubmissionPeriodLineItemView,
  SubmissionPeriodLineItemView
} from './SubmissionPeriodLineItemView';
import {
  reportedFlagSql,
  statusSql,
  fileIdsSql,
  filesCountSql,
  filesDataSql
} from './SubmissionPeriodSql';
import {
  returnsSubmissionSchedule,
  SubmissionSchedule
} from './SubmissionSchedule';
import { ServiceUser, returnsServiceUser } from '../user/ServiceUser';
import { DataFileSummaryInfo, returnsDataFileSummaryInfo } from '../datafile/DataFileSummaryInfo';

export const returnsSubmissionPeriod = () => SubmissionPeriod;
export const dataFileSummaryInfoInverseSide = (dataFileSummaryInfo) =>
  dataFileSummaryInfo.submissionPeriod;

@Entity({ name: 'SUBMISSION_PERIOD' })
export class SubmissionPeriod extends CustomerDomainEntity {
  @Column({ name: 'EXPECTED_DATE' })
  expectedDate: Date;

  @Column({ name: 'PERIOD_START_DATE' })
  periodStartDate: Date;

  @Column({ name: 'PERIOD_END_DATE' })
  periodEndDate: Date;

  @Column({ name: 'SUBMISSION_SCHEDULE_SID', select: false })
  submissionScheduleSid: number;

  @Column({ name: 'ON_TIME_OVERRIDE' })
  onTimeOverride: boolean;

  @Column({ name: 'NO_DATA' })
  noData: boolean;

  @Column({ name: 'NO_DATA_REASON' })
  noDataReason: string;

  @Column({ name: 'NO_DATA_CREATE_DATE' })
  noDataCreateDate: Date;

  @Column({ name: 'NO_DATA_SERVICE_USER_SID', select: false })
  noDataServiceUserSid: number;

  @OneToOne(returnsServiceUser)
  @JoinColumn({ name: 'NO_DATA_SERVICE_USER_SID' })
  noDataServiceUser: Promise<ServiceUser>;

  @Column({ name: 'TRACKING_LEVEL' })
  trackingLevel: string;

  @Column({ name: 'EXPECTED_DAY' })
  expectedDay: number;

  @Column({ name: 'WORKING_DAYS' })
  workingDays: string;

  @Column({ name: 'IS_IN_PERIOD_REPORTER' })
  isInPeriodReporter: number;

  @Column({ name: 'DELETED' })
  deleted: boolean;

  @OneToOne(returnsSubmissionSchedule)
  @JoinColumn({ name: 'SUBMISSION_SCHEDULE_SID' })
  submissionSchedule?: Promise<SubmissionSchedule>;

  @VirtualColumn({ query: statusSql })
  status?: string;

  @VirtualColumn({ query: reportedFlagSql })
  reportedFlag: boolean;

  @VirtualColumn( {query : fileIdsSql} )
  fileIds?: string;

  firstFileId?: string;

  firstFileName?: string;

  firstFileCreateDate?: Date;

  @VirtualColumn( {query : filesCountSql} )
  numberOfFiles?: number;

  @OneToMany(returnsDataFileSummaryInfo, dataFileSummaryInfoInverseSide)
  @JoinColumn({ name: 'SID', referencedColumnName: 'submissionPeriodSid' })
  filesData?: Promise<DataFileSummaryInfo>;

  @OneToOne(returnsSubmissionPeriodLineItemView)
  @JoinColumn({ name: 'SID', referencedColumnName: 'submissionPeriodSid' })
  submissionPeriodLineItemView?: Promise<SubmissionPeriodLineItemView>;

}
export const SubmissionDef = `
  type Query {
    submissionPeriods(
      offset: Float, 
      limit: Float,
      filters: SubmissionPeriodFilters,
      sort: SubmissionPeriodSort
    ): [SubmissionPeriod]
    submissionSchedules(
      offset: Float, 
      limit: Float,
      filters: SubmissionScheduleFilters, 
      sort: SubmissionScheduleSort
    ): [SubmissionSchedule]
    submissionScheduleNotifications(
      submissionScheduleSid: ID,
      offset: Float,
      limit: Float,
      filters: SubmissionScheduleNotificationFilters,
      sort: SubmissionScheduleNotificationSort
    ): [SubmissionScheduleNotification]
  }

  type Mutation {
    markNoData(data: [NoDataInput]): [MutationResponse] @auth(object: SubmissionPeriod)
  }

  type SubmissionPeriod {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    expectedDate: Date
    periodStartDate: Date
    periodEndDate: Date
    noData: Boolean
    noDataReason: String
    noDataCreateDate: Date
    onTimeOverride: Boolean
    expectedDay: String
    workingDays: String
    isInPeriodReporter: Float
    trackingLevel: String
    submissionSchedule: SubmissionSchedule
    status: String
    reportedFlag: Boolean
    numberOfFiles: Float
    filesData: DataFileSummaryInfo
    submissionPeriodLineItemView: SubmissionPeriodLineItemView
    noDataServiceUser: ServiceUser
  }

  type SubmissionPeriodLineItemView {
    salesLineItemCount: Float
    invLineItemCount: Float
    earliestFileSubmissionDate: Date
  }

  
  type DataFileSummaryInfo{
    numberOfPOSLines: Float
    numberOfInventoryLines: Float
  }
  
  type SubmissionSchedule {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    dataType: DataType    
    reportingPartner: Partner
    periodRule: String
    name: String
    startDate: Date
    endDate: Date
    expectedDay: String
    workingDays: String
    isInPeriodReporter: Boolean
    weekOfMonth: Float
    monthOfQuarter: Float
  }

  type DataType {
    sid: ID
    createDate: Date
    updateDate: Date
    type: String
  }

  type SubmissionScheduleNotification {
    sid: ID
    createDate: Date
    updateDate: Date
    customerSid: ID
    submissionScheduleSid: ID
    notificationType: NotificationType
    serviceUser: ServiceUser
  }

  enum NotificationType {
    PARSE_SUCCESS
    LATE
    PARSE_FAIL
    EXPECTED
  }

  input SubmissionPeriodFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    expectedDate: DateFilter
    periodStartDate: DateFilter
    periodEndDate: DateFilter
    submissionSchedule: SubmissionScheduleFilters
    status: StringFilter
    reportedFlag: BooleanFilter
    submissionPeriodLineItemView: SubmissionPeriodLineItemViewFilter
    numberOfFiles: NumberFilter
  }
  
  input SubmissionPeriodLineItemViewFilter {
    salesLineItemCount: NumberFilter
    invLineItemCount: NumberFilter
    earliestFileSubmissionDate: DateFilter
  }

  input SubmissionScheduleFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    reportingPartner: PartnerFilter
    name: StringFilter
    dataType: DataTypeFilter
    periodRule: StringFilter
    expectedDay: StringFilter
    workingDays: StringFilter
    startDate: DateFilter
    endDate: DateFilter
    isInPeriodReporter: BooleanFilter
    weekOfMonth: NumberFilter
    monthOfQuarter: NumberFilter
  }

  input DataTypeFilter {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    type: StringFilter
  }

  input SubmissionScheduleNotificationFilters {
    sid: IDFilter
    createDate: DateFilter
    updateDate: DateFilter
    customerSid: IDFilter
    submissionScheduleSid: IDFilter
    notificationType: StringFilter
    serviceUser: ServiceUserFilters
  }

  input SubmissionPeriodSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    expectedDate: SortOption
    periodStartDate: SortOption
    periodEndDate: SortOption
    submissionSchedule: SubmissionScheduleSort
    status: SortOption
    reportedFlag: SortOption
    submissionPeriodLineItemView: SubmissionPeriodLineItemViewSort
    numberOfFiles: SortOption
  }
  
  input SubmissionPeriodLineItemViewSort {
    salesLineItemCount: SortOption
    invLineItemCount: SortOption
    earliestFileSubmissionDate: SortOption
  }

  input SubmissionScheduleSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    customerSid: SortOption
    dataType: DataTypeSort
    reportingPartner: PartnerSort
    periodRule: SortOption
    name: SortOption
    startDate: SortOption
    endDate: SortOption
    expectedDay: SortOption
    workingDays: SortOption
    isInPeriodReporter: SortOption
    weekOfMonth: SortOption
    monthOfQuarter: SortOption
  }

  input DataTypeSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    type: SortOption
  }

  input SubmissionScheduleNotificationSort {
    sid: SortOption
    createDate: SortOption
    updateDate: SortOption
    notificationType: SortOption
    serviceUser: ServiceUserSort
  }

  input NoDataInput {
    sid: ID!
    noDataReason: String
  }
`;
int lowestCommonAncestor(TreeNode<int> *root, 
int x, int y)
{
	if(!root)
    return -1;
    if(root->data==x or root->data==y)
    return root->data;
    int lefti=lowestCommonAncestor(root->left,x,y);
    int righti=lowestCommonAncestor(root->right,x,y);
    if(lefti==-1)
    return righti;
    if(righti==-1)
    return lefti;
    return root->data;
}
  // Get husband information
  const getHusbandInformationByGuid = useCallback(async () => {
    const res = await trackPromise(api.getPersonalInformationByGuid(profileGuid));
    console.log('Profile information', res);
    setHusbandData(res?.data?.Output);
  }, [profileGuid, trackPromise, api, setHusbandData]);

  // Get spouse information
  const getSpouseInformationByGuid = useCallback(async () => {
    const res = await trackPromise(api.getPersonalInformationByGuid(spouseGuid));
    console.log('Spouse information', res);
    setSpouseData(res?.data?.Output);
  }, [spouseGuid, trackPromise, api, setSpouseData]);

  // Revert back to previous values after testing
  React.useEffect(() => {
    // if (spouseGuid && profileGuid) {
    if (profileGuid) getHusbandInformationByGuid();
    if (spouseGuid) getSpouseInformationByGuid();
    // }
  }, [profileGuid, spouseGuid]);
#include <bits/stdc++.h> 
vector<vector<string>>
 getGroupedAnagrams(vector<string> &input, int n)
{
    unordered_map<string,vector<string>>mp;
    vector<vector<string>>ans;
    for(int i=0 ; i<n ; i++)
    {
       string str=input[i];
       string s=str;
       sort(s.begin(),s.end());
       mp[s].push_back(str);
    }
    for(auto it:mp)
    {
        ans.push_back(it.second);
    }
    return ans;
}
ALTER TABLE your_table_name
ADD COLUMN new_column_name INT;
star

Wed Dec 20 2023 09:53:20 GMT+0000 (Coordinated Universal Time)

@alfred555 #react.js

star

Wed Dec 20 2023 08:49:02 GMT+0000 (Coordinated Universal Time) https://products.aspose.com/slides/php-java/conversion/ppt-to-pdf/

@zaryabmalik

star

Wed Dec 20 2023 07:24:43 GMT+0000 (Coordinated Universal Time) https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name/theme-color

@zaryabmalik

star

Wed Dec 20 2023 05:22:06 GMT+0000 (Coordinated Universal Time)

@dsce

star

Wed Dec 20 2023 03:10:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/77597251/best-approach-to-handle-dynamic-ui-based-on-regions-in-react-native

@rihafhusen

star

Wed Dec 20 2023 03:06:06 GMT+0000 (Coordinated Universal Time)

@rihafhusen

star

Tue Dec 19 2023 22:59:30 GMT+0000 (Coordinated Universal Time)

@wheedo

star

Tue Dec 19 2023 19:52:07 GMT+0000 (Coordinated Universal Time)

@abdul_rehman #c

star

Tue Dec 19 2023 17:51:46 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/snippets

@spekz369

star

Tue Dec 19 2023 17:50:36 GMT+0000 (Coordinated Universal Time)

@s7g7h ##excel

star

Tue Dec 19 2023 16:56:59 GMT+0000 (Coordinated Universal Time)

@gawlow

star

Tue Dec 19 2023 15:40:13 GMT+0000 (Coordinated Universal Time)

@sid_balar

star

Tue Dec 19 2023 14:02:10 GMT+0000 (Coordinated Universal Time)

@manishsah

star

Tue Dec 19 2023 13:05:26 GMT+0000 (Coordinated Universal Time)

@deba

star

Tue Dec 19 2023 12:08:26 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:07:51 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:07:30 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:07:06 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:06:42 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:06:06 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:05:23 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:04:47 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 12:04:20 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Tue Dec 19 2023 11:49:55 GMT+0000 (Coordinated Universal Time) https://share.bito.ai/static/share?aid=370c4051-69fe-4987-84c0-5fe4dbb7cddb

@codeing #dotenv #css

star

Tue Dec 19 2023 11:08:01 GMT+0000 (Coordinated Universal Time)

@mdfaizi

star

Tue Dec 19 2023 10:42:21 GMT+0000 (Coordinated Universal Time) https://www.anchorgroup.tech/netsuite-advanced-pdf-source-code-mode

@mdfaizi

star

Tue Dec 19 2023 10:40:33 GMT+0000 (Coordinated Universal Time) https://github.com/Mosquid/react-form-wp-cf7/tree/master

@rstringa

star

Tue Dec 19 2023 10:36:08 GMT+0000 (Coordinated Universal Time) https://css-tricks.com/headless-form-submission-with-the-wordpress-rest-api/

@rstringa #contactform7 #api #headless

star

Tue Dec 19 2023 07:11:28 GMT+0000 (Coordinated Universal Time)

@Utsav

star

Tue Dec 19 2023 06:57:59 GMT+0000 (Coordinated Universal Time)

@deba

star

Tue Dec 19 2023 05:29:57 GMT+0000 (Coordinated Universal Time) https://xtemos.com/forums/topic/add-year-in-post-date/

@deveseospace #php

star

Tue Dec 19 2023 04:45:44 GMT+0000 (Coordinated Universal Time)

@alfred555 #react.js

star

Mon Dec 18 2023 16:43:47 GMT+0000 (Coordinated Universal Time)

@deba

star

Mon Dec 18 2023 14:17:08 GMT+0000 (Coordinated Universal Time) https://github.com/openai/whisper/discussions/categories/show-and-tell?page

@jianglin998

star

Mon Dec 18 2023 14:07:37 GMT+0000 (Coordinated Universal Time) https://github.com/wikieden/Awesome-ChatGPT-Prompts-CN

@jianglin998

star

Mon Dec 18 2023 12:55:08 GMT+0000 (Coordinated Universal Time) https://maticz.com/apps-for-couples

@Floralucy #appsforcouples #coupleapps #bestappforcouples

star

Mon Dec 18 2023 09:07:37 GMT+0000 (Coordinated Universal Time) https://theonetechnologies.com/blog/post/how-to-integrate-restlet-api-of-netsuite-in-postman

@mdfaizi

star

Mon Dec 18 2023 08:32:38 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/jquery/jquery_animate.asp

@Sifat_H #animation #jqueryanimation #slidinganimation

star

Mon Dec 18 2023 08:10:50 GMT+0000 (Coordinated Universal Time) https://ceanatech.com/2019/07/02/using-postman-to-test-your-first-netsuite-restlet/

@mdfaizi

star

Mon Dec 18 2023 07:06:44 GMT+0000 (Coordinated Universal Time)

@chiragwebelight #reactj

star

Mon Dec 18 2023 06:33:06 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/

@dappfortglobal #swift #javascript #kotlin #mysql

star

Mon Dec 18 2023 05:37:02 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Mon Dec 18 2023 05:36:44 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Mon Dec 18 2023 05:36:22 GMT+0000 (Coordinated Universal Time)

@thanuj #sql

star

Mon Dec 18 2023 05:27:43 GMT+0000 (Coordinated Universal Time)

@nistha_jnn #c++

star

Mon Dec 18 2023 05:06:53 GMT+0000 (Coordinated Universal Time) https://www.codingninjas.com/studio/problems/group-anagrams_800285?utm_source=youtube&utm_medium=affiliate&utm_campaign=parikh_youtube&leftPanelTabValue=PROBLEM

@nistha_jnn #c++

star

Mon Dec 18 2023 04:27:52 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/

@Sifat_H #changecolumn #toadchangecolumn #oraclechangecolumn #toad #oracle #sql #sqlchange

star

Mon Dec 18 2023 04:25:51 GMT+0000 (Coordinated Universal Time)

@Sifat_H #addcolumn #sqladdcolumn #sql #add #oracle #toad

star

Mon Dec 18 2023 04:06:41 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/

@Sifat_H #addcolumn #sqladdcolumn #sql #add #addcolumn

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension