import moment from 'moment';
import React from 'react';
import { getKPIFields } from '../controller/functions';
import { db } from './constants';
import { AppTables } from './tableConstants';


export function Q_GetAvailabityDefaultData(storeData, isCompetitorClause) {
  console.log('Q_GetAvailabityDefaultData', isCompetitorClause)
  let { StoreId, ChainId, StoreTypeId, StateId, StoreClassId, StoreCategoryId } = storeData;
  let join = ` INNER JOIN Product_Master p on c.CategoryId=p.CategoryId  `;
  let join2 = ` INNER JOIN Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId`;
  // let q=` SELECT DISTINCT c.CategoryId,c.CategoryName,'' as MSL from Master_Category c ${join} ${join2} Where mp.StoreId ='${StoreId}' and p.IsCompetitor='0' order by p.CategorySequence`;
  let q = ` SELECT DISTINCT c.CategoryId,c.CategoryName,'' as MSL from Master_Category c ${join} ${join2} Where mp.StoreId ='${StoreId}' and ${isCompetitorClause}  order by p.CategorySequence`;
  return q;
}

export function Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, TBName) {
  let { StoreId, ChainId, StoreTypeId, StateId, StoreClassId, StoreCategoryId } = storeData;

  let COMPStockAllow_Index = AllKPIFields.findIndex(i => i.KPIFieldName == 'COMPStockAllow' && i.ScreenName == ScreenName);
  let COMPStockAllow_Obj = COMPStockAllow_Index >= 0 ? AllKPIFields[COMPStockAllow_Index] : {};
  let isCOMPStockAllow = COMPStockAllow_Index >= 0 ? COMPStockAllow_Obj['KPIFieldEnable'] : false;

  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let where = ` Where 1=1 ${(isCOMPStockAllow == true ? '' : ` and p.IsCompetitor='0' `)} ${condition} `;
  let stock_join = ` LEFT OUTER JOIN ${TBName} as s on p.ProductId=s.PRODUCT_ID and s.STORE_ID='${StoreId}' and s.VISIT_DATE='${d2}' `;
  let join2 = `  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
  let join = ` INNER JOIN Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId and mp.StoreId='${StoreId}'`;
  let q = ` SELECT DISTINCT p.ProductId,p.ProductName ${cols} from Product_Master p ${join} ${join2} ${stock_join} ${where} order by p.ProductSequence`;

  return q;
}


export function Q_getdefaltShareofSelf(storeData) {
  let { StoreId, ChainId, StoreTypeId, StateId } = storeData;
  let join = ` INNER JOIN Master_Category mc on mc.CategoryId = p.CategoryId  `;
  let join2 = ` INNER JOIN Mapping_ShareOfShelf m on p.SubCategoryId=m.SubCategoryId `;
  let q = `SELECT DISTINCT p.CategoryId,p.CategoryName from Product_Master p ${join} ${join2} Where m.StateId ='${StateId}' and m.ChainId ='${ChainId}'  and m.StoreTypeId ='${StoreTypeId}' order by p.CategorySequence`;
  return q;
}

export function Q_getpaidvisibility(storeData) {
  let { StoreId, ChainId, StoreTypeId } = storeData;
  let join = ` INNER JOIN Mapping_Visibility v on p.SubCategoryId=v.SubCategoryId `;
  let join2 = ` INNER join Master_Display md on md.DisplayId=v.DisplayId  `;
  let q = `SELECT DISTINCT p.SubCategoryName,p.SubCategoryId from Product_Master p  ${join} ${join2} Where v.StoreId='${StoreId}' and md.Paid='1' `;

  return q;
}

export function Q_getpromotionmappingList(storeData) {
  let { StoreId, ChainId, StoreTypeId, StateId } = storeData;
  let join = `  INNER JOIN Mapping_Promotion m  on p.SubCategoryId=m.SubCategoryId`;
  let q = `SELECT DISTINCT p.SubCategoryId,p.SubCategoryName from Product_Master p ${join} where m.StateId='${StateId}' and m.ChainId='${ChainId}' and m.StoreTypeId='${StoreTypeId}' `;
  return q;
}

export function Q_getSamplingData(storeData) {
  let { StoreId, ChainId, StoreTypeId, StateId } = storeData;
  let join = ` INNER JOIN Mapping_Sample m  on s.SampleId=m.SampleId`;
  let q = `SELECT DISTINCT s.Sample,s.SampleId from Master_Sample s ${join} where m.ChainId='${ChainId}' and  m.StateId='${StateId}' and m.StoreTypeId='${StoreTypeId}' `;
  return q;
}

export function Q_getSurveys(storeData) {
  let { StoreId, ChainId, StoreTypeId, StateId } = storeData;
  let join = ` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
  let q = `Select Distinct T.SurveyName ,T.SurveyId ,T.ShowCat from Master_SurveyQuestion T ${join} where M.StoreId='${StoreId}'`;
  return q;
}

export function Q_MenuList(storeData1, screen = '') {
  let { StoreId, ChannelId, RegionId, StoreTypeId, StoreCategoryId } = storeData1;

  let join = ` INNER join Mapping_Menu t2 on t1.MenuId=t2.MenuId`;
  let q = `SELECT DISTINCT t1.MenuId,t1.MenuName,t1.NormalIcon,t1.TickIcon,t1.GreyIcon,t1.MenuPath,t1.ScreenName,t1.UploadKeyName,t1.InnerScreenConfig from Menu_Master t1 ${join} where t2.ChannelId='${ChannelId}' and t2.RegionId='${RegionId}' and t2.StoreTypeId='${StoreTypeId}' and  t2.StoreCategoryId='${StoreCategoryId}'`;
  q += screen != '' ? ` and t1.ScreenName='${screen}' ` : '';
  q += ' Order by t1.MenuSequence ';


  return q;
  // and  t2.StoreCategoryId='${StoreCategoryId}'
}

export function Q_ALLScreenName() {
  let q = `SELECT DISTINCT t1.MenuId,t1.MenuName,t1.ScreenName from Menu_Master t1  Order by t1.MenuSequence `;
  return q;
}

export function Q_DBMenuList(storeData1, screen = '') {
  let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData1;

  let join = ` INNER join Mapping_MenuDistributorPoint t2 on t1.MenuId=t2.MenuId`;
  let q = `SELECT DISTINCT t1.MenuId,t1.MenuName,t1.NormalIcon,t1.TickIcon,t1.GreyIcon,t1.MenuPath,t1.ScreenName from Menu_Master t1 ${join}`;
  q += screen != '' ? ` where t1.ScreenName='${screen}' ` : '';
  q += ' Order by t1.MenuSequence ';
  return q;
}

export async function Q_getMyStoresList(isAdhoc = false, isBeat = false, isNonMerchan = false, isNonProgam = false, isStoreSearch = false) {
  let q = '', tb4 = 'JourneyPlan_RouteWise', tb1 = 'Mapping_JourneyPlan', tb2 = AppTables.CHECKIN_DATA, tb3 = 'Adhoc_JourneyPlan', tb5 = "NonMerchandising_JourneyPlan", tb6 = "NonProgram_JourneyPlan", tb7 = "StoreSearch_JourneyPlan";
  let join_tbl = isStoreSearch == true ? tb7 : (isBeat == true ? tb4 : (isAdhoc == true ? tb3 : (isNonMerchan == true ? tb5 : (isNonProgam == true ? tb6 : tb1))));
  let superQ_tblName = 'StoreCats';
  // let superQ2_tblName='StoreData';
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');


  let menusQ = ` (select Distinct  JP.*,MMAS.MenuId from ${join_tbl} JP
    inner join Mapping_Menu MM on JP.ChannelId=MM.ChannelId and JP.StoreTypeId=MM.StoreTypeId and JP.RegionId=MM.RegionId
    inner join Menu_Master MMAS on MM.MenuId=MMAS.MenuId
    where JP.VisitDate='${d2}'
    Order by JP.StoreId, MMAS.MenuId) as Menu `;


  let config_join = `Left Outer Join (Select Distinct ScreenName,KPIFieldName,KPIFieldEnable,KPIFieldDisplayName from Mapping_MenuConfiguration Where KPIFieldName='PartialSaveAllow') c on c.ScreenName=MM.ScreenName `;

  let menuQ2 = `(select Distinct  JP.*,MM.MenuId,c.KPIFieldEnable as PSAllow from ${join_tbl} JP
    Left outer join 
	  (select * from Mapping_Menu MN inner join Menu_Master MMAS on MN.MenuId=MMAS.MenuId) MM on JP.ChannelId=MM.ChannelId and JP.StoreTypeId=MM.StoreTypeId and JP.RegionId=MM.RegionId and JP.StoreCategoryId=MM.StoreCategoryId
    ${config_join}
    where JP.VisitDate='${d2}'
    Order by JP.StoreId, MM.MenuId) as Menu `;


  // and JP.StoreCategoryId=MM.StoreCategoryId
  // inner join Product_Master PM on MPA.ProductId=PM.ProductId 
  // let stored_Select=`${superQ_tblName}.StoreId as StoreId,${superQ_tblName}.StoreCode as StoreCode,${superQ_tblName}.MID as MID,${superQ_tblName}.ChannelId as ChannelId,${superQ_tblName}.StoreId as StoreId,${superQ_tblName}.EmpId as EmpId,${superQ_tblName}.VisitDate as VisitDate,${superQ_tblName}.ChainId as ChainId,${superQ_tblName}.ChainName as ChainName,${superQ_tblName}.StoreName as StoreName,${superQ_tblName}.Address as Address,${superQ_tblName}.Location as Location,${superQ_tblName}.Landmark as Landmark,${superQ_tblName}.CityId as CityId,${superQ_tblName}.CityName as CityName,${superQ_tblName}.StateId as StateId,${superQ_tblName}.StateName as StateName,${superQ_tblName}.RegionId as RegionId,${superQ_tblName}.StoreTypeId as StoreTypeId,${superQ_tblName}.StoreType as StoreType,${superQ_tblName}.Pincode as Pincode,${superQ_tblName}.Latitude as Latitude,${superQ_tblName}.Longitude as Longitude,${superQ_tblName}.Phone as Phone,${superQ_tblName}.Mobile as Mobile,${superQ_tblName}.ContactPerson as ContactPerson,${superQ_tblName}.Email as Email,${superQ_tblName}.UploadStatus as UploadStatus,${superQ_tblName}.GeoTag as GeoTag,${superQ_tblName}.GeoFenceRadius as GeoFenceRadius,${superQ_tblName}.ExpiryStock as ExpiryStock,${superQ_tblName}.InTime as InTime,${superQ_tblName}.OutTime as OutTime,${superQ_tblName}.CameraAllow as CameraAllow,${superQ_tblName}.AddVisiAllow as AddVisiAllow`;
  let stored_Select = `MDist.DistributorId,MDist.DistributorName,${superQ_tblName}.StoreId,${superQ_tblName}.StoreCode,${superQ_tblName}.MID,${superQ_tblName}.ChannelId,${superQ_tblName}.StoreId,${superQ_tblName}.EmpId,${superQ_tblName}.VisitDate,${superQ_tblName}.ChainId,${superQ_tblName}.ChainName,${superQ_tblName}.StoreName,${superQ_tblName}.Address,${superQ_tblName}.Location,${superQ_tblName}.Landmark,${superQ_tblName}.CityId,${superQ_tblName}.CityName,${superQ_tblName}.StateId,${superQ_tblName}.StateName,${superQ_tblName}.RegionId,${superQ_tblName}.StoreTypeId,${superQ_tblName}.StoreType,${superQ_tblName}.Pincode,${superQ_tblName}.Latitude,${superQ_tblName}.Longitude,${superQ_tblName}.Phone,${superQ_tblName}.Mobile,${superQ_tblName}.ContactPerson,${superQ_tblName}.Email,${superQ_tblName}.UploadStatus,${superQ_tblName}.GeoTag,${superQ_tblName}.GeoFenceRadius,${superQ_tblName}.ExpiryStock,${superQ_tblName}.InTime,${superQ_tblName}.OutTime,${superQ_tblName}.CameraAllow,${superQ_tblName}.AddVisiAllow,${superQ_tblName}.LastVisitDate,${superQ_tblName}.Score,${superQ_tblName}.MinTimeTaken,${superQ_tblName}.MTDMerchandised,${superQ_tblName}.StoreCategoryId,${superQ_tblName}.StoreCategory,${superQ_tblName}.StoreClassId,${superQ_tblName}.StoreClass,${superQ_tblName}.TaxType,${superQ_tblName}.GSTno,${superQ_tblName}.GSTImage,${superQ_tblName}.Deviation,${superQ_tblName}.StoreBgColor`;
  let checkinSelect = `CheckInData.CHECKIN_TIME as CheckInTime,CheckInData.CHECKOUT_TIME as CheckOutTime,CheckInData.JCP_TYPE`;
  let Distributor_join = ` Left Outer Join Master_Distributor MDist on ${superQ_tblName}.DistributorId=MDist.DistributorId   `;

  let AllKPIFields = await getKPIFields({}, true);
  let DataAvailable_QList = ``, KPIAvailable_QList = ``;
  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let mq = `SELECT DISTINCT t1.ScreenName,t1.MenuId from Menu_Master t1 INNER join Mapping_Menu t2 on t1.MenuId=t2.MenuId `;

      await txn.executeSql(mq, [], async function (txn2, txnres) {
        if (txnres.rows.length > 0) {
          for (let i = 0; i < txnres.rows.length; i++) {
            let data = txnres.rows.item(i);
            let avlblQ = getAvailblQuery(data, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch, AllKPIFields);
            let isDoneQ = getQuery(data, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch);
            console.log("testingIsDone", isDoneQ, data)

            KPIAvailable_QList += KPIAvailable_QList != '' && avlblQ != '' ? ' UNION ' : ' ';
            DataAvailable_QList += DataAvailable_QList != '' && isDoneQ != '' ? ' UNION ' : ' ';
            KPIAvailable_QList += ' ' + avlblQ + ' ';
            DataAvailable_QList += ' ' + isDoneQ + ' ';

            if (i == txnres.rows.length - 1) {

              let KPIAvlblJoin = `LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.StoreId=AVLSTK.StoreId and Menu.MenuId=AVLSTK.MenuId `;
              let DataAvailableJoin = ` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.StoreId=dataavl.StoreId and Menu.MenuId=dataavl.MenuId  `;
              let StoreData_join = ` Left Outer Join ( Select ${tb2}.* From ${tb2} Where ${tb2}.JCP_TYPE='${join_tbl}' and ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.StoreId=CheckInData.STORE_ID    `;//and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L')

              q = `Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount,
            dataavl.DataRowCount as DataDoneCount,
            AVLSTK.DataRowAvlblCount,
            Menu.PSAllow,
            CASE WHEN (KPIAVBL = 1 AND Menu.PSAllow IS NOT NULL AND (Menu.PSAllow = 'true' OR Menu.PSAllow = 1) AND dataavl.DataRowCount >= AVLSTK.DataRowAvlblCount)
            THEN 1 WHEN (KPIAVBL = 1 AND (Menu.PSAllow IS NULL OR (Menu.PSAllow <> 'true' AND Menu.PSAllow <> 1))
            AND dataavl.DataRowCount > 0) THEN 1 ELSE 0 END AS IsKPIDone 
            from ${menuQ2} ${KPIAvlblJoin} ${DataAvailableJoin}  `;
              console.log("localquery", q)
              // ######## Old PS_MenuDoneCount done logic end ########
              let superQ = `select ${checkinSelect},${stored_Select},count((CASE WHEN (${superQ_tblName}.KPIAVBL==1) THEN 1 ELSE null END)) as MenuCount,
            count(StoreCats.KPIAVBL) as MenuCountWithNonAvlbl,
            count((CASE WHEN (${superQ_tblName}.KPIAVBL==1 and ${superQ_tblName}.DataRowCount>0) THEN 1 ELSE null END )) as MenuDoneCount,
            count (CASE WHEN StoreCats.IsKPIDone==1 THEN 1 ELSE NULL END) as PS_MenuDoneCount
          
            from (${q}) as ${superQ_tblName} ${StoreData_join} ${Distributor_join}  GROUP BY ${superQ_tblName}.StoreId`;
              resolve(
                superQ +
                " ORDER BY CASE StoreCats.UploadStatus " +
                "WHEN 'I' THEN 1 " +
                "WHEN 'P' THEN 2 " +
                "WHEN 'D' THEN 3 " +
                "WHEN 'U' THEN 4 " +
                "WHEN 'L' THEN 5 " +
                "WHEN 'N' THEN 6 " +
                "WHEN '' THEN 7 " +
                "ELSE 8 END"
              );
            }
          }
        }
        else {
          let StoreData_join = ` Left Outer Join ( Select ${tb2}.* From ${tb2} Where ${tb2}.JCP_TYPE='${join_tbl}' and ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.StoreId=CheckInData.STORE_ID `;
          q = `Select Menu.*, 0 as KPIAVBL, 0 as DataRowCount from ${menuQ2}   `;
          let superQ = `select ${checkinSelect},${stored_Select},0 as MenuCount,0 as MenuCountWithNonAvlbl,0 as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join} ${Distributor_join} GROUP BY ${superQ_tblName}.StoreId`;
          resolve(
            superQ +
            " ORDER BY CASE StoreCats.UploadStatus " +
            "WHEN 'I' THEN 1 " +
            "WHEN 'P' THEN 2 " +
            "WHEN 'D' THEN 3 " +
            "WHEN 'U' THEN 4 " +
            "WHEN 'L' THEN 5 " +
            "WHEN 'N' THEN 6 " +
            "WHEN '' THEN 7 " +
            "ELSE 8 END"
          );
        }
      }, function (txnE, txnerr) { console.log('txnerr in store q:', txnerr); resolve(''); },);

    });
  }).catch((err) => {
    console.log('error in query:', err);
    return '';
  })

}

export async function Q_getMyDistributorList(props) {
  let q = '', tb2 = AppTables.DISTRIBUTOR_CHECKIN;
  let join_tbl = 'Master_Distributor';
  let superQ_tblName = 'StoreCats';
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  // Mapping_MenuDistributorPoint
  let menusQ = ` (select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    cross join (select MMAS.* from Menu_Master MMAS Inner Join Mapping_MenuDistributorPoint MMap on MenuId on MMap.MenuId=MMAS.MenuId) as MM
    Order by JP.DistributorId, MM.MenuId) as Menu `;


  let menuQ2 = `(select Distinct  JP.*,MM.MenuId from ${join_tbl} JP
    Left outer join 
	  (select Distinct  JP.DistributorId,MM_Inner.* from ${join_tbl} JP cross join (select MMAS.* from Menu_Master MMAS Inner Join Mapping_MenuDistributorPoint MMap on MMap.MenuId=MMAS.MenuId) as MM_Inner) 
    MM on JP.DistributorId=MM.DistributorId
    Order by JP.DistributorId, MM.MenuId) as Menu `;

  let stored_Select = `${superQ_tblName}.DMID as MID,${superQ_tblName}.EmpId,${superQ_tblName}.DistributorId as StoreId,${superQ_tblName}.DistributorName as StoreName,${superQ_tblName}.DistributorCode as StoreCode,${superQ_tblName}.Latitude,${superQ_tblName}.Longitude,${superQ_tblName}.InTime,${superQ_tblName}.OutTime,${superQ_tblName}.UploadStatus,${superQ_tblName}.GeoTag`;
  let checkinSelect = `CheckInData.CHECKIN_TIME as CheckInTime,CheckInData.CHECKOUT_TIME as CheckOutTime`;

  let DataAvailable_QList = ``, KPIAvailable_QList = ``;
  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let mq = `SELECT DISTINCT t1.ScreenName,t1.MenuId from Menu_Master t1 INNER join Mapping_MenuDistributorPoint t2 on t1.MenuId=t2.MenuId`;

      await txn.executeSql(mq, [], async function (txn2, txnres) {
        if (txnres.rows.length > 0) {
          for (let i = 0; i < txnres.rows.length; i++) {
            let data = txnres.rows.item(i);
            let avlblQ = get_DBAvailblQuery(props, data, join_tbl);
            let isDoneQ = get_DBQuery(data, join_tbl);

            KPIAvailable_QList += KPIAvailable_QList != '' && avlblQ != '' ? ' UNION ' : ' ';
            DataAvailable_QList += DataAvailable_QList != '' && isDoneQ != '' ? ' UNION ' : ' ';
            KPIAvailable_QList += ' ' + avlblQ + ' ';
            DataAvailable_QList += ' ' + isDoneQ + ' ';

            if (i == txnres.rows.length - 1) {

              let KPIAvlblJoin = `LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.DistributorId=AVLSTK.DistributorId and Menu.MenuId=AVLSTK.MenuId `;
              let DataAvailableJoin = ` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.DistributorId=dataavl.DistributorId and Menu.MenuId=dataavl.MenuId  `;

              let StoreData_join = ` Left Outer Join ( Select ${tb2}.* From ${tb2} Where ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID   `;//and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L') 
              // var SD_orderby=` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;


              q = `Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount from ${menuQ2} ${KPIAvlblJoin} ${DataAvailableJoin}  `;
              let superQ = `select ${checkinSelect},${stored_Select},count((CASE WHEN (${superQ_tblName}.KPIAVBL==1) THEN 1 ELSE null END)) as MenuCount,count((CASE WHEN (${superQ_tblName}.KPIAVBL==1 and ${superQ_tblName}.DataRowCount==1) THEN 1 ELSE null END )) as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
              resolve(
                superQ +
                " ORDER BY CASE StoreCats.UploadStatus " +
                "WHEN 'I' THEN 1 " +
                "WHEN 'P' THEN 2 " +
                "WHEN 'D' THEN 3 " +
                "WHEN 'U' THEN 4 " +
                "WHEN 'L' THEN 5 " +
                "WHEN 'N' THEN 6 " +
                "WHEN '' THEN 7 " +
                "ELSE 8 END"
              );
            }

          }
        }
        else {

          let StoreData_join = ` Left Outer Join ( Select ${tb2}.* From ${tb2} Where  ${tb2}.VISIT_DATE='${d2}') as CheckInData on ${superQ_tblName}.DistributorId=CheckInData.DISTRIBUTOR_ID   `;//and ${superQ_tblName}.UploadStatus in ('I','C','D','U','L') 
          q = `Select Menu.*, 0 as KPIAVBL, 0 as DataRowCount from ${menuQ2}   `;
          let superQ = `select ${checkinSelect},${stored_Select},0 as MenuCount,0 as MenuDoneCount from (${q}) as ${superQ_tblName} ${StoreData_join}  GROUP BY ${superQ_tblName}.DistributorId`;
          resolve(
            superQ +
            " ORDER BY CASE StoreCats.UploadStatus " +
            "WHEN 'I' THEN 1 " +
            "WHEN 'P' THEN 2 " +
            "WHEN 'D' THEN 3 " +
            "WHEN 'U' THEN 4 " +
            "WHEN 'L' THEN 5 " +
            "WHEN 'N' THEN 6 " +
            "WHEN '' THEN 7 " +
            "ELSE 8 END"
          );
        }
      }, function (txnE, txnerr) { console.log('txnerr in store q:', txnerr); resolve(''); },);

    });
  }).catch((err) => {
    console.log('error in query:', err);
    return '';
  })

}

export async function Q_getMyStoresMenuList(isAdhoc = false, storeData, cat, isBeat = false, isNonMerchan = false, isNonProgam = false, isStoreSearch = false, props) {
  // console.log('Q_getMyStoresCatList:',storeData)
  let q = '', tb4 = 'JourneyPlan_RouteWise', tb1 = 'Mapping_JourneyPlan', tb2 = AppTables.CHECKIN_DATA, tb3 = 'Adhoc_JourneyPlan', tb5 = "NonMerchandising_JourneyPlan", tb6 = 'NonProgram_JourneyPlan', tb7 = 'StoreSearch_JourneyPlan';
  //let join_tbl=isBeat==true?tb4:(isAdhoc==true?tb3:(isNonMerchan==true?tb5:isNonProgam==true?tb6:tb1));
  let join_tbl = isStoreSearch == true ? tb7 : (isBeat == true ? tb4 : (isAdhoc == true ? tb3 : (isNonMerchan == true ? tb5 : (isNonProgam == true ? tb6 : tb1))));
  let superQ_tblName = 'StoreCats';
  // let superQ2_tblName='StoreData';
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let menusQ = ` (select Distinct  JP.StoreId,MMAS.MenuId,MMAS.MenuName,MMAS.NormalIcon,MMAS.TickIcon,MMAS.GreyIcon,MMAS.MenuPath,MMAS.ScreenName,MMAS.MenuSequence,MMAS.InnerScreenConfig,c.KPIFieldEnable as PSAllow,c.KPIFieldDisplayName as PSTableName from ${join_tbl} JP
    inner join Mapping_Menu MM on JP.ChannelId=MM.ChannelId and JP.StoreTypeId=MM.StoreTypeId and JP.RegionId=MM.RegionId and JP.StoreCategoryId=MM.StoreCategoryId
    inner join Menu_Master MMAS on MM.MenuId=MMAS.MenuId
    Left Outer Join (Select Distinct ScreenName,KPIFieldName,KPIFieldEnable,KPIFieldDisplayName from Mapping_MenuConfiguration Where KPIFieldName='PartialSaveAllow' and (KPIFieldEnable='true' or KPIFieldEnable=1 or KPIFieldEnable='1') ) c on c.ScreenName=MMAS.ScreenName 
    where JP.VisitDate='${d2}'
    Order by JP.StoreId, MMAS.MenuId) as Menu `;
  console.log("menuQ-->", menusQ)

  let DataAvailable_QList = ``, KPIAvailable_QList = ``;
  let AllKPIFields = await getKPIFields({}, true);
  return await new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let config_join = `Left Outer Join (Select Distinct ScreenName,KPIFieldName,KPIFieldEnable,KPIFieldDisplayName from Mapping_MenuConfiguration Where KPIFieldName='PartialSaveAllow') c on c.ScreenName=t1.ScreenName `;
      let mq = `SELECT DISTINCT t1.ScreenName,t1.MenuId,t1.MenuName,c.KPIFieldEnable as PSAllow,c.KPIFieldDisplayName as PSTableName from Menu_Master t1 INNER join Mapping_Menu t2 on t1.MenuId=t2.MenuId ${config_join}`;
      await txn.executeSql(mq, [], async function (txn2, txnres) {
        // console.log("menuslist check-----",txnres.rows.length)
        if (txnres.rows.length > 0) {
          for (let i = 0; i < txnres.rows.length; i++) {
            let data = txnres.rows.item(i);

            // console.log('data in menu query: KPIFieldEnable:',data.ScreenName,data.KPIFieldEnable,data.KPIFieldDisplayName)
            let avlblQ = getAvailblQuery(data, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch, AllKPIFields);
            let isDoneQ = getQuery(data, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch);

            KPIAvailable_QList += KPIAvailable_QList != '' && avlblQ != '' ? ' UNION ' : ' ';
            DataAvailable_QList += DataAvailable_QList != '' && isDoneQ != '' ? ' UNION ' : ' ';
            KPIAvailable_QList += ' ' + avlblQ + ' ';
            DataAvailable_QList += ' ' + isDoneQ + ' ';


            if (i == txnres.rows.length - 1) {
              console.log("rows.length", i, txnres.rows.length)
              let KPIAvlblJoin = `LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.StoreId=AVLSTK.StoreId and Menu.MenuId=AVLSTK.MenuId`;
              let DataAvailableJoin = ` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.StoreId=dataavl.StoreId and Menu.MenuId=dataavl.MenuId `;
              q = `Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount,dataavl.DataRowCount as DataDoneCount,AVLSTK.DataRowAvlblCount from ${menusQ} ${KPIAvlblJoin} ${DataAvailableJoin} Where Menu.StoreId='${storeData.StoreId}' order by Menu.MenuSequence `;
              resolve(q);
            }

          }
        }
        else {
          resolve('');
        }
      }, function (txnE, txnerr) { console.log(txnerr); resolve(''); },);

    });
  }).then((val) => {
    // console.log('myval',val);
    return val;
  }).catch((err) => {
    console.log('error in query:', err);
    return '';
  })


}

export async function Q_getMyDBMenuList(storeData, props) {
  console.log('Q_getMyDBMenuList:', storeData)
  let q = '', tb2 = AppTables.CHECKIN_DATA;
  let join_tbl = 'Master_Distributor';
  let superQ_tblName = 'StoreCats';
  // let superQ2_tblName='StoreData';
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let menusQ = `(select Distinct JP.DistributorId,MM_Inner.MenuId,MM_Inner.MenuName,MM_Inner.NormalIcon,MM_Inner.TickIcon,MM_Inner.GreyIcon,MM_Inner.MenuPath,MM_Inner.ScreenName,MM_Inner.MenuSequence from ${join_tbl} JP 
    cross join 
    (select MMAS.* from Menu_Master MMAS Inner Join Mapping_MenuDistributorPoint MMap on MMap.MenuId=MMAS.MenuId) as MM_Inner
    Order by JP.DistributorId, MM_Inner.MenuId) as Menu `;


  let DataAvailable_QList = ``, KPIAvailable_QList = ``;
  return await new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let mq = `SELECT DISTINCT t1.ScreenName,t1.MenuId from Menu_Master t1 INNER join Mapping_MenuDistributorPoint t2 on t1.MenuId=t2.MenuId`;

      await txn.executeSql(mq, [], async function (txn2, txnres) {

        if (txnres.rows.length > 0) {
          for (let i = 0; i < txnres.rows.length; i++) {
            let data = txnres.rows.item(i);

            let avlblQ = get_DBAvailblQuery(props, data, join_tbl);
            let isDoneQ = get_DBQuery(data, join_tbl);

            KPIAvailable_QList += KPIAvailable_QList != '' && avlblQ != '' ? ' UNION ' : ' ';
            DataAvailable_QList += DataAvailable_QList != '' && isDoneQ != '' ? ' UNION ' : ' ';
            KPIAvailable_QList += ' ' + avlblQ + ' ';
            DataAvailable_QList += ' ' + isDoneQ + ' ';


            if (i == txnres.rows.length - 1) {
              let KPIAvlblJoin = `LEFT Outer Join ( ${KPIAvailable_QList} ) as AVLSTK ON Menu.DistributorId=AVLSTK.DistributorId and Menu.MenuId=AVLSTK.MenuId`;
              let DataAvailableJoin = ` Left Outer Join ( ${DataAvailable_QList} ) dataavl ON Menu.DistributorId=dataavl.DistributorId and Menu.MenuId=dataavl.MenuId `;
              q = `Select Menu.*,  IFNULL(KPIAVBL, 0) as KPIAVBL, CASE WHEN IFNULL(dataavl.DataRowCount, 0)>0 THEN 1 ELSE 0 END  as DataRowCount from ${menusQ} ${KPIAvlblJoin} ${DataAvailableJoin} Where Menu.DistributorId='${storeData.StoreId}' order by Menu.MenuSequence `;
              resolve(q);
            }

          }
        }
        else {
          resolve('');
        }
      }, function (txnE, txnerr) { console.log(txnerr); resolve(''); },);

    });
  }).then((val) => {
    // console.log('myval',val);
    return val;
  }).catch((err) => {
    console.log('error in query:', err);
    return '';
  })


}


export async function checkFilledSurveys(ScreenName, txnres2, storeData) {
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');
  let { StoreId } = storeData;
  let isSurveyDone = true;

  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      if (txnres2.rows.length > 0) {
        for (var i = 0; i < txnres2.rows.length; i++) {
          let data = txnres2.rows.item(i);
          let c_index = i;
          let { SurveyId, ShowCat } = data;
          let isshowcat = (ShowCat == 1 || ShowCat == 'true' || ShowCat == true);
          let isDone = await checkIf_surveyDone(storeData, SurveyId, isshowcat);
          if (!isDone) {
            isSurveyDone = false;
            resolve(isSurveyDone);
            break;
          }
          else if (i == txnres2.rows.length - 1) {
            resolve(isSurveyDone)
          }
        }
      }
      else {
        resolve(true);
      }
    });
  }).then(val => {
    return val;
  }).catch(err => {
    console.log(err);
    return false;
  });


}


//################### get KPI availbale queries start ############################

export function Q_getAvailbl_Stock(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let COMPStockAllow_Index = AllKPIFields?.findIndex(i => i.KPIFieldName == 'COMPStockAllow' && i.ScreenName == ScreenName);
  let COMPStockAllow_Obj = COMPStockAllow_Index >= 0 ? AllKPIFields[COMPStockAllow_Index] : {};
  let isCOMPStockAllow = COMPStockAllow_Index >= 0 ? COMPStockAllow_Obj['KPIFieldEnable'] : false;


  let q = `SELECT JP.StoreId , ${MenuId} as MenuID,CASE WHEN count(PM.ProductId)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(PM.ProductId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN Mapping_ProductAssortmentStorewise MP on JP.StoreId=MP.StoreId
  INNER JOIN Product_Master PM on PM.ProductId=MP.ProductId Where JP.VisitDate='${d2}'  ${(isCOMPStockAllow == true ? '' : ` and (PM.IsCompetitor='0' or PM.IsCompetitor = 0) `)}
  group by JP.StoreId`;


  return q;
}
export function Q_getAvailbl_KycOneApp(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let COMPStockAllow_Index = AllKPIFields?.findIndex(i => i.KPIFieldName == 'COMPStockAllow' && i.ScreenName == ScreenName);
  let COMPStockAllow_Obj = COMPStockAllow_Index >= 0 ? AllKPIFields[COMPStockAllow_Index] : {};
  let isCOMPStockAllow = COMPStockAllow_Index >= 0 ? COMPStockAllow_Obj['KPIFieldEnable'] : false;


  //   q = `
  //   SELECT JP.StoreId, ${MenuId} AS MenuID,
  //     CASE WHEN EXISTS (SELECT 1 FROM Mapping_KYCConfiguration) THEN 1 ELSE 0 END AS KPIAVBL,
  //     (SELECT COUNT(1) FROM Mapping_KYCConfiguration) AS DataRowAvlblCount
  //   FROM ${PJP_Table} JP
  //   WHERE JP.VisitDate = '${d2}'
  //   GROUP BY JP.StoreId
  // `;
  // return q;


  q = `
    SELECT JP.StoreId, ${MenuId} AS MenuID,
      CASE 
        WHEN EXISTS (SELECT 1 FROM Mapping_KYCConfiguration)
        AND NOT EXISTS (SELECT 1 FROM Mapping_KYCUploaded KYC_U WHERE KYC_U.StoreId = JP.StoreId)
        THEN 1 
        ELSE 0 
      END AS KPIAVBL,
      (SELECT COUNT(1) FROM Mapping_KYCConfiguration WHERE (IsMandatory = 'true' or IsMandatory=1)) AS DataRowAvlblCount
    FROM ${PJP_Table} JP
    WHERE JP.VisitDate = '${d2}'
    GROUP BY JP.StoreId
  `;
  return q;
}

export function Q_getAvailbl_ProgramOneApp(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ProgramDefinitionId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreProgram MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_ProgramDefinition W on W.ProgramDefinitionId=MW.ProgramDefinitionId and W.MenuId='${MenuId}'
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_TGBASEDONEAPP(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(MW.TargetId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreTargetBased MW on MW.StoreId=JP.StoreId and MW.MenuId='${MenuId}'
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_DynamicStorescore(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,1 as DataRowAvlblCount
  from ${PJP_Table} JP 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_Training(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,1 as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getMissedCall(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  CROSS JOIN (SELECT Topic FROM Master_DetailerContent) MS
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_Default(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // *****************************************
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,1 as KPIAVBL,1 as DataRowAvlblCount  
  from ${PJP_Table} JP 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_SOS(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let join=` INNER JOIN Master_Category mc on mc.CategoryId = p.CategoryId  `;
  // let join2=` INNER JOIN Mapping_ShareOfShelf m on p.SubCategoryId=m.SubCategoryId `;
  // let q=`SELECT DISTINCT p.CategoryId,p.CategoryName from Product_Master p ${join} ${join2} Where m.StateId ='${StateId}' and m.ChainId ='${ChainId}'  and m.StoreTypeId ='${StoreTypeId}' order by p.CategorySequence`;

  let q = `SELECT JP.StoreId , ${MenuId} as MenuID,CASE WHEN count(PM.ProductId)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(PM.ProductId),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_ShareOfShelf MP on JP.StateId=MP.StateId and JP.ChainId=MP.ChainId and JP.StoreTypeId=MP.StoreTypeId
  INNER JOIN Product_Master PM on PM.SubCategoryId=MP.SubCategoryId Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_Vis(menuItem, PJP_Table = '', type = 'Paid') {

  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let join=` INNER JOIN Mapping_Visibility v on p.SubCategoryId=v.SubCategoryId `;
  // let join2=` INNER join Master_Display md on md.DisplayId=v.DisplayId  `;
  // let q=`SELECT DISTINCT p.SubCategoryName,p.SubCategoryId from Product_Master p  ${join} ${join2} Where v.StoreId='${StoreId}' and md.Paid='1' `;
  let q = '';
  if (type == 'Paid') {
    q = `SELECT JP.StoreId , ${MenuId} as MenuID,CASE WHEN count(MD.DisplayId)>0 THEN 1 ELSE 0 END as KPIAVBL,1 as DataRowAvlblCount 
    from ${PJP_Table} JP 
    INNER JOIN Mapping_Visibility v on v.StoreId=JP.StoreId
    INNER JOIN Master_Display MD on MD.DisplayId=v.DisplayId and MD.Paid='1'
    Where JP.VisitDate='${d2}' 
    group by JP.StoreId`;
  }
  else {
    q = `SELECT DISTINCT JP.StoreId , ${MenuId} as MenuID,CASE WHEN count(MD.DisplayId)>0 THEN 1 ELSE 0 END as KPIAVBL , 1 as DataRowAvlblCount
    from ${PJP_Table} JP 
    CROSS JOIN (select * from Master_Display  WHERE 
    ${(type == 'Add' ? `Additional='1' or Additional=1 or Additional='true'` : '')}
    ${(type == 'Comp' ?
        ` Competitor='1' or Competitor='true' or Competitor=1
    `: '')}
    ) MD
    Where JP.VisitDate='${d2}' ${(type == 'Add' ? ` and JP.AddVisiAllow='Y'` : '')}
    group by JP.StoreId`;
  }

  return q;
}


export function Q_getAvailbl_ReturnStk(menuItem, PJP_Table = '') {

  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = '';

  q = `SELECT DISTINCT JP.StoreId , ${MenuId} as MenuID,CASE WHEN count(MD.ProductId)>0 THEN 1 ELSE 0 END as KPIAVBL , 1 as DataRowAvlblCount
    from ${PJP_Table} JP 
    CROSS JOIN (select * from Product_master
    )as MD
    Where JP.VisitDate='${d2}'
    group by JP.StoreId`;

  return q;
}


export function Q_getAvailbl_Promo(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(1),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_Promotion MP on JP.StateId=MP.StateId and JP.ChainId=MP.ChainId and JP.StoreTypeId=MP.StoreTypeId
  INNER JOIN (Select Distinct CategoryId, SubCategoryId from Product_Master) PMM on PMM.SubCategoryId=MP.SubCategoryId 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_CompPromo(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=` select distinct CompanyId,Company from Master_Competitor  `; 

  // let q=`SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL  
  // from ${PJP_Table} JP  
  // INNER JOIN Mapping_Promotion MP on JP.StateId=MP.StateId and JP.ChainId=MP.ChainId and JP.StoreTypeId=MP.StoreTypeId 
  // INNER JOIN (Select Distinct CategoryId, SubCategoryId from Master_Competitor) PMM on PMM.SubCategoryId=MP.SubCategoryId  
  // Where JP.VisitDate='${d2}' 
  // group by JP.StoreId`; 

  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL,1 as DataRowAvlblCount 
  from ${PJP_Table} JP  
  CROSS JOIN (select * from Master_Competitor) 
  Where JP.VisitDate='${d2}' 
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_Survey(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
  // let q=`Select Distinct T.SurveyName ,T.SurveyId ,T.ShowCat from Master_SurveyQuestion T ${join} where M.StoreId='${StoreId}'`;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(1),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_Survey MS on MS.StoreId=JP.StoreId
  INNER JOIN (Select Distinct SurveyId,MenuId from Master_SurveyQuestion) S on S.SurveyId=MS.SurveyId and S.MenuId='${MenuId}'
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_Sampling(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let join=` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
  // let q=`Select Distinct T.SurveyName ,T.SurveyId ,T.ShowCat from Master_SurveyQuestion T ${join} where M.StoreId='${StoreId}'`;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(S.SamplingDefinitionId),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreSampling MS on MS.StoreId=JP.StoreId
  INNER JOIN Master_SamplingDefinition S on S.SamplingDefinitionId=MS.SamplingDefinitionId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}

export function Q_getAvailbl_Feedback(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT DISTINCT FeedbackQuestionId FROM Master_FeedbackQuestion  `;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL,IFNULL(count(1),0) as DataRowAvlblCount  
  from ${PJP_Table} JP 
  INNER JOIN (SELECT DISTINCT FeedbackQuestionId,JP.StoreId FROM Master_FeedbackQuestion) MS on MS.StoreId=JP.StoreId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_Window(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT DISTINCT w.WindowId FROM Master_WindowDefinition w inner join Mapping_StoreWindow s on w.WindowDefinitionId=s.WindowDefinitionId where s.StoreId='${StoreId}'`;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(1),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId and W.MenuId='${MenuId}'
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_POSM(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=``SELECT DISTINCT w.POSMDefinitionId,w.PosmId FROM Master_POSMDefinition w inner join Mapping_StorePOSM s on s.POSMDefinitionId=w.POSMDefinitionId where s.StoreId='${StoreId}'`;`;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(1),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_StoreImage(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT * FROM Master_ImageType  `;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  CROSS JOIN (SELECT ImageTypeId FROM Master_ImageType) MS
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_ShelfTalker(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT DISTINCT w.StDefinitionId FROM Master_ShelfTalkerDefinition w inner join Mapping_StoreShelfTalker s on w.StDefinitionId=s.StDefinitionId  where s.StoreId='${StoreId}' `;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL, IFNULL(count(1),0) as DataRowAvlblCount  
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreShelfTalker MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_ShelfTalkerDefinition W on W.StDefinitionId=MW.StDefinitionId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}


export function Q_getAvailbl_PromoOneApp(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT DISTINCT w.PromoDefinitionId FROM Master_PromotionDefinition w inner join Mapping_StorePromotion s on w.PromoDefinitionId=s.PromoDefinitionId  where s.StoreId='${StoreId}' `;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL , IFNULL(count(W.PromoDefinitionId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StorePromotion MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_PromotionDefinition W on W.PromoDefinitionId=MW.PromoDefinitionId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_PaidVisOneApp(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let isSpecificMapIndex = AllKPIFields?.findIndex(i => i.KPIFieldName == 'SpecificMapping')
  let isSpecificMapKPIObj = isSpecificMapIndex >= 0 ? AllKPIFields[isSpecificMapIndex] : {};
  let isSpecificMappingEnable = isSpecificMapIndex >= 0 ? isSpecificMapKPIObj['KPIFieldEnable'] : false;

  // let AllKPIFields=await getKPIFields(menuItem);
  //         console.log("AllKPIFields--------------ad",AllKPIFields)
  // let isSpecificMapIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='SpecificMapping')
  // let isSpecificMapKPIObj=isSpecificMapIndex>=0?AllKPIFields[isSpecificMapIndex]:{};
  // let isSpecificMappingEnable=isSpecificMapIndex>=0?isSpecificMapKPIObj['KPIFieldEnable']:true;
  // let q=`SELECT DISTINCT w.VisibilityDefinitionId FROM Master_VisibilityDefinition w inner join Mapping_StoreVisibility s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  where s.StoreId='${StoreId}' `;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.VisibilityDefinitionId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN (select distinct StoreId,VisibilityDefinitionId from ${isSpecificMappingEnable == true ? 'Mapping_StoreVisibilitySpecific' : "Mapping_StoreVisibility"}) MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_VisibilityDefinition W on W.VisibilityDefinitionId=MW.VisibilityDefinitionId and W.MenuId='${MenuId}'
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  // console.log("Q_getAvailbl_PaidVisOneApp q:",q);
  return q;
}

export function Q_getAvailbl_WareHouseDeploy(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId, MenuName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let DeploymentTypeH = AllKPIFields?.find((i) => i.ScreenName == "WAREHOUSEDEPLOY" && i.KPIFieldName == "DeploymentTypeHide");

  let DeploymentTypeHArr = DeploymentTypeH?.KPIType?.split(":");
  let DeploymentTypeHMenu = DeploymentTypeHArr?.length > 0 ? DeploymentTypeHArr[DeploymentTypeHArr?.length - 1] : null;


  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ItemId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN ${DeploymentTypeHMenu == MenuId ? "Mapping_WarehousePrimaryItem" : "Mapping_WarehouseCampaignDeployment"} MW on MW.MenuId='${MenuId}' and MW.StoreId=JP.StoreId
  INNER JOIN Master_WarehouseItem W on W.ItemId=MW.ItemId 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  // let q=`SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ItemId),0) as DataRowAvlblCount
  // from ${PJP_Table} JP 
  // INNER JOIN Mapping_WarehouseCampaignDeployment MW on MW.ItemId=W.ItemId
  // INNER JOIN Master_WarehouseItem W on W.ItemCategory='${MenuName=="Temporary Visibility"?"Temporary Visibility":"Permanent Visibility"}'
  // Where JP.VisitDate='${d2}'
  // group by JP.StoreId`;

  // WHERE w.ItemCategory='${menu1?.MenuName=="Temporary Visibility"?"Temporary Visibility":"Permanent Visibility"}' 
  console.log("Q_getAvailbl_WarehouseDeployment q:", q, DeploymentTypeH);
  return q;
}

export function Q_getAvailbl_WarehouseDeploymentCampaign(menuItem, PJP_Table = '', AllKPIFields) {
  let { MenuId } = menuItem

  console.log("menuItem-----", menuItem)
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');


  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ItemId),0) as DataRowAvlblCount
  from ${PJP_Table} JP 
  INNER JOIN Mapping_WarehouseCampaignItem MW on MW.CityId=JP.CityId and MW.StoreTypeId=JP.StoreTypeId
  INNER JOIN Master_WarehouseItem W on W.ItemId=MW.ItemId 
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  // let q=`SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ItemId),0) as DataRowAvlblCount
  // from ${PJP_Table} JP 
  // INNER JOIN Mapping_WarehouseCampaignDeployment MW on MW.MenuId='${MenuId}'
  // INNER JOIN Master_WarehouseItem W on W.ItemId=MW.ItemId 
  // Where JP.VisitDate='${d2}'
  // group by JP.StoreId`;

  // let q=`SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.ItemId),0) as DataRowAvlblCount
  // from ${PJP_Table} JP 
  // INNER JOIN Mapping_WarehouseItem MW on MW.MenuId='${MenuId}'
  // INNER JOIN Master_WarehouseItem W on W.ItemId=MW.ItemIds
  // Where JP.VisitDate='${d2}'
  // group by JP.StoreId`;

  // console.log("Q_getAvailbl_WarehouseDeploymentCampaign q:",q);
  return q;
}

export function Q_getAvailbl_SOSOneApp(menuItem, PJP_Table = '', AllKPIFields = []) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let sosCheckAssortmentI = AllKPIFields?.findIndex(i => i.KPIFieldName == 'SOSCheckAssortment' && i.ScreenName == ScreenName);
  let sosCheckAssortmentObj = sosCheckAssortmentI >= 0 ? AllKPIFields[sosCheckAssortmentI] : {};
  let sosCheckAssortment = sosCheckAssortmentI >= 0 ? sosCheckAssortmentObj['KPIFieldEnable'] : false;

  function getprodq(fname = 'CategoryId') {
    let prodq = ` Select DISTINCT JP1.StoreId,p.${fname} from ${PJP_Table} JP1
    INNER JOIN Mapping_ProductAssortmentStorewise mp on mp.StoreId=JP1.StoreId
    INNER JOIN Product_Master p on p.ProductId=mp.ProductId `;
    return prodq;
  }

  let cat_assrtq = getprodq('CategoryId');
  let subcat_assrtq = getprodq('SubCategoryId');
  let brand_assrtq = getprodq('BrandId');
  let prd_assrtq = getprodq('ProductId');

  let q = ``;

  if (sosCheckAssortment) {

    q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelf MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfDefinition where  SOSChildTable='Master_Category') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${cat_assrtq})  p on p.CategoryId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId

    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelf MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfDefinition where  SOSChildTable='Master_SubCategory') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${subcat_assrtq})  p on p.SubCategoryId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId


    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelf MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfDefinition where  SOSChildTable='Master_Brand') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${brand_assrtq})  p on p.BrandId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId

    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelf MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfDefinition where  SOSChildTable='Master_Product') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${prd_assrtq})  p on p.ProductId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId
    `;

  }
  else {

    q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelf MW on MW.StoreId=JP.StoreId
    INNER JOIN Master_ShareOfShelfDefinition W on W.SOSDefinitionId=MW.SOSDefinitionId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId`;

  }

  // console.log('Q_getAvailbl_SOSOneApp AllKPIFields:',AllKPIFields);
  // console.log('Q_getAvailbl_SOSOneApp sosCheckAssortment:',sosCheckAssortment,q);

  return q;
}

export function Q_getAvailbl_SosEyeLevel(menuItem, PJP_Table = '', AllKPIFields = []) {
  let { MenuId, ScreenName } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let sosCheckAssortmentI = AllKPIFields?.findIndex(i => i.KPIFieldName == 'SOSCheckAssortment' && i.ScreenName == ScreenName);
  let sosCheckAssortmentObj = sosCheckAssortmentI >= 0 ? AllKPIFields[sosCheckAssortmentI] : {};
  let sosCheckAssortment = sosCheckAssortmentI >= 0 ? sosCheckAssortmentObj['KPIFieldEnable'] : false;

  function getprodq(fname = 'CategoryId') {
    let prodq = ` Select DISTINCT JP1.StoreId,p.${fname} from ${PJP_Table} JP1
    INNER JOIN Mapping_ProductAssortmentStorewise mp on mp.StoreId=JP1.StoreId
    INNER JOIN Product_Master p on p.ProductId=mp.ProductId `;
    return prodq;
  }

  let cat_assrtq = getprodq('CategoryId');
  let subcat_assrtq = getprodq('SubCategoryId');
  let brand_assrtq = getprodq('BrandId');
  let prd_assrtq = getprodq('ProductId');

  let q = ``;
  console.log("sosCheckAssortment------", sosCheckAssortment)
  if (sosCheckAssortment) {

    q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelfEyeLevel MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfEyeLevelDefinition where  SOSChildTable='Master_Category') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${cat_assrtq})  p on p.CategoryId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId

    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelfEyeLevel MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfEyeLevelDefinition where  SOSChildTable='Master_SubCategory') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${subcat_assrtq})  p on p.SubCategoryId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId


    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelfEyeLevel MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfEyeLevelDefinition where  SOSChildTable='Master_Brand') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${brand_assrtq})  p on p.BrandId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId

    UNION

    SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelfEyeLevel MW on MW.StoreId=JP.StoreId
    INNER JOIN (Select * from Master_ShareOfShelfEyeLevelDefinition where  SOSChildTable='Master_Product') W on W.SOSDefinitionId=MW.SOSDefinitionId
    INNER JOIN (${prd_assrtq})  p on p.ProductId=W.SOSChildValue and p.StoreId=JP.StoreId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId
    `;

  }
  else {

    q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.SOSDefinitionId),0) as DataRowAvlblCount
    from ${PJP_Table} JP 
    INNER JOIN Mapping_StoreShareOfShelfEyeLevel MW on MW.StoreId=JP.StoreId
    INNER JOIN Master_ShareOfShelfEyeLevelDefinition W on W.SOSDefinitionId=MW.SOSDefinitionId
    Where JP.VisitDate='${d2}'
    group by JP.StoreId`;

  }

  // console.log('Q_getAvailbl_SOSOneApp AllKPIFields:',AllKPIFields);
  // console.log('Q_getAvailbl_SOSOneApp sosCheckAssortment:',sosCheckAssortment,q);

  return q;
}

export function Q_getAvailbl_POSSaleOneApp(menuItem, PJP_Table = '') {
  // let {MenuId}= menuItem
  // // console.log('PossaleMenuId',MenuId)
  // let d1=new Date();
  // let d2=moment(d1).format('MM/DD/YYYY');
  // let q=`SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(ps.PosDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  // from ${PJP_Table} JP 
  // CROSS JOIN (SELECT * from Master_PosSaleDefinition) ps 
  // Where JP.VisitDate='${d2}'
  // group by JP.StoreId`;
  // console.log('qpos',q)

  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=SELECT DISTINCT w.SOSDefinitionId FROM Master_ShareOfShelfDefinition w inner join Mapping_StoreShareOfShelf s on w.SOSDefinitionId=s.SOSDefinitionId  where s.StoreId='${StoreId}' ;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(ps.PosDefinitionId),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  CROSS JOIN (SELECT * ,mps.StoreId from Master_PosSaleDefinition p INNER join Mapping_StorePosSaleDefinition mps on p.PosDefinitionId=mps.PosDefinitionId ) ps on ps.StoreId=JP.StoreId
  Where JP.VisitDate='${d2}' 
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_StoreCategoryOneApp(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // let q=SELECT DISTINCT w.SOSDefinitionId FROM Master_ShareOfShelfDefinition w inner join Mapping_StoreShareOfShelf s on w.SOSDefinitionId=s.SOSDefinitionId  where s.StoreId='${StoreId}' ;
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(W.CategoryDefinitionId),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_StoreCategory MW on MW.StoreId=JP.StoreId
  INNER JOIN Master_CategoryDefinition W on W.CategoryDefinitionId=MW.CategoryDefinitionId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  return q;
}

export function Q_getAvailbl_StoreScore(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,1 as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Report_ComplianceScore Rp on Rp.StoreId=JP.StoreId
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;
  // INNER JOIN Report_ComplianceScore Rp on Rp.StoreId=JP.StoreId
  return q;
}

export function Q_getAvailbl_OrderStatus(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // *****************************************
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,IFNULL(count(1),0) as DataRowAvlblCount 
  from ${PJP_Table} JP 
  CROSS JOIN (SELECT OrderId, StoreId  FROM PriviousVisit_Orders) as MS
  Where JP.VisitDate='${d2}' and MS.StoreId=JP.StoreId
  group by JP.StoreId`;

  return q;
}

//################### get KPI availbale queries End ############################

export function Q_getAvailbl_BreakTime(menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  // *****************************************
  let q = `SELECT JP.StoreId, ${MenuId} as MenuID,CASE WHEN count(1)>0 THEN 1 ELSE 0 END as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  CROSS JOIN (SELECT BreakId FROM Master_Break) MS
  Where JP.VisitDate='${d2}'
  group by JP.StoreId`;

  return q;
}


export function getAvailblQuery(menu, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch, AllKPIFields) {
  let { ScreenName, MenuId } = menu
  let PJP_Table = isBeat == true ? 'JourneyPlan_RouteWise' : (isAdhoc == true ? 'Adhoc_JourneyPlan' : isNonMerchan == true ? 'NonMerchandising_JourneyPlan' : isNonProgam == true ? 'NonProgram_JourneyPlan' : isStoreSearch == true ? 'StoreSearch_JourneyPlan' : 'Mapping_JourneyPlan');
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = ``;

  switch (ScreenName) {
    case 'STOCK':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      // console.log("chehcstock---",q)
      return q;
    case 'STOCKWITHPROMO':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    //arman
    case 'ONEAPPSTOCKQRSCAN':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'ONEAPPSALEQRSCAN':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'KYCONEAPP':
      q = Q_getAvailbl_KycOneApp(menu, PJP_Table, AllKPIFields);
      return q;

    case 'STOCKWITHCATEGORY':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'OPSTOCK':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'BACKSTOCK':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'MDSTOCK':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'CLSSTOCK':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SOS':
      q = Q_getAvailbl_SOS(menu, PJP_Table);
      return q;
    case 'PAIDVISI':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Paid');
      return q;
    case 'ADDITIONALVISI':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Add');
      return q;
    case 'ADDITIONALVISI_IR':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Add');
      return q;
    case 'ADDITIONALVISI_IR_ONLY':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Add');
      return q;
    case 'COMPVISI':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Comp');
      console.log("COMPVISI_qqqq", q)
      return q;
    case 'COMPVISI_IR':
      q = Q_getAvailbl_Vis(menu, PJP_Table, 'Comp');
      return q;
    case 'PROMOTION':
      q = Q_getAvailbl_Promo(menu, PJP_Table);
      return q;
    case 'COMPROMO':
      q = Q_getAvailbl_CompPromo(menu, PJP_Table);
      return q;
    case 'CONCOV':
      q = Q_getAvailbl_Default(menu, PJP_Table);
      return q;
    case 'SALE':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SURVEY':
      q = Q_getAvailbl_Survey(menu, PJP_Table);
      return q;
    case 'WINDOW':
      q = Q_getAvailbl_Window(menu, PJP_Table);
      return q;
    case 'WINDOW_IR':
      q = Q_getAvailbl_Window(menu, PJP_Table);
      return q;
    case 'POSM':
      q = Q_getAvailbl_POSM(menu, PJP_Table);
      return q;
    case 'FEEDBACK':
      q = Q_getAvailbl_Feedback(menu, PJP_Table);
      return q;
    case 'PROMOTION2':
      q = Q_getAvailbl_Promo(menu, PJP_Table);
      return q;
    case 'STOREIMG':
      q = Q_getAvailbl_StoreImage(menu, PJP_Table);
      return q;
    case 'SHELFTALKER':
      q = Q_getAvailbl_ShelfTalker(menu, PJP_Table);
      return q;
    case 'PROMOTIONONEAPP':
      q = Q_getAvailbl_PromoOneApp(menu, PJP_Table);
      return q;
    case 'PROMOTIONONEAPP_IR':
      q = Q_getAvailbl_PromoOneApp(menu, PJP_Table);
      return q;
    case 'PAIDVISIONEAPP':
      q = Q_getAvailbl_PaidVisOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'PAIDVISIONEAPP_IR':
      q = Q_getAvailbl_PaidVisOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'PAIDVISIONEAPP_IR_ONLY':
      q = Q_getAvailbl_PaidVisOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SOSONEAPP':
      q = Q_getAvailbl_SOSOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SOSONEAPP_IR':
      q = Q_getAvailbl_SOSOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SOSONEAPP_IR_ONLY':
      q = Q_getAvailbl_SOSOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'CATEXEONEAPP':
      q = Q_getAvailbl_StoreCategoryOneApp(menu, PJP_Table);
      return q;
    case 'STORESCORE':
      q = Q_getAvailbl_StoreScore(menu, PJP_Table);
      return q;
    case 'ORDER':
      q = Q_getAvailbl_Stock(menu, PJP_Table, AllKPIFields);
      return q;
    case 'ORDERSTATUS':
      q = Q_getAvailbl_OrderStatus(menu, PJP_Table);
      return q;
    case 'TRAININGONEAPP':
      q = Q_getAvailbl_Training(menu, PJP_Table);
      return q;
    case 'POSSALEONEAPP':
      q = Q_getAvailbl_POSSaleOneApp(menu, PJP_Table);
      // console.log('menu+PJPTable',q)
      return q;
    case 'SAMPLINGONEAPP':
      q = Q_getAvailbl_Sampling(menu, PJP_Table);
      return q;
    case 'PROGRAMONEAPP':
      q = Q_getAvailbl_ProgramOneApp(menu, PJP_Table, AllKPIFields);
      return q;
    case 'TGBASEDONEAPP':
      q = Q_getAvailbl_TGBASEDONEAPP(menu, PJP_Table, AllKPIFields);
      return q;
    case 'STOREDYNAMICSCORE':
      q = Q_getAvailbl_DynamicStorescore(menu, PJP_Table, AllKPIFields);
      return q;
    case 'ONEAPPMISSEDCALL':
      q = Q_getMissedCall(menu, PJP_Table, AllKPIFields);
      return q;
    case 'SOSEYELEVELONEAPP':
      q = Q_getAvailbl_SosEyeLevel(menu, PJP_Table, AllKPIFields);
      return q;
    case 'BREAKTIME':
      q = Q_getAvailbl_BreakTime(menu, PJP_Table);
      return q;
    case 'WAREHOUSEDEPLOY':
      q = Q_getAvailbl_WareHouseDeploy(menu, PJP_Table, AllKPIFields);
      return q;
    case 'WAREHOUSECAMPAIGN':
      q = Q_getAvailbl_WarehouseDeploymentCampaign(menu, PJP_Table, AllKPIFields);
      return q;
    case 'RETURNSTOCKONEAPP':
      q = Q_getAvailbl_ReturnStk(menu, PJP_Table);
      return q;

       case 'ORDERSIMPLIFYONEAPP':
      q = Q_getAvailbl_ReturnStk(menu, PJP_Table);
      return q;
    default: return '';

  }
}

export function getIfAvlbl(ScreenName, txnres2, storeData = {}) {
  let isAvlbl = false;
  switch (ScreenName) {
    case 'STOCK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'STOCKWITHCATEGORY':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'OPSTOCK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'BACKSTOCK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'MDSTOCK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'CLSSTOCK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'SOS':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PAIDVISI':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'RETURNSTOCKONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;

       case 'ORDERSIMPLIFYONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;

    case 'ADDITIONALVISI':
      if (txnres2.rows.length > 0 && storeData.AddVisiAllow == 'Y') { isAvlbl = true; }
      return isAvlbl;
    case 'ADDITIONALVISI_IR':
      if (txnres2.rows.length > 0 && storeData.AddVisiAllow == 'Y') { isAvlbl = true; }
      return isAvlbl;
    case 'COMPVISI':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'COMPVISI_IR':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PROMOTION':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    // case 10:
    // if(txnres2.rows.length>0){ isAvlbl=true;}
    // return isAvlbl;
    // case 11:isAvlbl=true;
    // return isAvlbl;
    // case 12:
    // if(txnres2.rows.length>0){ isAvlbl=true;}
    // return isAvlbl;
    case 'COMPROMO':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'CONCOV':
      isAvlbl = true;
      return isAvlbl;
    case 'SALE':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'SURVEY':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'WINDOW':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'WINDOW_IR':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'POSM':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'FEEDBACK':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PROMOTION2':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'STOREIMG':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'SHELFTALKER':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PROMOTIONONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PAIDVISIONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'PAIDVISIONEAPP_IR':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'SOSONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'SOSONEAPP_IR':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;
    case 'POSSALEONEAPP':
      if (txnres2.rows.length > 0) { isAvlbl = true; }
      return isAvlbl;

    default: return isAvlbl;
  }
}

export function getQuery(menu, isAdhoc, isBeat, isNonMerchan, isNonProgam, isStoreSearch) {
  let { ScreenName, MenuId } = menu;
  let PJP_Table = isBeat == true ? 'JourneyPlan_RouteWise' : (isAdhoc == true ? 'Adhoc_JourneyPlan' : isNonMerchan == true ? 'NonMerchandising_JourneyPlan' : isNonProgam == true ? 'NonProgram_JourneyPlan' : isStoreSearch == true ? 'StoreSearch_JourneyPlan' : 'Mapping_JourneyPlan');
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = ``;
  switch (ScreenName) {
    case 'STOCK':
      // SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}' `;
      return q;

    case 'STOCKWITHPROMO':
      // SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCKPROMO_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}' `;
      return q;

    ///arman 
    case 'ONEAPPSTOCKQRSCAN':
      // SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.QRCODE_SCANNER} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}' `;
      console.log("ONEAPPSTOCKQRSCAN--", q)
      return q;

    case 'ONEAPPSALEQRSCAN':
      // SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
            (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.QRCODE_SALE} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
            ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}' `;
      console.log("ONEAPPSALEQRSCAN--", q)
      return q;

    case 'KYCONEAPP':
      // SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK2HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
              (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STORE_KYC_INFO} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
              ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}' `;
      console.log("KYCONEAPP--", q)
      return q;


    case 'STOCKWITHCATEGORY':
      q = `SELECT Jp.StoreId,${MenuId} as MenuID, IFNULL(DR.StoreDone,0) as DataRowCount FROM ${PJP_Table} JP 
          LEFT OUTER JOIN
          (SELECT JP.StoreId,count(MC.CategoryId) as CatCount,count((CASE WHEN CR.StockCount>0 THEN 1 ElSE null  END)) as CatDoneCount 
          ,CASE WHEN count(MC.CategoryId)==count((CASE WHEN CR.StockCount>0 THEN 1 ElSE null  END)) THEN 1 ELSE 0 END as StoreDone
          FROM ${PJP_Table} JP
          CROSS JOIN (Select Distinct CategoryId,CategoryName from Product_Master p
            INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId where mp.StoreId=JP.StoreId) MC
          LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId ,CATEGORY_ID as CategoryId, IFNULL(COUNT(STOCK),0) AS StockCount FROM ${AppTables.STOCKWITHCAT_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID,CATEGORY_ID ) CR
          ON JP.StoreId=CR.StoreId and MC.CategoryId=CR.CategoryId
          GROUP BY JP.StoreId)  DR
          ON DR.StoreId=JP.StoreId  Where Jp.VisitDate='${d2}' GROUP BY JP.StoreId`;
      return q;
    case 'OPSTOCK':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'BACKSTOCK':
      // q=`SELECT DISTINCT STOCK FROM ${AppTables.CHILD_BACK_OF_STORE} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.CHILD_BACK_OF_STORE} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'MDSTOCK':
      // q=`SELECT DISTINCT MIDDAY_STOCK FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID,  IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT DISTINCT MIDDAY_STOCK,STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK_DATA} WHERE VISIT_DATE='${d2}' and MIDDAY_STOCK is not null and MIDDAY_STOCK!='' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;

      return q;
    case 'CLSSTOCK':
      // q=`SELECT DISTINCT CLOSING_STOCK FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID,  IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT DISTINCT CLOSING_STOCK,STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STOCK_DATA} WHERE VISIT_DATE='${d2}' and CLOSING_STOCK is not null and CLOSING_STOCK!='' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId where Jp.VisitDate='${d2}' `;
      return q;
    case 'SOS':
      // q=`SELECT * FROM ${AppTables.SHARE_OF_SHELF_IMAGE} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SHARE_OF_SHELF_IMAGE} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PAIDVISI':
      // q=`SELECT * FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID,  IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'RETURNSTOCKONEAPP':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.RETURN_STOCK} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'ORDERSIMPLIFYONEAPP':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ORDER_SIMPLIFY} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'ADDITIONALVISI':
      // q=`SELECT * FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'ADDITIONALVISI_IR':
      // q=`SELECT * FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'ADDITIONALVISI_IR_ONLY':
      // q=`SELECT * FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'COMPVISI':
      // q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.COMPETITION_VISIBILITY} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'COMPVISI_IR':
      // q=`SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.COMPETITION_VISIBILITY} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PROMOTION':
      // q=`SELECT * FROM ${AppTables.PROMOTION_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID,  IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PROMOTION_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'COMPROMO':
      // q=`SELECT * FROM ${AppTables.COMPETITION_PROMOTION} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.COMPETITION_PROMOTION} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'CONCOV':
      // q=`SELECT * FROM ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.CONTACT_CONVERSION} WHERE SCREEN_TYPE='Contact' AND VISIT_DATE='${d2}'  GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'SALE':
      // q=`SELECT DISTINCT STOCK FROM ${AppTables.SALES} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SALES} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'ORDER':
      // q=`SELECT DISTINCT STOCK FROM ${AppTables.SALES} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ORDER} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'ORDERSTATUS':
      // q=` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
      // (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ORDERSTATUS} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
      // ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;


      q = `select Distinct DR.StoreId,${MenuId} as MenuID, (CASE WHEN count(DR.OrderId)==count(DR.IsDone)  THEN 1 ELSE 0 END)  as DataRowCount
          from
          (select Distinct JP.StoreId,JP.VisitDate,p.OrderId,p2.ProductCount,(CASE WHEN o.FilledProdCount>0 THEN 1 ELSE null END) as IsDone from ${PJP_Table} as JP
          INNER join PriviousVisit_Orders p on p.StoreId=JP.StoreId
          LEFT OUTER JOIN (select OrderId,count(ProductId) as ProductCount from PriviousVisit_Orders GROUP BY OrderId )  p2 on p.OrderId=p2.OrderId
          LEFT OUTER JOIN (Select ORDER_ID,count(ORDER_ID) as FilledProdCount from ORDER_STATUS where  VISIT_DATE='${d2}' group by ORDER_ID) o on p.OrderId=o.ORDER_ID
          )DR WHERE DR.VisitDate='${d2}'  group by DR.StoreId`;

      return q;
    case 'SURVEY':
      q = `SELECT JP.StoreId, ${MenuId} as MenuID, DataRowCount FROM  ${PJP_Table} JP 
          LEFT OUTER JOIN
          (SELECT SR.StoreId,SR.ShowCat,(CASE WHEN Count(SR.SurveyId) = count(CASE WHEN SR.SurveyDone==1 THEN 1 ELSE null END)
           THEN 1 ELSE 0 END) as DataRowCount FROM 
          (SELECT DISTINCT JP.StoreId,T.SurveyId,T.ShowCat,(CASE WHEN SF.Qtns>0 THEN 1 ELSE 0 END ) AS SurveyDone  FROM Master_SurveyQuestion T 
          INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
          INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
          LEFT OUTER JOIN  
          (
           SELECT T1.STORE_ID AS StoreId, T1.SURVEY_ID AS SurveyId, CASE  WHEN COUNT(T1.QUESTION_ID) = M.TotalQuestion THEN 1  ELSE 0  END AS Qtns from ${AppTables.SURVEY} T1 
           INNER JOIN (  SELECT m.StoreId, m.SurveyId, COUNT(DISTINCT t.QuestionId) AS TotalQuestion FROM Mapping_Survey m
           INNER JOIN ${PJP_Table} n ON n.StoreId = m.StoreId INNER JOIN Master_SurveyQuestion t ON t.SurveyId = m.SurveyId WHERE t.MenuId = '${MenuId}'
           GROUP BY m.StoreId, m.SurveyId
          ) AS M ON M.StoreId = T1.STORE_ID AND M.SurveyId = T1.SURVEY_ID
           where T1.VISIT_DATE='${d2}' and T1.MENU_ID='${MenuId}' 
            GROUP BY T1.STORE_ID,T1.SURVEY_ID, M.TotalQuestion
            
            ) SF 
          on T.SurveyId=SF.SurveyId and JP.StoreId=SF.StoreId Where T.MenuId='${MenuId}') SR GROUP BY SR.StoreId ) DR 
          ON JP.StoreId=DR.StoreId WHERE JP.VisitDate='${d2}'
          

          UNION

          SELECT JP.StoreId, ${MenuId} as MenuID, DR.DataRowCount as DataRowCount FROM  ${PJP_Table} JP 
          LEFT OUTER JOIN
          (SELECT SR.StoreId,SR.ShowCat, (CASE WHEN Count(SR.SurveyId) = count(CASE WHEN SR.SurveyDone==1 THEN 1 ELSE null END) THEN 1 ELSE 0 END) as DataRowCount
           FROM 
            (SELECT  DISTINCT JP.StoreId,T.SurveyId,SCF.ShowCat,(CASE WHEN count(SCF.CategoryId) =  count(CASE WHEN SCF.SurveyCatDone=1 THEN 1 ELSE null END) and count(SCF.CategoryId)>0 THEN 1 ELSE 0 END   ) as SurveyDone
          		FROM (Select DISTINCT SurveyId,ShowCat, CategoryId from Master_SurveyQuestion Where MenuId='${MenuId}') T 
                    INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
                    INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
                    LEFT OUTER JOIN  
                
                    (SELECT  DISTINCT JP.StoreId,T.SurveyId,T.ShowCat,T.CategoryId,(CASE WHEN count(SF.Qtns)>0 THEN 1 ELSE 0 END) as SurveyCatDone
                      FROM Master_SurveyQuestion T 
                      INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
                      INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
                      LEFT OUTER JOIN  
          				    ( SELECT DISTINCT T1.STORE_ID as StoreId,T1.SURVEY_ID as  SurveyId,T1.CATEGORY_ID as CategoryId,count(T1.QUESTION_ID) as Qtns  from ${AppTables.SURVEY} T1 where VISIT_DATE='${d2}' and MENU_ID='${MenuId}'  GROUP BY STORE_ID,SURVEY_ID,CATEGORY_ID) SF  
          				    on T.SurveyId=SF.SurveyId and JP.StoreId=SF.StoreId and T.CategoryId=SF.CategoryId
                      Where T.MenuId='${MenuId}'
                 
          					GROUP BY JP.StoreId,T.SurveyId,T.CategoryId
          		    ) SCF  on M.StoreId=SCF.StoreId and T.SurveyId=SCF.SurveyId and  T.CategoryId=SCF.CategoryId
                GROUP BY JP.StoreId,T.SurveyId
            ) SR GROUP BY SR.StoreId 
          )DR on JP.StoreId=DR.StoreId  WHERE JP.VisitDate='${d2}'
          
          `;
      // console.log('survey done q:',q);
      // AND DR.ShowCat='1'
      //AND DR.ShowCat='0'

      //  q=`SELECT JP.StoreId, ${MenuId} as MenuID, DataRowCount FROM  ${PJP_Table} JP 
      //            LEFT OUTER JOIN
      //            (SELECT SR.StoreId,SR.ShowCat,(CASE WHEN Count(SR.SurveyId) = count(CASE WHEN SR.SurveyDone==1 THEN 1 ELSE null END)  THEN 1 ELSE 0 END) as DataRowCount
      //            FROM 
      //            (SELECT DISTINCT JP.StoreId,T.SurveyId,T.ShowCat,(CASE WHEN SF.Qtns>0 THEN 1 ELSE 0 END ) AS SurveyDone  FROM Master_SurveyQuestion T 
      //            INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
      //            INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
      //            LEFT OUTER JOIN  
      //            ( SELECT DISTINCT T1.STORE_ID as StoreId,T1.SURVEY_ID as  SurveyId,count(T1.QUESTION_ID ) as Qtns from ${AppTables.SURVEY} T1 where VISIT_DATE='${d2}' and MENU_ID='${MenuId}'  GROUP BY STORE_ID,SURVEY_ID) SF 
      //            on T.SurveyId=SF.SurveyId and JP.StoreId=SF.StoreId Where T.MenuId='${MenuId}') SR GROUP BY SR.StoreId ) DR 
      //            ON JP.StoreId=DR.StoreId WHERE JP.VisitDate='${d2}'



      //            UNION



      //            SELECT JP.StoreId, ${MenuId} as MenuID, DR.DataRowCount as DataRowCount FROM  ${PJP_Table} JP 
      //            LEFT OUTER JOIN
      //            (SELECT SR.StoreId,SR.ShowCat, (CASE WHEN Count(SR.SurveyId) = count(CASE WHEN SR.SurveyDone==1 THEN 1 ELSE null END) THEN 1 ELSE 0 END) as DataRowCount
      //             FROM 
      //              (SELECT  DISTINCT JP.StoreId,T.SurveyId,SCF.ShowCat,(CASE WHEN count(SCF.CategoryId) =  count(CASE WHEN SCF.SurveyCatDone=1 THEN 1 ELSE null END) and count(SCF.CategoryId)>0 THEN 1 ELSE 0 END   ) as SurveyDone
      //               FROM (Select DISTINCT SurveyId,ShowCat, CategoryId from Master_SurveyQuestion Where MenuId='${MenuId}') T 
      //                      INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
      //                      INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
      //                      LEFT OUTER JOIN  

      //                      (SELECT  DISTINCT JP.StoreId,T.SurveyId,T.ShowCat,T.CategoryId,(CASE WHEN count(SF.Qtns)>0 THEN 1 ELSE 0 END) as SurveyCatDone
      //                        FROM Master_SurveyQuestion T 
      //                        INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId  
      //                        INNER JOIN ${PJP_Table} JP ON M.StoreId=JP.StoreId  
      //                        LEFT OUTER JOIN  
      //                       ( SELECT DISTINCT T1.STORE_ID as StoreId,T1.SURVEY_ID as  SurveyId,T1.CATEGORY_ID as CategoryId,count(T1.QUESTION_ID) as Qtns  from ${AppTables.SURVEY} T1 where VISIT_DATE='${d2}' and MENU_ID='${MenuId}'  GROUP BY STORE_ID,SURVEY_ID,CATEGORY_ID) SF  
      //                       on T.SurveyId=SF.SurveyId and JP.StoreId=SF.StoreId and T.CategoryId=SF.CategoryId
      //                        Where T.MenuId='${MenuId}'

      //                     GROUP BY JP.StoreId,T.SurveyId,T.CategoryId
      //                   ) SCF  on M.StoreId=SCF.StoreId and T.SurveyId=SCF.SurveyId and  T.CategoryId=SCF.CategoryId
      //                  GROUP BY JP.StoreId,T.SurveyId
      //              ) SR GROUP BY SR.StoreId 
      //            )DR on JP.StoreId=DR.StoreId  WHERE JP.VisitDate='${d2}'


      //            `;
      return q;

    case 'WINDOW':
      // q=`SELECT DISTINCT WINDOW_DEFINITION_ID  FROM ${AppTables.WINDOW_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'  `;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.WINDOW_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'WINDOW_IR':
      // q=`SELECT DISTINCT WINDOW_DEFINITION_ID  FROM ${AppTables.WINDOW_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'  `;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.WINDOW_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'POSM':
      // q=`SELECT DISTINCT POSM_DEFINITION_ID  FROM ${AppTables.POSM_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'  `;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.POSM_HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'FEEDBACK':
      // q=`SELECT DISTINCT QUESTION_ID  FROM ${AppTables.FEEDBACK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'  `;
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId ,  IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.FEEDBACK_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PROMOTION2':
      // q=`SELECT * FROM ${AppTables.SIMPLE_PROMOTION_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SIMPLE_PROMOTION_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'STOREIMG':
      // q=`SELECT * FROM ${AppTables.STORE_IMAGES} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      // q=` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
      // (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.STORE_IMAGES} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
      // ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;

      q = `SELECT StoreId , ${MenuId} as MenuID,  (CASE WHEN count(d.ImageTypeId)=count(d.isStImageDone) THEN 1 ELSE 0 END) as DATAROWCOUNT from (
            select distinct jtbl.StoreId,jtbl.ImageTypeId,jtbl.ImageType,jtbl.MinImage,	count(i.IMAGE) as ImageCount,(CASE WHEN count(i.IMAGE)>=jtbl.MinImage THEN 1 ELSE NULL END ) isStImageDone
            from  (select JPTbl.*,m.ImageTypeId,m.ImageType,m.MinImage from ${PJP_Table}  JPTbl cross join Master_ImageType m ) jtbl 
            Left Outer join ${AppTables.STORE_IMAGES} i on  jtbl.ImageTypeId=i.IMAGE_TYPE_ID and jtbl.StoreId=i.STORE_ID and i.VISIT_DATE='${d2}'
              group by jtbl.StoreId,jtbl.ImageTypeId
            ) d  GROUP BY StoreId`


      // console.log("DataRowCount-----d",q)
      return q;

    case 'SHELFTALKER':
      // q=`SELECT DISTINCT ST_DEFINITION_ID  FROM ${AppTables.ST_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID,  IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.ST_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'PROMOTIONONEAPP':
      // q=`SELECT DISTINCT PROMO_DEFINITION_ID  FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PROMO_HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PROMOTIONONEAPP_IR':
      // q=`SELECT DISTINCT PROMO_DEFINITION_ID  FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PROMO_HDR_DATA} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PAIDVISIONEAPP':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'WAREHOUSEDEPLOY':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.WAREHOUSE_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'WAREHOUSECAMPAIGN':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.WAREHOUSE_CAMPAIGN_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PAIDVISIONEAPP_IR':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'PAIDVISIONEAPP_IR_ONLY':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'SOSONEAPP':
      // q=`SELECT DISTINCT SOS_DEFINITION_ID  FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SOS_CHILD_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'SOSONEAPP_IR':
      // q=`SELECT DISTINCT SOS_DEFINITION_ID  FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SOS_CHILD_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'SOSONEAPP_IR_ONLY':
      // q=`SELECT DISTINCT SOS_DEFINITION_ID  FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.SOS_CHILD_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'CATEXEONEAPP':
      // q=`SELECT DISTINCT SOS_DEFINITION_ID  FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.CATEXE_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'STORESCORE':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, 1 as DataRowCount FROM ${PJP_Table} JP`;
      return q;
    case 'TRAININGONEAPP':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, 1 as DataRowCount FROM ${PJP_Table} JP`;
      return q;
    case 'SAMPLINGONEAPP':
      //count(CASE WHEN l.ISFILLED='1' THEN 1  ELSE NULL END) as DataRowCount, 
      // (CASE WHEN (count(CASE WHEN l.ISFILLED='1' THEN 1  ELSE NULL END))==count(T.SamplingDefinitionId) THEN 1 ELSE 0 END ) as DataRowCount
      q = ` SELECT DR.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount 
          FROM 
          (SELECT JP1.StoreId,
            (CASE WHEN (count(CASE WHEN l.ISFILLED='1' THEN 1  ELSE NULL END))==count(T.SamplingDefinitionId) THEN 1 ELSE 0 END ) as DataRowCount,

          count(T.SamplingDefinitionId) as SamplingAvlblCount
          
                                 From ${PJP_Table} JP1 
                                 INNER JOIN Mapping_StoreSampling M on JP1.StoreId=M.StoreId 
                                 INNER JOIN Master_SamplingDefinition T ON T.SamplingDefinitionId=M.SamplingDefinitionId       
                                 Left Outer Join ${AppTables.SAMPLING_LIST} l on T.SamplingDefinitionId=l.SAMPLING_DEFINITION_ID and JP1.StoreId=l.STORE_ID and l.VISIT_DATE='${d2}'    
                                 GROUP BY JP1.StoreId) DR `

      return q;
    case 'POSSALEONEAPP':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.POSSALE_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'PROGRAMONEAPP':
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
          (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.PROGRAM_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
          ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'TGBASEDONEAPP':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
            (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.VISICO_HDR_DATA} WHERE VISIT_DATE='${d2}' and MENU_ID='${MenuId}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
            ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;
    case 'STOREDYNAMICSCORE':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, 1 as DataRowCount FROM ${PJP_Table} JP WHERE Jp.VisitDate='${d2}'`
      return q;
    case 'ONEAPPMISSEDCALL':
      // q=`SELECT DISTINCT PVIS_DEFINITION_ID  FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
            (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.MISSED_CALL} WHERE VISIT_DATE='${d2}' and IS_UPDATED='1' GROUP BY STORE_ID) DR
            ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'SOSEYELEVELONEAPP':
      // q=`SELECT DISTINCT SOS_DEFINITION_ID  FROM ${AppTables.SOS_HDR_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}' `
      q = ` SELECT Jp.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
            (SELECT STORE_ID AS StoreId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.EYE_LEVEL_CHILD_DATA} WHERE VISIT_DATE='${d2}' GROUP BY STORE_ID) DR
            ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`;
      return q;

    case 'BREAKTIME':

      //       q=`SELECT JP.StoreId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount 
      //       FROM ${PJP_Table} JP LEFT OUTER JOIN(
      //   SELECT STORE_ID AS StoreId , (CASE WHEN  count(c.Status)=count(c.BreakId) THEN 1 ELSE 0 END) AS DATAROWCOUNT FROM
      // (SELECT DISTINCT B.STORE_ID,B.VISIT_DATE,B.BreakId ,A.MINNUMBER,A.MAXNUMBER,B.COUNT, CASE WHEN B.COUNT>=A.MINNUMBER THEN 1 ELSE null  END AS STATUS FROM
      // (select BreakId ,MINNUMBER,MAXNUMBER from ${AppTables.BREAKTIME} WHERE VISIT_DATE='06/12/2023'  )A
      // LEFT JOIN (select store_id, VISIT_DATE,breakid , count (*) as count from ${AppTables.BREAKTIME} group by store_id, VISIT_DATE,breakid)  B
      // ON A.BreakId=B.BreakId ) c 
      // INNER JOIN Master_Break T ON T.BreakId=c.breakid 
      // ) DR ON JP.StoreId=DR.StoreId WHERE Jp.VisitDate='${d2}'`

      // q=`SELECT StoreId , ${MenuId} as MenuID,  (CASE WHEN count(d.BreakId)=count(d.isStImageDone) THEN 1 ELSE 0 END) as DATAROWCOUNT from 
      //     (select distinct jtbl.StoreId,jtbl.BreakId,jtbl.Break_Name,jtbl.Minimum, 
      //       count(i.BREAKID) as BreakCount,(CASE WHEN count(i.BREAKID)>=jtbl.Minimum THEN 1 ELSE NULL END ) isStImageDone
      //         from  
      //           (select JPTbl.*,m.BreakId,m.Break_Name,m.Minimum from ${PJP_Table}  JPTbl cross join Master_Break m ) jtbl
      //         Left Outer join ${AppTables.BREAKTIME}  i on  jtbl.BreakId=i.BREAKID and jtbl.StoreId=i.STORE_ID and i.VISIT_DATE='${d2}'
      //         group by jtbl.StoreId,jtbl.BreakId
      //       ) d  GROUP BY StoreId`

      q = `SELECT StoreId , ${MenuId} as MenuID,  (CASE WHEN count(d.isStImageDone) THEN 1 ELSE 0 END) as DATAROWCOUNT from 
                (select distinct jtbl.StoreId,jtbl.BreakId,jtbl.Break_Name,jtbl.Minimum, 
                  count(i.BREAKID) as BreakCount,(CASE WHEN count(i.BREAKID)>=jtbl.Minimum THEN 1 ELSE NULL END ) isStImageDone
                    from  
                      (select JPTbl.*,m.BreakId,m.Break_Name,m.Minimum from ${PJP_Table}  JPTbl cross join Master_Break m ) jtbl
                    Left Outer join ${AppTables.BREAKTIME}  i on  jtbl.BreakId=i.BREAKID and jtbl.StoreId=i.STORE_ID and i.VISIT_DATE='${d2}'
                    group by jtbl.StoreId,jtbl.BreakId
                  ) d  GROUP BY StoreId`

      console.log("BreakTime list q:1", q)
      return q;

    default: return '';

  }
}

export async function getIfKPIDone(ScreenName, txnres2, storeData) {
  let isDone = false;
  switch (ScreenName) {
    case 'STOCK':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.STORE_ID != null && sdata.STORE_ID != '') isDone = true;
      }
      return isDone;

    case 'STOCKWITHCATEGORY':
      let isDone = await checkIf_StockWithCat_KPIDone(txnres2, storeData);
      return isDone;
    case 'OPSTOCK':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.STORE_ID != null && sdata.STORE_ID != '') isDone = true;
      }
      return isDone;
    case 'BACKSTOCK':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.STOCK === 0 || (sdata.STOCK != null && sdata.STOCK != '')) isDone = true;
      }
      return isDone;
    case 'MDSTOCK':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.MIDDAY_STOCK === 0 || (sdata.MIDDAY_STOCK != null && sdata.MIDDAY_STOCK != '')) isDone = true;
      }
      return isDone;
    case 'CLSSTOCK':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.CLOSING_STOCK === 0 || (sdata.CLOSING_STOCK != null && sdata.CLOSING_STOCK != '')) isDone = true;
      }
      return isDone;
    case 'SOS':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'PAIDVISI':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'RETURNSTOCKONEAPP':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;

    case 'ORDERSIMPLIFYONEAPP':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;

    case 'ADDITIONALVISI':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'ADDITIONALVISI_IR':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'COMPVISI':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'COMPVISI_IR':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'PROMOTION':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    // case 10:
    //   if(txnres2.rows.length>0) isDone=true;
    // return isDone; 
    // case 11: 
    // if(txnres2.rows.length>0){
    //   let grdata=txnres2.rows.item(0);
    //   if(grdata.IMAGE!=null && grdata.IMAGE!='' ) isDone=true;
    // }      
    // return isDone; 
    // case 12:
    //   if(txnres2.rows.length>0) isDone=true;
    // return isDone; 
    case 'COMPROMO':
      if (txnres2.rows.length > 0) isDone = true;
      return isDone;
    case 'CONCOV':
      if (txnres2.rows.length > 0) {
        let ccdata = txnres2.rows.item(0);
        if (ccdata.TOTAL_CONTACT === 0 || (ccdata.TOTAL_CONTACT != null && ccdata.TOTAL_CONTACT != '')) isDone = true;
      }
      return isDone;
    case 'SALE':
      if (txnres2.rows.length > 0) {
        let sdata = txnres2.rows.item(0);
        if (sdata.STOCK === 0 || (sdata.STOCK != null && sdata.STOCK != '')) isDone = true;
      }
      return isDone;
    case 'SURVEY':
      isDone = await checkFilledSurveys(ScreenName, txnres2, storeData);
      return isDone;
    case 'WINDOW':
      if (txnres2.rows.length > 0) {
        isDone = true;
      }
      return isDone;
    case 'WINDOW_IR':
      if (txnres2.rows.length > 0) {
        isDone = true;
      }
      return isDone;
    case 'POSM':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'FEEDBACK':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'PROMOTION2':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'STOREIMG':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'SHELFTALKER':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'PROMOTIONONEAPP':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'POSSALEONEAPP':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'PAIDVISIONEAPP':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'PAIDVISIONEAPP_IR':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'SOSONEAPP':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;
    case 'SOSONEAPP_IR':
      if (txnres2.rows.length > 0) { isDone = true; }
      return isDone;

    default: return isDone;

  }
}


// ##### DB get available queries start

export function Q_getAvlblDBPOSM(props, menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
  INNER JOIN Mapping_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId
  
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
  INNER JOIN Adhoc_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `+ (props.ShowNonMerList == true ? `
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
  INNER JOIN NonMerchandising_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId
  `: '')
    + (props.ShowNonProgram == true ? `
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
  INNER JOIN NonProgram_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId
 
  `: '')
    + (props.ShowStoreSearch == true ? `
    union 
    
    SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
    from ${PJP_Table} JP 
    Inner Join 
    (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
    INNER JOIN StoreSearch_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
    INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
    INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
    Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
    on dbPOSM.DistributorId=JP.DistributorId
    group by JP.DistributorId
   
    `: '')
    + (props.ShowBeatPlanList == true ?
      `
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.POSMDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.POSMDefinitionId from ${PJP_Table} db
  INNER JOIN JourneyPlan_RouteWise jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StorePOSM MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_POSMDefinition W on W.POSMDefinitionId=MW.POSMDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.POSMDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `: '');

  return q;
}

export function Q_getAvlblDBWindow(props, menuItem, PJP_Table = '') {
  let { MenuId } = menuItem
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
  INNER JOIN Mapping_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId 
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId
  
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
  INNER JOIN Adhoc_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `+ (props.ShowNonMerList == true ? `

  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
  INNER JOIN NonMerchandising_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `: '')
    + (props.ShowNonProgram == true ? `

  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
  INNER JOIN NonProgram_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `: '')
    + (props.ShowStoreSearch == true ? `

    union 
    
    SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
    from ${PJP_Table} JP 
    Inner Join 
    (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
    INNER JOIN StoreSearch_JourneyPlan jcp on db.DistributorId=jcp.DistributorId
    INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
    INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId
    Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
    on dbPOSM.DistributorId=JP.DistributorId
    group by JP.DistributorId

    `: '')
    + (props.ShowBeatPlanList == true ?
      `
  union 
  
  SELECT JP.DistributorId, ${MenuId} as MenuID,CASE WHEN count(dbPOSM.WindowDefinitionId)>0 THEN 1 ELSE 0 END as KPIAVBL 
  from ${PJP_Table} JP 
  Inner Join 
  (select Distinct db.DistributorId,W.WindowDefinitionId from ${PJP_Table} db
  INNER JOIN JourneyPlan_RouteWise jcp on db.DistributorId=jcp.DistributorId
  INNER JOIN Mapping_StoreWindow MW on MW.StoreId=jcp.StoreId
  INNER JOIN Master_WindowDefinition W on W.WindowDefinitionId=MW.WindowDefinitionId
  Where jcp.VisitDate='${d2}' order by db.DistributorId,W.WindowDefinitionId) dbPOSM
  on dbPOSM.DistributorId=JP.DistributorId
  group by JP.DistributorId

  `: '');
  return q;
}


export function Q_getAvlblDBVisicooler(props, menu, PJP_Table = '') {
  let { MenuId } = menu
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');

  let q = `SELECT JP.DistributorId, ${MenuId} as MenuID,1 as KPIAVBL ,1 as DataRowAvlblCount 
  from ${PJP_Table} JP 
  INNER JOIN Mapping_MenuDistributorPoint MW on MW.MenuId='${MenuId}'
  group by JP.DistributorId`;
  // Where JP.VisitDate='${d2}'

  // let join2=` inner join Sup_VisibilityAudit s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  `;
  // let q=` Select * from Sup_Master_VisibilityDefinition w  ${join2} where s.StoreId='${StoreId}'`;

  return q;
}

// ##### DB get available queries end

export function get_DBAvailblQuery(props, menu, PJP_Table) {
  let { ScreenName, MenuId } = menu
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = ``;

  switch (ScreenName) {
    case 'DBPOSMONEAPP':
      q = Q_getAvlblDBPOSM(props, menu, PJP_Table);
      return q;
    case 'DBWINDOWONEAPP':
      q = Q_getAvlblDBWindow(props, menu, PJP_Table);
      return q;
    case 'DBVISICOOLERONEAPP':
      q = Q_getAvlblDBVisicooler(props, menu, PJP_Table);
      return q;
    default: return '';
  }
}

export function get_DBQuery(menu, PJP_Table) {
  let { ScreenName, MenuId } = menu
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let q = ``;

  switch (ScreenName) {
    case 'DBPOSMONEAPP':
      q = ` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DBPOSM_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
      return q;
    case 'DBWINDOWONEAPP':
      q = ` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DB_WINDOW_HDR_DATA} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
      return q;
    case 'DBVISICOOLERONEAPP':
      q = ` SELECT Jp.DistributorId, ${MenuId} as MenuID, IFNULL(DR.DataRowCount,0) as DataRowCount FROM ${PJP_Table} JP LEFT OUTER JOIN
        (SELECT DISTRIBUTOR_ID AS DistributorId , IFNULL(COUNT(1),0) AS DATAROWCOUNT FROM ${AppTables.DB_VISICOOLER} WHERE VISIT_DATE='${d2}' GROUP BY DISTRIBUTOR_ID) DR
        ON JP.DistributorId=DR.DistributorId `;
      return q;
    default: return '';

  }
}


async function checkIf_StockWithCat_KPIDone(txnres2, storeData) {
  let { StoreId } = storeData;
  return await new Promise((resolve, reject) => {
    if (txnres2.rows.length > 0) {
      db.transaction(async function (txn) {
        let allDone = true;
        for (var i = 0; i < txnres2.rows.length; i++) {
          let cat = txnres2.rows.item(i);
          let isDone = await isCatDone(storeData, cat)
          if (isDone == false) {
            allDone = false;
          }

          if (i == txnres2.rows.length - 1) {
            resolve(allDone);
          }
        }
      });

    }
    else {
      resolve(false);
    }
  }).catch((err) => {
    console.log(err);
    return false;
  });

}

async function isCatDone(storeData1, cat) {
  let { StoreId, ChainId, StateId, StoreTypeId } = storeData1;
  return await new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let seletlist = `STOCK_UID,PRODUCT as ProductName,PRODUCT_ID as ProductId,BRAND as BrandName,BRAND_ID as BrandId,SUB_CATEGORY as SubCategoryName,SUB_CATEGORY_ID as SubCategoryId,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK`;
      let sku_q = `SELECT ${seletlist} FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' and CATEGORY_ID='${cat.CategoryId}'    `;
      await txn.executeSql(sku_q, [], async function (txn2, txnres2) {
        if (txnres2.rows.length > 0) {
          resolve(true);
        } else {
          resolve(false);
        }
      }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

    });
  }).catch((err) => {
    console.log(err);
    return false;
  })
}

export async function checkIf_surveyCatDone(storeData1, SurveyId, CategoryId, ShowCat1) {
  var d1 = new Date();
  var d2 = moment(d1).format('MM/DD/YYYY');
  return new Promise((resolve, reject) => {
    try {
      db.transaction(async function (txn) {

        let { StoreId } = storeData1;

        // get inserted audit
        let selectlist = ` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,T.SubCategoryId,T.SubCategory,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids `;
        let join = ` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
        let join2 = ` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID and T.SubCategoryId=T1.SUB_CATEGORY_ID And T.QuestionId=T1.QUESTION_ID`;
        let q2 = `Select ${selectlist} FROM Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' AND T1.VISIT_DATE= '${d2}' AND T1.SURVEY_ID=${SurveyId} and  T1.ANSWER_ID Is Not NULL `;
        if (ShowCat1 == true) {
          q2 += ` AND  T1.CATEGORY_ID=${CategoryId} `;
        }
        q2 += ` ORDER BY T.SubCategorySequence `;

        await txn.executeSql(q2, [], async function (txn2, txnres) {

          if (txnres.rows.length > 0) {
            resolve(true);
          }
          else {
            resolve(false);
          }

        }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

      });

    }
    catch (err) {
      console.log('checkIfDone Error CatSurvey', err)
      resolve(false);
    }
  }).catch((err) => {
    console.log('checkIfDone Error CatSurvey', err)
    return false;
  });
}

export async function checkIf_surveyDone(storeData1, SurveyId, ShowCat1) {
  var d1 = new Date();
  var d2 = moment(d1).format('MM/DD/YYYY');
  return new Promise((resolve, reject) => {
    try {
      db.transaction(async function (txn) {
        let { StoreId } = storeData1;
        if (ShowCat1 == true) {
          let q2 = `SELECT DISTINCT T.Category,T.CategoryId , T.CategorySequence FROM Master_SurveyQuestion T INNER JOIN Mapping_Survey M ON T.SurveyId=M.SurveyId WHERE M.StoreId='${StoreId}' and T.SurveyId='${SurveyId}' order by T.CategorySequence`;
          await txn.executeSql(q2, [], async function (txn2, txnres) {

            if (txnres.rows.length > 0) {
              let arr = [], isSurveyDone = true;
              for (var i = 0; i < txnres.rows.length; i++) {
                let data = txnres.rows.item(i);
                let isDone = await checkIf_surveyCatDone(storeData1, SurveyId, data.CategoryId, true)
                if (isDone != true) {
                  isSurveyDone = false;
                  resolve(isSurveyDone)
                  break;
                }
                else if (i == txnres.rows.length - 1) {
                  resolve(isSurveyDone)
                }
              }
            }
            else {
              resolve(true);
            }
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          let isDone = await checkIf_surveyCatDone(storeData1, SurveyId, '', false)
          resolve(isDone)
        }
      });

    }
    catch (err) {
      console.log('checkIfDone Error CatSurvey', err)
      resolve(false);
    }
  }).catch((err) => {
    console.log('checkIfDone Error CatSurvey', err)
    return false;
  });
}

export function getProgramChecklistAvailableQ(storeData, menu, program) {
  let { StoreId } = storeData;
  let { ProgramId } = program;
  console.log("program:", program);
  let q = "";
  let join1 = `inner join Mapping_StoreProgram s on w.ProgramDefinitionId=s.ProgramDefinitionId `;
  let join2 = `inner join Mapping_StoreAuditGrading mg on s.ProgramDefinitionId=mg.ProgramDefinitionId and s.StoreId = mg.StoreId`;
  q = `select mg.* from Master_ProgramDefinition w ${join1} ${join2} where s.StoreId='${StoreId}' and w.MenuId='${menu.MenuId}' and w.ProgramId='${ProgramId}' `;
  return q;
}

export function Q_getContractFormStoresList(props) {
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let join1 = "inner join Master_ProgramDefinition w on w.ProgramDefinitionId=mp.ProgramDefinitionId and w.ProgramId=mp.ProgramId ";
  // let join2="inner join Mapping_StoreProgram mp on mp.StoreId=jp.StoreId ";
  let join2 = "inner join Mapping_ContractForm mp on mp.StoreId=jp.StoreId ";
  let mapq = `select DISTINCT jp.*,'Mapping_JourneyPlan' as JcpType from Mapping_JourneyPlan jp ${join2} ${join1} where jp.VisitDate='${d2}'`;
  let adhoc_q = `select DISTINCT jp.*,'Adhoc_JourneyPlan' as JcpType from Adhoc_JourneyPlan jp ${join2} ${join1} where jp.VisitDate='${d2}'`;
  let NonMer_q = `select DISTINCT jp.*,'NonMerchandising_JourneyPlan' as JcpType from NonMerchandising_JourneyPlan jp ${join2} ${join1} where jp.VisitDate='${d2}'`;
  let NonProg_q = `select DISTINCT jp.*,'NonProgram_JourneyPlan' as JcpType from NonProgram_JourneyPlan jp ${join2} ${join1} where jp.VisitDate='${d2}'`;
  let StoreSearch_q = `select DISTINCT jp.*,'StoreSearch_JourneyPlan' as JcpType from StoreSearch_JourneyPlan jp ${join2} ${join1} where jp.VisitDate='${d2}'`;
  let JPRoute_q = `select DISTINCT jp.*,'JourneyPlan_RouteWise' as JcpType from JourneyPlan_RouteWise jp ${join2} ${join1} where jp.VisitDate='${d2}'`;

  let q = mapq + ' UNION ' + adhoc_q;
  if (props.ShowNonMerList == true) {
    q += ' UNION ' + NonMer_q;
  }
  if (props.ShowNonProgram == true) {
    q += ' UNION ' + NonProg_q;
  }
  if (props.ShowStoreSearch == true) {
    q += ' UNION ' + StoreSearch_q;
  }
  if (props.ShowBeatPlanList == true) {
    q += ' UNION ' + JPRoute_q;
  }

  return q;
}

export function Q_getContractFormPrograms(storeData) {
  let { JcpType, StoreId } = storeData;
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let join1 = "inner join Master_ProgramDefinition w on w.ProgramDefinitionId=mp.ProgramDefinitionId and w.ProgramId=mp.ProgramId ";
  let join2 = "inner join Mapping_ContractForm mp on mp.StoreId=jp.StoreId ";
  let join3 = `Left outer join ${AppTables.CONTRACT_FORM} cf on mp.ProgramId=cf.PROGRAM_ID and mp.StoreId=cf.STORE_ID and mp.ProgramDefinitionId=cf.PROGRAM_DEFINITION_ID `;
  let q = `select w.ProgramDefinitionId,w.ProgramId,w.ChildName as ProgramName,mp.ContractFormStatus,'0' as DataDoneCount,(CASE WHEN cf.STORE_ID is not null THEN 1 ELSE 0 END) as IsDataExists from ${JcpType} jp ${join2} ${join1} ${join3} where jp.VisitDate='${d2}' and jp.StoreId='${StoreId}' order by w.ChildName`;
  return q;
}