feat(lstv2 move): moved lstv2 into this app to keep them combined and easier to maintain

This commit is contained in:
2025-09-19 22:22:05 -05:00
parent caf2315191
commit e4477402ad
847 changed files with 165801 additions and 0 deletions

View File

@@ -0,0 +1,238 @@
import sql from "mssql";
import { prodSqlConfig } from "./utils/prodServerConfig.js";
import { createLog } from "../logger/logger.js";
import { db } from "../../../database/dbclient.js";
import { settings } from "../../../database/schema/settings.js";
import { eq } from "drizzle-orm";
import { installed } from "../../index.js";
import { checkHostnamePort } from "../../globalUtils/pingServer.js";
import { serverSettings } from "../server/controller/settings/getSettings.js";
let pool: any;
let connected: boolean = false;
export const initializeProdPool = async () => {
if (!installed) {
createLog(
"info",
"lst",
"sqlProd",
"The server was not installed will reconnect in 5 seconds"
);
setTimeout(() => {
initializeProdPool();
}, 5 * 1000);
return { success: false, message: "The server is not installed." };
}
// const dbServer = await db
// .select()
// .from(settings)
// .where(eq(settings.name, "dbServer"));
// the move to the go version for settings
const dbServer = serverSettings.filter(
(n: any) => n.name === "dbServer"
) as any;
const serverUp = await checkHostnamePort(`${dbServer[0].value}:1433`);
if (!serverUp) {
createLog(
"error",
"lst",
"server",
`The sql ${dbServer[0].value} is not reachable`
);
return {
success: false,
message: `The sql ${dbServer[0].value} is not reachable`,
data: [],
};
}
// make sure the server is not set to localhost this will prevent some weird issues later but can be localhost on the dev
// const serverLoc = await db
// .select()
// .from(settings)
// .where(eq(settings.name, "dbServer"));
const serverLoc = serverSettings.filter(
(n: any) => n.name === "dbServer"
) as any;
if (
serverLoc[0].value === "localhost" &&
process.env.NODE_ENV !== "development"
) {
createLog(
"error",
"lst",
"sqlProd",
"The server is set to localhost, and you are not in development mode."
);
return {
success: false,
message:
"The server is set to localhost, and you are not in development mode.",
data: [],
};
}
// if you were restarting from the endpoint you get this lovely error
if (connected) {
createLog("error", "lst", "sqlProd", "There is already a connection.");
return { success: false, message: "There is already a connection." };
}
try {
const config = await prodSqlConfig();
pool = await sql.connect(config!);
createLog(
"info",
"lst",
"sqlProd",
`Connected to ${config?.server}, and looking at ${config?.database}`
);
connected = true;
return {
success: true,
message: "The sql server connection has been closed",
};
} catch (error) {
createLog(
"error",
"lst",
"sqlProd",
`${JSON.stringify(
error
)}, "There was an error connecting to the pool."`
);
throw new Error("There was an error closing the sql connection");
}
};
export const closePool = async () => {
if (!connected) {
createLog(
"error",
"lst",
"sqlProd",
"There is no connection a connection."
);
return { success: false, message: "There is already a connection." };
}
try {
await pool.close();
createLog("info", "lst", "sqlProd", "Connection pool closed");
connected = false;
return {
success: true,
message: "The sql server connection has been closed",
};
} catch (error) {
createLog(
"error",
"lst",
"sqlProd",
`${JSON.stringify(
error
)}, "There was an error closing the sql connection"`
);
throw new Error("There was an error closing the sql connection");
}
};
export async function query(queryToRun: string, name: string) {
/**
* Just an extra catch incase someone tried to run a query while we were not connected to the server or sql server
*/
// const dbServer = await db
// .select()
// .from(settings)
// .where(eq(settings.name, "dbServer"));
const dbServer = serverSettings.filter(
(n: any) => n.name === "dbServer"
) as any;
const serverUp = await checkHostnamePort(`${dbServer[0].value}:1433`);
if (!serverUp) {
createLog(
"error",
"lst",
"server",
`The sql ${dbServer[0].value} is not reachable`
);
return {
success: false,
message: `The sql ${dbServer[0].value} is not reachable`,
data: [],
};
}
if (!connected) {
createLog(
"error",
"lst",
"server",
`The sql ${dbServer[0].value} is not connected`
);
return {
success: false,
message: `The sql ${dbServer[0].value} is not not connected`,
data: [],
};
}
/**
* We no longer need to send over the plant token change as we do it inside the query function.
*/
// const plantToken = await db
// .select()
// .from(settings)
// .where(eq(settings.name, "plantToken"));
const plantToken = serverSettings.filter(
(n: any) => n.name === "plantToken"
) as any;
const query = queryToRun.replaceAll("test1", plantToken[0].value);
try {
const result = await pool.request().query(query);
return {
success: true,
message: `Query results for: ${name}`,
data: result.recordset,
};
} catch (error: any) {
if (error.code === "ETIMEOUT") {
createLog(
"error",
"lst",
"sqlProd",
`${JSON.stringify(
error
)}, ${name} did not run due to a timeout.`
);
//throw new Error(`${name} query did not run due to a timeout.`);
return {
success: false,
message: `${name} query did not run due to a timeout.`,
data: [],
};
}
if (error.code === "EREQUEST") {
// throw new Error(
// `${name} encoutnered an error ${error.originalError.info.message}`
// );
return {
success: false,
message: `${name} encoutnered an error ${error.originalError.info.message}`,
data: [],
};
}
//console.log(error.originalError.info.message);
//EREQUEST
//throw new Error(`${name} encoutnered an error ${error.code}`);
}
}

View File

@@ -0,0 +1,175 @@
export const activeArticle = `
use AlplaPROD_test1
SELECT V_Artikel.IdArtikelvarianten,
V_Artikel.Bezeichnung,
V_Artikel.ArtikelvariantenTypBez,
V_Artikel.PreisEinheitBez,
case when sales.price is null then 0 else sales.price end as salesPrice,
TypeOfMaterial=CASE
WHEN
V_Artikel.ArtikelvariantenTypBez LIKE'%Additive'
Then 'AD'
when V_Artikel.ArtikelvariantenTypBez Like '%Masterbatch'
THEN 'MB'
WHEN V_Artikel.ArtikelvariantenTypBez ='Pallet' or
V_Artikel.ArtikelvariantenTypBez ='Top' or
V_Artikel.ArtikelvariantenTypBez ='Bags' or
V_Artikel.ArtikelvariantenTypBez ='Bag' or
V_Artikel.ArtikelvariantenTypBez ='Stretch Wrap' or
V_Artikel.ArtikelvariantenTypBez ='Stretch Film' or
V_Artikel.ArtikelvariantenTypBez ='Banding Materials' or
V_Artikel.ArtikelvariantenTypBez ='Carton' or
V_Artikel.ArtikelvariantenTypBez ='Re-Shipper Box' or
V_Artikel.ArtikelvariantenTypBez ='Label' or
V_Artikel.ArtikelvariantenTypBez ='Pallet Label' or
V_Artikel.ArtikelvariantenTypBez ='Carton Label' or
V_Artikel.ArtikelvariantenTypBez ='Liner' or
V_Artikel.ArtikelvariantenTypBez ='Dose Cup' or
V_Artikel.ArtikelvariantenTypBez ='Metal Cage' or
V_Artikel.ArtikelvariantenTypBez ='Spout' or
V_Artikel.ArtikelvariantenTypBez = 'Slip Sheet' or
V_Artikel.ArtikelvariantenTypBez = 'Palet' or
V_Artikel.ArtikelvariantenTypBez = 'LID' or
V_Artikel.ArtikelvariantenTypBez= 'Metal' or
V_Artikel.ArtikelvariantenTypBez= 'Corner post' or
V_Artikel.ArtikelvariantenTypBez= 'Bottle Label' or
V_Artikel.ArtikelvariantenTypBez = 'Paper label' or
V_Artikel.ArtikelvariantenTypBez = 'Banding' or
V_Artikel.ArtikelvariantenTypBez = 'Glue' or
V_Artikel.ArtikelvariantenTypBez = 'Top Frame' or
V_Artikel.ArtikelvariantenTypBez = 'IML Label' or
V_Artikel.ArtikelvariantenTypBez = 'Purch EBM Bottle' or
V_Artikel.ArtikelvariantenTypBez = 'Purchased Spout' or
V_Artikel.ArtikelvariantenTypBez = 'Gaylord' or
V_Artikel.ArtikelvariantenTypBez = 'Misc. Packaging' or
V_Artikel.ArtikelvariantenTypBez = 'Sleeve' or
V_Artikel.ArtikelvariantenTypBez = 'Plastic Bag' or
V_Artikel.ArtikelvariantenTypBez = 'Purch Spout' or
V_Artikel.ArtikelvariantenTypBez = 'Seal' or
V_Artikel.ArtikelvariantenTypBez = 'Tape' or
V_Artikel.ArtikelvariantenTypBez = 'Box' or
V_Artikel.ArtikelvariantenTypBez = 'Label IML' or
V_Artikel.ArtikelvariantenTypBez = 'Pallet Runner'
THEN 'PKG'
WHEN V_Artikel.ArtikelvariantenTypBez='HD-PE' or
V_Artikel.ArtikelvariantenTypBez='HD-PE PCR' or
V_Artikel.ArtikelvariantenTypBez='HD-PP' or
V_Artikel.ArtikelvariantenTypBez= 'PP' or
V_Artikel.ArtikelvariantenTypBez LIKE '%PCR' or
V_Artikel.ArtikelvariantenTypBez= 'LDPE' or
V_Artikel.ArtikelvariantenTypBez= 'PP' or
V_Artikel.ArtikelvariantenTypBez= 'HDPE' or
V_Artikel.ArtikelvariantenTypBez= 'PET' or
V_Artikel.ArtikelvariantenTypBez= 'PET-P'
THEN 'MM'
WHEN
V_Artikel.ArtikelvariantenTypBez='HDPE-Waste' or
V_Artikel.ArtikelvariantenTypBez='$Waste Container' or
V_Artikel.ArtikelvariantenTypBez='Mixed-Waste' or
V_Artikel.ArtikelvariantenTypBez LIKE'%-Waste%'
THEN 'Waste'
WHEN
V_Artikel.ArtikelvariantenTypBez = 'Bottle' or
V_Artikel.ArtikelvariantenTypBez = 'SBM Bottle' or
V_Artikel.ArtikelvariantenTypBez = 'EBM Bottle' or
V_Artikel.ArtikelvariantenTypBez = 'ISBM Bottle' or
V_Artikel.ArtikelvariantenTypBez = 'Decorated Bottle'
THEN 'Bottle'
WHEN V_Artikel.ArtikelvariantenTypBez = 'Preform'
Then 'Preform'
When
V_Artikel.ArtikelvariantenTypBez = 'Purchased Preform' or
V_Artikel.ArtikelvariantenTypBez = 'Purchased Caps' or
V_Artikel.ArtikelvariantenTypBez = 'Purchased_preform'
THEN 'Purchased_preform'
When
V_Artikel.ArtikelvariantenTypBez = 'Closures' or
V_Artikel.ArtikelvariantenTypBez = 'Cap'
THEN 'Caps'
When
V_Artikel.ArtikelvariantenTypBez = 'Dummy'
THEN 'Not used'
ELSE 'Item not defined' END
,V_Artikel.IdArtikelvariantenTyp,
Round(V_Artikel.ArtikelGewicht, 3) as Article_Weight,
IdAdresse,
AdressBez,
AdressTypBez,
ProdBereichBez,
FG=case when
V_Artikel.ProdBereichBez = 'SBM' or
V_Artikel.ProdBereichBez = 'IM-Caps' or
V_Artikel.ProdBereichBez = 'IM-PET' or
V_Artikel.ProdBereichBez = 'PRINT OFFICE' or
V_Artikel.ProdBereichBez = 'EBM' or
V_Artikel.ProdBereichBez = 'ISBM' or
V_Artikel.ProdBereichBez = 'IM-Finishing'
Then 'FG'
Else 'not Defined Profit Center'
end,
V_Artikel.Umlaeufe as num_of_cycles,
V_FibuKonten_BASIS.FibuKontoNr as CostsCenterId,
V_FibuKonten_BASIS.Bezeichnung as CostCenterDescription,
sales.[KdArtNr] as CustomerArticleNumber,
sales.[KdArtBez] as CustomerArticleDescription,
round(V_Artikel.Zyklus, 2) as CycleTime,
Sypronummer as salesAgreement,
V_Artikel.ProdArtikelBez as ProductFamily
,REPLACE(pur.UOM,'UOM:','') as UOM
--,*
FROM dbo.V_Artikel (nolock)
join
dbo.V_Artikelvarianten (nolock) on dbo.V_Artikel.IdArtikelvarianten =
dbo.V_Artikelvarianten.IdArtikelvarianten
join
dbo.V_FibuKonten_BASIS (nolock) on dbo.V_Artikelvarianten.IdFibuKonto =
dbo.V_FibuKonten_BASIS.IdFibuKonto
-- adding in the sales price
left join
(select * from
(select
ROW_NUMBER() OVER (PARTITION BY IdArtikelvarianten ORDER BY GueltigabDatum DESC) AS RN,
IdArtikelvarianten as av
,GueltigabDatum as validDate
,VKPreis as price
,[KdArtNr]
,[KdArtBez]
--,*
from dbo.T_HistoryVK (nolock)
where
--GueltigabDatum > getDate() - 120
--and
Aktiv = 1
and StandardKunde = 1 -- default address
) a
where RN = 1) as sales
on dbo.V_Artikel.IdArtikelvarianten = sales.av
/* adding the purchase price info */
left join
(select * from
(select
ROW_NUMBER() OVER (PARTITION BY IdArtikelvarianten ORDER BY GueltigabDatum DESC) AS RN,
IdArtikelvarianten as av
,GueltigabDatum as validDate
,EKPreis as price
,LiefArtNr as supplierNr
,case when Bemerkung is not null and Bemerkung like '%UOM:%' then LEFT(Bemerkung, CHARINDEX(' ', Bemerkung)) else 'UOM:1' end as UOM
,Bemerkung
--,*
from dbo.T_HistoryEK (nolock)
where
StandardLieferant = 1 -- default address
) a
where RN = 1) as pur
on dbo.V_Artikel.IdArtikelvarianten = pur.av
where V_Artikel.aktiv = 1
order by V_Artikel.IdArtikelvarianten /*, TypeOfMaterial */
`;

View File

@@ -0,0 +1,46 @@
export const customerInvNoHold = `
select x.idartikelVarianten as av
,ArtikelVariantenAlias as Alias
--x.Lfdnr as RunningNumber,
--,round(sum(EinlagerungsMengeVPKSum),0) as Total_Pallets
--,sum(EinlagerungsMengeSum) as Total_PalletQTY
,round(sum(VerfuegbareMengeVPKSum),0) as Avalible_Pallets
,sum(VerfuegbareMengeSum) as Avaliable_PalletQTY
,sum(case when c.Description LIKE '%COA%' then GesperrteMengeVPKSum else 0 end) as COA_Pallets
,sum(case when c.Description LIKE '%COA%' then GesperrteMengeSum else 0 end) as COA_QTY
--,sum(case when c.Description NOT LIKE '%COA%' then GesperrteMengeVPKSum else 0 end) as Held_Pallets
--,sum(case when c.Description NOT LIKE '%COA%' then GesperrteMengeSum else 0 end) as Held_QTY
,IdProdPlanung as Lot
--,IdAdressen
--,x.AdressBez
--,*
from [AlplaPROD_test1].dbo.[V_LagerPositionenBarcodes] (nolock) x
left join
[AlplaPROD_test1].dbo.T_EtikettenGedruckt (nolock) on
x.Lfdnr = T_EtikettenGedruckt.Lfdnr AND T_EtikettenGedruckt.Lfdnr > 1
left join
(SELECT *
FROM [AlplaPROD_test1].[dbo].[T_BlockingDefects] (nolock) where Active = 1) as c
on x.IdMainDefect = c.IdBlockingDefect
/*
The data below will be controlled by the user in excell by default everything will be passed over
IdAdressen = 3
*/
where IdArtikelTyp = 1
and x.IdWarenlager not in (6, 1)
--and IdAdressen
--and x.IdWarenlager in (14,15)
group by x.IdArtikelVarianten
,ArtikelVariantenAlias
,IdProdPlanung
--,c.Description
,IdAdressen
,x.AdressBez
--, x.Lfdnr
order by x.IdArtikelVarianten
`;

View File

@@ -0,0 +1,72 @@
export const deliveryByDateRange = `
use AlplaPROD_test1
DECLARE @StartDate DATE = '[startDate]' -- 2025-1-1
DECLARE @EndDate DATE = '[endDate]' -- 2025-1-31
select * from
(select (select wert from dbo.T_SystemParameter where Bezeichnung = 'Werkskuerzel') as Plant,
AuftragsNummer as OrderNumber,
PositionsNummer as CustomerLineNumber,
AbrufNummer as CustomerReleaseNumber,
CONVERT(date, AbrufLiefertermin) as DeliveryDate,
CONVERT(DATE,JournalDatum) Bol_PrintDate,
AbrufMenge AS OrderQuantity,
AbrufMengeVPK as OrderPallets,
GelieferteMenge AS DeliveredQTY,
GelieferteMengeVPK as DeliverdPallets,
JournalNummer as BOLNum,
ProdArtikelBez AS ProductFamily,
dbo.V_LadePlanungenLadeAuftragAbruf.AbrufIdKundenAdresse AS IdCustomer,
dbo.V_LadePlanungenLadeAuftragAbruf.AdressBez AS CustName,
dbo.T_EAIJournal.IdJournalStatus as bolStatus,
V_TrackerAuftragsAbrufe.IdAuftragsAbruf as releaseNum,
V_LadePlanungenLadeAuftragAbruf.IdLadeAuftrag as truckPostion
,'Base Plant' as plantType
from dbo.V_TrackerAuftragsAbrufe (nolock)
left join
dbo.V_LadePlanungenLadeAuftragAbruf on V_TrackerAuftragsAbrufe.IdAuftragsAbruf =
dbo.V_LadePlanungenLadeAuftragAbruf.AbrufIdAuftragsAbruf
left join
dbo.T_EAIJournal on dbo.V_LadePlanungenLadeAuftragAbruf.IdLadeAuftrag =
dbo.T_EAIJournal.IdLadeAuftrag
left join
dbo.V_ArtikelKomplett on V_TrackerAuftragsAbrufe.IdArtikelVarianten =
dbo.V_ArtikelKomplett.IdArtikelvarianten
where GelieferteMengeVPK > 0 AND (
AbrufLiefertermin IS NULL
OR CONVERT(date, JournalDatum) BETWEEN @StartDate AND @EndDate
)
/*in house*/
union all
select top (50) (select wert from dbo.T_SystemParameter where Bezeichnung = 'Werkskuerzel') as Plant
,[KundenAuftragsNummer] as OrderNumber
,[KundenPositionsNummer] as CustomerLineNumber
, null as CustomerReleaseNumber
,CONVERT(date, i.Add_Date) as DeliveryDate
,CONVERT(DATE,i.Upd_Date) Bol_PrintDate
,null AS OrderQuantity
,null as OrderPallets
,LieferMengeVereinbart AS DeliveredQTY
,null as DeliverdPallets
,JournalNummer as BOLNum
,null AS ProductFamily
,IdAdresse AS IdCustomer
,null AS CustName
,null as bolStatus
,null as releaseNum
,null as truckPostion
,'In-House' as plantType
--,*
from [dbo].[T_InhouseLieferungen] as i (nolock)
where CONVERT(date, Upd_Date) BETWEEN @StartDate AND @EndDate
) x
order by Bol_PrintDate desc
`;

View File

@@ -0,0 +1,17 @@
export const fakeEDIUpdate = `
Select LEFT(ArtikelVariantenAlias, charindex(' ', ArtikelVariantenAlias) - 1) CustomerArticleNumber,
cast(AuftragsNummer as varchar) AS CustomerOrderNumber,
cast(PositionsNummer as varchar)as CustomerLineNumber,
cast(AbrufNummer as varchar)AS CustomerRealeaseNumber,
AbrufMenge AS Quantity,
AbrufLiefertermin AS DeliveryDate,
IdAdresse AS CustomerID,
' ' AS Remark
--,*
FROM AlplaPROD_test1.dbo.V_TrackerAuftragsAbrufe
WHERE AbrufStatus = 1
--AND AbrufLiefertermin > DATEADD(d, -1, getdate())
AND GelieferteMenge = 0
--and IdAdresse = 14
ORDER BY AbrufLiefertermin
`;

View File

@@ -0,0 +1,65 @@
export const financeAudit = `
use AlplaPROD_test1
select
(select wert from dbo.T_SystemParameter where Bezeichnung = 'Werkskuerzel') as Plant,
b.IdArtikelVarianten
,ArtikelVariantenAlias
,ArtikelVariantenBez
,a.Bezeichnung as articleType
,sum(EinlagerungsMengeVPKSum) totalPal
,sum(EinlagerungsMengeSum) totalPieces
--,ProduktionsDatumMin
,pp.VKPreis as salesPrice
,sp.EKPreis as purhcasePrice
,convert(date, ProduktionsDatumMin, 111) as bookinDate
,DATEDIFF(DAY, convert(date, ProduktionsDatumMin, 111), getdate()) as aged
--,*
from dbo.V_LagerPositionenBarcodes (nolock) b
/* purhcase price */
left join
(select * from (select
IdArtikelvarianten
,VKPreis
,ROW_NUMBER() OVER (PARTITION BY IdArtikelVarianten ORDER BY gueltigabDatum DESC) AS rn
--,*
from T_HistoryVK (nolock))c
where rn = 1) as pp on
b.IdArtikelVarianten = pp.IdArtikelvarianten
/* sales price */
left join
(select * from (select
IdArtikelvarianten
,EKPreis
,ROW_NUMBER() OVER (PARTITION BY IdArtikelVarianten ORDER BY gueltigabDatum DESC) AS rn
--,*
from T_HistoryEK (nolock) )x
where rn = 1) sp on
sp.IdArtikelvarianten = b.IdArtikelVarianten
/* article type */
left join
T_Artikeltyp (nolock) a
on a.IdArtikelTyp = b.IdArtikelTyp
where IdWarenlager not in (1,5,6)
and ProduktionsDatumMin < '[date]' -- '2025-05-31'
group by b.IdArtikelVarianten
,ArtikelVariantenAlias
,ArtikelVariantenBez
,convert(date, ProduktionsDatumMin, 111)
,pp.VKPreis
,sp.EKPreis
,a.Bezeichnung
order by IdArtikelVarianten
`;

View File

@@ -0,0 +1,28 @@
export const openOrders = `
Select LEFT(ArtikelVariantenAlias, charindex(' ', ArtikelVariantenAlias) - 1) customerItemNumber,
x.IdArtikelVarianten AS article,
ArtikelVariantenAlias AS articleDescription,
IdAuftragsAbruf as releaseNumber,
AuftragsNummer AS header,
PositionsNummer as customerLineItemNo,
AbrufNummer AS customerReleaseNumber,
AbrufMengeVPK AS pallets,
AbrufMenge AS qty,
y.TradeUnits AS cartons,
IdAdresse AS customerID,
LieferAdressBez as DeliveryAddressDescription,
AbrufLadeDatum AS loadingDate,
AbrufLiefertermin AS deliveryDate
,Remark
--,OrderStatus = 'loading'
--,*
FROM alplaprod_test1.dbo.V_TrackerAuftragsAbrufe (nolock) x
left join
[test1_AlplaPROD2.0_Read].[order].[Release] (nolock) y on
x.IdAuftragsAbruf = y.ReleaseNumber
--WHERE AbrufStatus = 1 AND AbrufLiefertermin < getdate() + 5 AND GelieferteMenge = 0
WHERE AbrufStatus = 1 AND AbrufLiefertermin between getDate() + -[sDay] and getdate() + [eDay] AND GelieferteMenge = 0
ORDER BY AbrufLiefertermin
`;

View File

@@ -0,0 +1,34 @@
const pastBOLInfo = `
select (select wert from dbo.T_SystemParameter where Bezeichnung = 'Werkskuerzel') as Plant,
AuftragsNummer as OrderNumber,
PositionsNummer as CustomerLineNumber,
AbrufNummer as CustomerReleaseNumber,
CONVERT(date, AbrufLiefertermin) as DeliveryDate,
CONVERT(DATE,JournalDatum) Bol_PrintDate,
AbrufMenge AS OrderQuantity,
AbrufMengeVPK as OrderPallets,
GelieferteMenge AS DeliveredQTY,
GelieferteMengeVPK as DeliverdPallets,
JournalNummer as BOLNum,
ProdArtikelBez AS ProductFamily,
dbo.V_LadePlanungenLadeAuftragAbruf.AbrufIdKundenAdresse AS IdCustomer,
dbo.V_LadePlanungenLadeAuftragAbruf.AdressBez AS CustName,
dbo.T_EAIJournal.IdJournalStatus as bolStatus,
dbo.V_TrackerAuftragsAbrufe.IdArtikelvarianten as av,
dbo.V_TrackerAuftragsAbrufe.ArtikelVariantenAlias as alias,
ladeauftragidstapler as remark
--,*
from dbo.V_TrackerAuftragsAbrufe (nolock)
left join
dbo.V_LadePlanungenLadeAuftragAbruf on V_TrackerAuftragsAbrufe.IdAuftragsAbruf =
dbo.V_LadePlanungenLadeAuftragAbruf.AbrufIdAuftragsAbruf
left join
dbo.T_EAIJournal on dbo.V_LadePlanungenLadeAuftragAbruf.IdLadeAuftrag =
dbo.T_EAIJournal.IdLadeAuftrag
left join
dbo.V_ArtikelKomplett on V_TrackerAuftragsAbrufe.IdArtikelVarianten =
dbo.V_ArtikelKomplett.IdArtikelvarianten
where GelieferteMengeVPK > 0 and CONVERT(date, AbrufLiefertermin) between '2025-05-10' and '2025-05-20'
order by AbrufLiefertermin
`;

View File

@@ -0,0 +1,12 @@
export const plantInfo = `
select werkkurzbez as plantToken,
gln,
IdAdressen as addressId,
Bezeichnung as addressDecriptuion,
Strasse as streetAddress,
plz as zipcode,
ort as cityState
--,*
from alplaprod_test1.dbo.T_Adressen where werkkurzbez = '[token]'
`;

View File

@@ -0,0 +1,88 @@
// this query pulls all the inventory except the inv locations.
export const totalInvNoRn = `
select
x.idartikelVarianten as av,
x.ArtikelVariantenAlias as Alias
--x.Lfdnr as RunningNumber,
,round(sum(EinlagerungsMengeVPKSum),0) as Total_Pallets
,sum(EinlagerungsMengeSum) as Total_PalletQTY
,round(sum(VerfuegbareMengeVPKSum),0) as Avalible_Pallets
,sum(VerfuegbareMengeSum) as Avaliable_PalletQTY
,sum(case when c.Description LIKE '%COA%' then GesperrteMengeVPKSum else 0 end) as COA_Pallets
,sum(case when c.Description LIKE '%COA%' then GesperrteMengeSum else 0 end) as COA_QTY
,sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeVPKSum else 0 end) as Held_Pallets
,sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeSum else 0 end) as Held_QTY
,sum(case when x.WarenLagerLagerTyp = 8 then VerfuegbareMengeSum else 0 end) as Consigment
,IdProdPlanung as Lot
----,IdAdressen,
,x.AdressBez
--,*
from [AlplaPROD_test1].dbo.[V_LagerPositionenBarcodes] (nolock) x
left join
[AlplaPROD_test1].dbo.T_EtikettenGedruckt as l(nolock) on
x.Lfdnr = l.Lfdnr AND l.Lfdnr > 1
left join
(SELECT *
FROM [AlplaPROD_test1].[dbo].[T_BlockingDefects] where Active = 1) as c
on x.IdMainDefect = c.IdBlockingDefect
/*
The data below will be controlled by the user in excell by default everything will be passed over
IdAdressen = 3
*/
where /*IdArtikelTyp = 1 and */x.IdWarenlager not in (6, 1)
group by x.idartikelVarianten, ArtikelVariantenAlias, c.Description
--,IdAdressen
,x.AdressBez
,IdProdPlanung
--, x.Lfdnr
order by x.IdArtikelVarianten
`;
export const totalInvRn = `
select x.idartikelVarianten as av,
ArtikelVariantenAlias as Alias,
x.Lfdnr as RunningNumber,
round(sum(EinlagerungsMengeVPKSum),0) as Total_Pallets,
sum(EinlagerungsMengeSum) as Total_PalletQTY,
round(sum(VerfuegbareMengeVPKSum),0) as Avalible_Pallets,
sum(VerfuegbareMengeSum) as Avaliable_PalletQTY,
sum(case when c.Description LIKE '%COA%' then GesperrteMengeVPKSum else 0 end) as COA_Pallets,
sum(case when c.Description LIKE '%COA%' then GesperrteMengeSum else 0 end) as COA_QTY,
sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeVPKSum else 0 end) as Held_Pallets,
sum(case when c.Description NOT LIKE '%COA%' or x.IdMainDefect = -1 then GesperrteMengeSum else 0 end) as Held_QTY
,IdProdPlanung as Lot
,IdAdressen,
x.AdressBez
--,*
from [AlplaPROD_test1].dbo.[V_LagerPositionenBarcodes] (nolock) x
left join
[AlplaPROD_test1].dbo.T_EtikettenGedruckt as l(nolock) on
x.Lfdnr = l.Lfdnr AND l.Lfdnr > 1
left join
(SELECT *
FROM [AlplaPROD_test1].[dbo].[T_BlockingDefects] where Active = 1) as c
on x.IdMainDefect = c.IdBlockingDefect
/*
The data below will be controlled by the user in excell by default everything will be passed over
IdAdressen = 3
*/
where IdArtikelTyp = 1 and x.IdWarenlager not in (6, 1)
group by x.idartikelVarianten, ArtikelVariantenAlias, c.Description, IdAdressen,
x.AdressBez , x.Lfdnr,
IdProdPlanung -- this will be flagged as being removed when we do historical.
order by x.IdArtikelVarianten
`;
const totalInvValue = ``;
const totalInvValueRn = ``;

View File

@@ -0,0 +1,14 @@
export const validateCityState = `
select IdAdressen addressID,
x.Bezeichnung as name,
c.Bezeichnung as deliveryCondition,
c.Kurzbezeichnung as Abbreviation,
ort as cityState
--,*
from AlplaPROD_test1.dbo.t_Adressen (nolock) x
left join
AlplaPROD_test1.[dbo].[T_Lieferkonditionen] (nolock) c
on x.IdLieferkondition = c.IdLieferkondition
WHERE c.Kurzbezeichnung not in ('exw') and ort not like '%,%'
`;

View File

@@ -0,0 +1,27 @@
export const bulkOrderArticleInfo = `
SELECT
x.HumanReadableId as av
,x.Name
,Alias
,CustomerDescription
,CustomerArticleNumber
,LoadingUnitPieces
,LoadingUnitsPerTruck
,LoadingUnitPieces * LoadingUnitsPerTruck as totalTruckLoad
FROM [test1_AlplaPROD2.0_Read].[masterData].[Article] (nolock) as x
--get the sales price stuff
left join
(select * from (select *
,ROW_NUMBER() OVER (PARTITION BY articleId ORDER BY validAfter DESC) as rn
from [test1_AlplaPROD2.0_Read].[masterData].[SalesPrice] (nolock))as b
where rn = 1) as s on
x.id = s.ArticleId
-- link pkg info
left join
[test1_AlplaPROD2.0_Read].[masterData].[PackagingInstruction] (nolock) as p on
s.PackagingId = p.id
where x.HumanReadableId in ([articles])
`;

View File

@@ -0,0 +1,15 @@
export const invoiceAddress = `
SELECT deliveryAddress.humanreadableid as deliveryAddress
,invoice.HumanReadableId as invoiceAddress
,[Default]
FROM [test1_AlplaPROD2.0_Read].[masterData].[InvoiceAddress] (nolock) as d
join
[test1_AlplaPROD2.0_Read].[masterData].[Address] deliveryAddress (nolock) on deliveryAddress.id = d.AddressId
join
[test1_AlplaPROD2.0_Read].[masterData].[Address] invoice (nolock) on invoice.id = d.InvoiceAddressId
where [Default] = 1
`;

View File

@@ -0,0 +1,26 @@
export const orderState = `
SELECT top(10000)
CustomerOrderNumber
,r.CustomerReleaseNumber
, OrderState
, r.ReleaseState
, h.CreatedByEdi
--, *
FROM [test1_AlplaPROD2.0_Read].[order].[Header] (nolock) h
/* get the line items to link to the headers */
left join
[test1_AlplaPROD2.0_Read].[order].[LineItem] (nolock) l on
l.HeaderId = h.id
/* get the releases to link to the headers */
left join
[test1_AlplaPROD2.0_Read].[order].[Release] (nolock) r on
r.LineItemId = l.id
where
--h.CreatedByEdi = 1
r.ReleaseState > 0
--and CustomerOrderNumber in ( '2358392')
`;

View File

@@ -0,0 +1,17 @@
export const lastSalesPriceCheck = `
use AlplaPROD_test1
select * from
(select IdArtikelvarianten as av,
VKPreis as salesPrice,
MPB, FWMPAlpla,
FWMPB,
ROW_NUMBER() over(partition by IdArtikelVarianten order by gueltigabdatum desc) rn,
convert(date, gueltigabdatum, 120) as validDate
from dbo.T_HistoryVK (nolock)
where convert(date, gueltigabdatum, 120) <= '[date]' and StandardKunde = 1) a
where rn =1
order by av asc,
validDate desc
`;

View File

@@ -0,0 +1,17 @@
export const lastPurchasePrice = `
use AlplaPROD_test1
SELECT plant=(SELECT Wert FROM dbo.T_SystemParameter (nolock) WHERE (Bezeichnung = 'Werkskuerzel')),
plantName=(SELECT Wert FROM dbo.T_SystemParameter AS T_SystemParameter (nolock) WHERE (Bezeichnung = 'Mandant-intern')),*
from
(Select IdBestellung as 'Purchase order number',
IdArtikelVarianten AS AV,
BestellMenge,
BestellMengeVPK,
PreisProEinheit,
convert(varchar,Lieferdatum,23) as deliveryDate,
ROW_NUMBER() over(partition by IdArtikelVarianten order by Lieferdatum desc) rn
from dbo.V_Bestellpositionen_PURCHASE (nolock)
where PositionsStatus = '7' or PositionsStatus = '6' or PositionsStatus = '5' and convert(varchar,Lieferdatum,23) > DATEADD(year, -5, GetDate()) )a
where rn = 1
`;

View File

@@ -0,0 +1,21 @@
export const labelData = `
select x.Barcode as barcode,
Produktionslos as lot,
x.IdArtikelVarianten as article,
x.ArtikelVariantenBez as description,
m.Standort as machineLocation,
m.Bezeichnung as machineDescription,
e.IdEtikettenDrucker as printer,
x.LfdNr as runningNr
from alplaprod_test1.dbo.V_LagerPositionenBarcodes x (NOLOCK)
left join
alplaprod_test1.dbo.T_EtikettenGedruckt as e
on x.Lfdnr = e.LfdNr
left join
alplaprod_test1.dbo.T_Maschine as m on
e.IdMaschine = m.IdMaschine
where x.lfdnr = [rn]
--and x.IdWarenlager not in(6)
`;

View File

@@ -0,0 +1,7 @@
export const laneInfo = `
select IdLagerAbteilung as laneID,
Bezeichnung as laneName
from AlplaPROD_test1.dbo.T_LagerAbteilungen
where Aktiv = 1
and Bezeichnung = '[laneName]'
`;

View File

@@ -0,0 +1,4 @@
export const shiftChange = `
select top(1) convert(varchar(8) ,convert(time,startdate), 108) as shiftChange
from [test1_AlplaPROD2.0_Read].[masterData].[ShiftDefinition] where teamNumber = 1
`;

View File

@@ -0,0 +1,46 @@
export const blockQuery = `
SELECT TOP(1)
'Alert! new blocking order: #' + cast(HumanReadableId as varchar) + ' - ' + ArticleVariantDescription as subject,
cast([HumanReadableId] as varchar) as blockingNumber,
[ArticleVariantDescription] as article,
cast([CustomerHumanReadableId] as varchar) + ' - ' + [CustomerDescription] as customer,
convert(varchar(10), [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].[BlockingDate], 101) + ' - ' + convert(varchar(5), [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].[BlockingDate], 108) as blockingDate,
cast(ArticleVariantHumanReadableId as varchar) + ' - ' + ArticleVariantDescription as av,
case when [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].Remark = '' or [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].Remark is NULL then 'Please reach out to quality for the reason this was placed on hold as a remark was not entered during the blocking processs' else [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].Remark end as remark,
cast(FORMAT(TotalAmountOfPieces, '###,###') as varchar) + ' / ' + cast(LoadingUnit as varchar) as peicesAndLoadingUnits,
[test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].ProductionLotHumanReadableId as lotNumber,
cast(IdGlobalBlockingDefectsGroup as varchar) + ' - ' + BD.Description as mainDefectGroup,
cast(IdGlobalBlockingDefect as varchar) + ' - ' + MD.Description as mainDefect,
sent=0,
lot.MachineLocation as line,
HumanReadableId
FROM [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder] (nolock)
/*** Join 1.0 table to get correct id info to link ***/
join
[AlplaPROD_test1].[dbo].[T_BlockingOrders] (nolock) AS BO
on [HumanReadableId] = BO.[IdBlockingOrder]
/*** Get the main defect info ***/
Inner join
[AlplaPROD_test1].[dbo].[T_BlockingDefectsGroups] (nolock) as BD
ON BO.IdMainDefectGroup = BD.IdBlockingDefectsGroup
INNER join
[AlplaPROD_test1].[dbo].[T_BlockingDefects] as MD
ON BO.IdMainDefect = MD.IdBlockingDefect
/*** get lot info ***/
left join
(SELECT [MachineLocation]
,[MachineDescription]
,[ProductionLotHumanReadableId]
FROM [test1_AlplaPROD2.0_Reporting].[reporting_productionControlling].[ProducedLot]) as lot
on [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].ProductionLotHumanReadableId = lot.ProductionLotHumanReadableId
where [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].[BlockingDate] between getdate() - 1 and getdate() + 1
and [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockingOrder].BlockingTrigger = 1
--and HumanReadableId NOT IN ([sentBlockingOrders])
and HumanReadableId > [lastBlocking]
`;

View File

@@ -0,0 +1,9 @@
export const bow2incoming = `
select LKWNummer as truckNumber
,LKWBezeichnung as carrier
,Add_Date
from [AlplaPROD_test1].[dbo].[V_WareneingangAuftraege]
where Add_Date > DATEADD(MINUTE, -[time], getdate())
`;

View File

@@ -0,0 +1,45 @@
export const downTimeCheck = `
SELECT
[IdHistoryStillstandsereignis] as downTimeId
,DATEDIFF(MINUTE,b.[Startzeit], case when b.[Endzeit] = '1900-01-01' then getdate() else b.[Endzeit] end ) as totalDuration
--, b.[IdMaschine]
,x.[Bezeichnung] as machineAlias
--,b.[IdStillstandsGrund],
, c.CTO_Code
,c.Downtime_Description
--,b.[IdFehlermerkmal],
,case when g.DT_Group_Desc is null then 'Not assigned yet' else g.DT_Group_Desc end as groupDesc
,b.[Bemerkung] as remark
,CONVERT(VARCHAR, CAST(b.[Startzeit] AS DATETIME), 100) dtStart
,CONVERT(VARCHAR, CAST(b.[Endzeit] AS DATETIME), 100) dtEnd
,b.Upd_Date
FROM Alplaprod_test1.[dbo].[T_HistoryStillstandsereignis] (nolock)b
--get the machine info
left join
Alplaprod_test1.[dbo].[T_Maschine] (nolock)x
on b.IdMaschine = x.IdMaschine
-- add in the cto codes
left join
Alplaprod_test1.[dbo].[V_MES_Downtime_Reasons] (nolock)c
on b.IdStillstandsGrund = c.Local_Downtime_ID
left join
Alplaprod_test1.[dbo].[V_MES_Downtime_Characteristics] (nolock)g
on b.IdFehlermerkmal = g.Local_DT_Characteristic_Id
where DATEDIFF(MINUTE,b.[Startzeit],case when b.[Endzeit] = '1900-01-01' then getdate() else b.[Endzeit] end) > [dtDuration]
and b.[Startzeit] > DATEADD(day, -[daysInPast], getDate())
and b.[Endzeit] = '1900-01-01'
--adding this date check in so we dont get everything possible
and c.CTO_Code not like 'a%'
and c.CTO_Code not like 'b%'
and c.CTO_Code not like 'c%'
and c.CTO_Code not like 'd%'
and c.CTO_Code not like 'e%'
and c.CTO_Code not like 'f%'
and c.CTO_Code not like 'y%'
order by IdHistoryStillstandsereignis desc
`;

View File

@@ -0,0 +1,10 @@
export const currentInv = `
SELECT Produktionslos as lot
,Lfdnr as runningNr
,IdArtikelVarianten as av
,Barcode
,ProduktionsDatumMin as prodDate
FROM [AlplaPROD_test1].[dbo].V_LagerPositionenBarcodes t
where GesperrtAktivSum = 0 and t.IdArtikelTyp in (1)
order by ProduktionsDatumMin
`;

View File

@@ -0,0 +1,32 @@
export const shippedPallets = `
SELECT
--[IdJournalLieferPosition]
--,[IdJournalPosition]
--,[IdLadePlanung]
[Beleg] as lot
,[LfdNrJeArtikelKunde] as runningNr
,l.IdArtikelvarianten as av
,x.[Barcode]
,[ProduktionsDatum] as prodDate
--,x.[Add_User]
--,x.[Add_Date]
--,x.[Upd_User]
--,x.[Upd_Date]
--,[IdJournalWarenPosition]
--,[LieferMenge]
--,x.[SSCC_ReserveZiffer]
--,[EAN_BasisNr]
--,[Guid]
--,[LieferEinheit]
--,x.[Bestrahlungsnummer]
FROM [AlplaPROD_test1].[dbo].[T_EAIJournalLieferPosition] x
--where Barcode = '1000000000000000000000000000000001144380'
left join
[AlplaPROD_test1].[dbo].[T_EtikettenGedruckt] l on
x.LfdNrJeArtikelKunde = l.LfdNr
where x.Add_Date between dateadd(hour, -1, getDate()) and getDate() -- this is looking only in the last hour
order by [ProduktionsDatum]
`;

View File

@@ -0,0 +1,17 @@
export const palletsRemovedAswaste = `
select * from (select IdArtikelVarianten as av
,ArtikelVariantenAlias as alias
,Lfdnr as runningnumber
,case when GesperrtAktivSum = 1 then 'Blocked' else 'Released' end as palletStatus
,BewegungsDatumMax as lastMovingDate
--,*
from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes (nolock) )x
where runningnumber in (
SELECT
[HumanReadableId]
FROM [test1_AlplaPROD2.0_Reporting].[reporting_blocking].[BlockedItem] (nolock)
where state = 4
) and palletStatus = 'Released'
`;

View File

@@ -0,0 +1,31 @@
export const shortageBookings = `
use AlplaPROD_test1
Declare @range int = [time] -- change this to be range in minutues you want to monitor, this shouldnt be more than the interval check so we do not see duplicates
declare @avType nvarchar(3) = '[type]' --change to blank or single to have specific ones if all the type is ignored
declare @avTypeID NVARCHAR(MAX) = '[avType]' -- this can only be 1 article now.
select
IdArtikelVarianten as materialAV
,IdArtikelTyp
,ArtikelTypBez
,ArtikelVariantenAlias as materialAlias
,CAST(Menge as varchar) as qtyShortpcs
,ProduktionsLos as productionlot
,LEFT(PARSE(Right(barcode, 39) as int), LEN(PARSE(Right(barcode, 39)as int)) - 1) as palletWithShortBookings
,m.Standort as machineNumber
,m.Bezeichnung ,m.Bezeichnung as machineAlias
,Buchungsdatum as bookingDate
from [dbo].[V_LagerBuchungen] (nolock) s
left join
dbo.T_Maschine (nolock) as m
on m.IdMaschine = s.IdMaschine
where beleg like '%$Sho%' and s.Add_Date > DATEADD(MINUTE, -@range, getdate())
and (@avType = 'all' or IdArtikelTyp in (@avTypeID))
order by ProduktionsLos
`;

View File

@@ -0,0 +1,27 @@
export let getHeaders = `
select AuftragsNummer as header,
IdAuftragsAbruf as releaseNumber,
AbrufLadeDatum AS LoadingDate,
AbrufLiefertermin as delDate
FROM alplaprod_test1.dbo.V_TrackerAuftragsAbrufe (nolock) b
left join
(
select IdAdressen addressID,
x.Bezeichnung as name,
c.Bezeichnung as deliveryCondition,
c.Kurzbezeichnung as Abbreviation
from AlplaPROD_test1.dbo.t_Adressen (nolock) x
left join
AlplaPROD_test1.[dbo].[T_Lieferkonditionen] (nolock) c
on x.IdLieferkondition = c.IdLieferkondition
) x
on b.IdAdresse = x.addressID
WHERE AbrufStatus = 1 and
--AbrufLiefertermin between DATEADD(HOUR, -[from], getdate()) and DATEADD(HOUR, [to], GETDATE()) -- this number will be grabbed from the db with a default of 24hours
AbrufLadeDatum between DATEADD(HOUR, -[from], getdate()) and DATEADD(HOUR, [to], GETDATE()) -- this number will be grabbed from the db with a default of 24hours
and x.Abbreviation not in ('exw')
and IdAuftragsAbruf not in ([exclude])
`;

View File

@@ -0,0 +1,150 @@
export let getOrderToSend = `
select * from (
Select IdAdresse as addressId,
LieferAdressBez as addressAlias,
LEFT(ArtikelVariantenAlias, charindex(' ', ArtikelVariantenAlias) - 1) item,
IdArtikelVarianten as article,
ArtikelVariantenAlias as articleAlias,
IdAuftragsAbruf as releaseNumber,
AuftragsNummer AS Header,
AuftragsNummer as CustomerLineItemNo,
AbrufNummer AS CustomerReleaseNumber,
AbrufMengeVPK AS Pallets,
AbrufMenge AS QTY,
IdAdresse AS CUSTOMERID,
AbrufLadeDatum AS LoadingDate,
AbrufLiefertermin AS DeliveryDate
,carrierAV
,singleTrip
,roundTrip
,countryAv
,zipCode
,streetAddress
,city -- split on here by ,
--,OrderStatus = 'loading'
,ac.costCenter -- also called pfc
,pkg.pkgHeight
,pkg.pkgLengh
,pkg.pkgWidth
,ROUND((ac.weight * pkg.palletCount / 1000) + pkg.totalPKGWeight,2)as pkgWeight
,AbrufStatus as status
,remark
,ac.artileType
--,*
FROM alplaprod_test1.dbo.V_TrackerAuftragsAbrufe (nolock) x
--av info
left join
(SELECT [IdArtikelvarianten] as article
,[FibuKontenKontoNr] as costCenter
,ArtikelGewicht as weight,
s.pkgId
,artikelvariantentypbez as artileType
FROM [AlplaPROD_test1].[dbo].[V_Artikelvarianten_BASIS] (nolock) x
left join
(
select * from (select
ROW_NUMBER() OVER(PARTITION BY [IdArtikelvarianten] ORDER BY gueltigabDatum DESC) AS rn
,[IdArtikelvarianten] as article
,IdVpkVorschrift as pkgId
from [AlplaPROD_test1].[dbo].[T_HistoryVK] (nolock)) a where rn = 1
) as s
on
x.[IdArtikelvarianten] = s.article
) as ac
on
x.IdArtikelVarianten = ac.article
-- transport part of query
left join
(SELECT [IdHistoryTransportkosten]
,[IdLieferadresse] as customerAddressAV
,[IdSpediteuradresse] as carrierAV
,[GueltigabDatum] as validDate
,[Einzelfahrtkosten] as singleTrip
,[Rundfahrtkosten] as roundTrip
,[EinzelfahrtkostenProKubikmeter] as singletripCostsperCubicMeter
,[RundfahrtkostenProKubikmeter] as roundSingletripCostsperCubicMeter
,[Standard] as standard
,[Aktiv] as active
--,[FWEinzelfahrtkosten]
--,[FWRundfahrtkosten]
--,[FWEinzelfahrtkostenProKubikmeter]
--,[FWRundfahrtkostenProKubikmeter]
FROM [AlplaPROD_test1].[dbo].[T_HistoryTransportkosten] (nolock)
where Standard = 1 and Aktiv = 1) as carrier
on x.IdAdresse = carrier.customerAddressAV
-- address stuff
left join
(SELECT [IdAdressen] as addressAV
,[IdAdressentyp] as addressType -- 1 customer,2 supplier, 4 transport
--,[IdZahlKond]
--,[IdMwst]
,[Bezeichnung] as addressName
,[IdStaaten] as countryAv
,[PLZ] as zipCode
,[Strasse] as streetAddress
,[PLZPostfach] as poBox
,[Postfach] as mailbox
,[Ort] as city
,[Tel] as customerPhone
,[DebNr] as debitorNr
,xy.[Bonus] as bonus
,[Bemerkung] as remark
,[Aktiv] as active
,Entfernung as distanceKM
,Transportzeit as transportTime
,IdLieferkondition as deliveryCondtionAV
,delc.deliveryContionAlias
,delc.deliveryContionAbv
--,ac.costCenter
FROM [AlplaPROD_test1].[dbo].[T_Adressen] (nolock) xy
--delivery condtion details
left join
(SELECT [IdLieferkondition] as deliveryCondtionAV
,[Bezeichnung] as deliveryContionAlias
,[Kurzbezeichnung] as deliveryContionAbv
,[Bemerkung] as deliveryContionRemark
,[Aktiv] as active
FROM [AlplaPROD_test1].[dbo].[T_Lieferkonditionen] (nolock)) as delC
on xy.IdLieferkondition = delC.deliveryCondtionAV
) as del
on
x.IdAdresse = del.addressAV
-- pkg info
left join
(
SELECT [IdVpkVorschrift] as pkgId
,[Aktiv] as active
,[Bezeichnung] as alias
,[AnzahlAVProVpk] as palletCount
,[AnzahlVpkProLKW] as totalTruck
,[AnzahlKistenProKarton]
,[BruttoGewicht] / 1000 as totalPKGWeight
--,[AnzahlAVProHE]
,[VpkDimensionenHoehe] as pkgHeight
,[VpkDimensionenBreite] as pkgWidth
,[VpkDimensionenTiefe] as pkgLengh
FROM [AlplaPROD_test1].[dbo].[V_Vpk_BASIS]
)as pkg
on
ac.pkgId = pkg.pkgId
WHERE AbrufStatus = 1
--and AbrufLiefertermin between DATEADD(HOUR, -[from], getdate()) and DATEADD(HOUR, [to], getdate())-- this number will be grabbed from the db with a default of 24hours
and AbrufLadeDatum between DATEADD(HOUR, -[from], getdate()) and DATEADD(HOUR, [to], getdate())-- this number will be grabbed from the db with a default of 24hours
and deliveryContionAbv not in ('EXW')
--ORDER BY AbrufLiefertermin)
) a
where releaseNumber = [releaseToProcess]
`;

View File

@@ -0,0 +1,9 @@
export const alplaStock = `
select IdLagerAbteilung as alpla_laneID,
LagerAbteilungKurzBez as alpla_laneDescription,
IdArtikelVarianten as Article,
ArtikelVariantenBez as description,
lfdnr as runningNumber
from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes
where IdLagerAbteilung = [laneID]
`;

View File

@@ -0,0 +1,24 @@
export const ocmeInventory = `
SELECT [ocme_laneLevelID]
,[alpla_laneID]
,[alpla_laneDescription]
,bob.SKU as Article
,bob.description
,bob.sscc
,bob.runningNumber
FROM [Alpla_Lst].[dbo].[lanes] (nolock) a
left JOIN
(Select p.SKEY,
x.y.value('(value)[1]', 'varchar(max)') AS sscc,
b.y.value('(value)[1]', 'varchar(max)') AS runningNumber,
k.l.value('(value)[1]', 'varchar(max)') AS SKU,
d.l.value('(value)[1]', 'varchar(max)') AS description
from Agv_AlplaDayton.dbo.Park p (nolock)
outer apply p.pallet_card.nodes('/*:ArrayOfClsPalletCard/*:clsPalletCard/*:PalletCardConfig/*:palletCardFieldList/*:clsPalletCardField[Name="SSCC"]') as x(y)
outer apply p.pallet_card.nodes('/*:ArrayOfClsPalletCard/*:clsPalletCard/*:PalletCardConfig/*:palletCardFieldList/*:clsPalletCardField[Name="RUNNING_NUMBER"]') as b(y)
outer apply p.pallet_card.nodes('/*:ArrayOfClsPalletCard/*:clsPalletCard/*:PalletCardConfig/*:palletCardFieldList/*:clsPalletCardField[Name= "SKU" ]') as k(l)
outer apply p.pallet_card.nodes('/*:ArrayOfClsPalletCard/*:clsPalletCard/*:PalletCardConfig/*:palletCardFieldList/*:clsPalletCardField[Name= "DESCRIPTION" ]') as d(l)) as bob
on a.ocme_laneLevelID = bob.SKEY
where alpla_laneDescription = '[lane]' and runningNumber > 1
`;

View File

@@ -0,0 +1,6 @@
export const getLanes = `
select DISTINCT alpla_laneDescription
from Alpla_Lst.dbo.lanes (nolock)
where alpla_laneDescription is not null
order by alpla_laneDescription desc
`;

View File

@@ -0,0 +1,18 @@
export const shipmentPallets = `
select TOP([totalPallets]) IdLagerAbteilung as laneId,
LagerAbteilungKurzBez as lane,
Produktionslos as lotNum,
lfdnr as runningNumber,
IdAdresse as addressID,
ProduktionsDatumMin as productionDate,
IdArtikelVarianten as article
from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes (nolock)
where IdArtikelVarianten = [article]
and LagerAbteilungKurzBez in ([lanes])
and IdWarenlager not in (1)
and GesperrtAktivSum in (0)
order by CASE
WHEN BewegungsDatumMax <= DATEADD(DAY, -[fifo], GETDATE()) THEN 0
ELSE 1
END desc
`;

View File

@@ -0,0 +1,55 @@
export const lotQuery = `
select IdMaschinen_ProdPlanung as LabelOnlineID,
IdMaschine as machineID,
MaschinenStandort as MachineLocation,
MaschinenBez as MachineDescription,
IdProdPlanung as lot,
prolink.lot as ProlinkLot,
IdArtikelvarianten as AV,
ArtikelVariantenBez as Alias,
convert(varchar, add_date, 20) as Add_Date,
Add_user,
idEtikettenDrucker as printerID,
b.name as PrinterName,
CAST(TotalPlannedLoadingUnits as float) as PlannedQTY,
CAST(TotalProducedLoadingUnits as float) as Produced,
ROUND(CAST(TotalPlannedLoadingUnits as float) - CAST(TotalProducedLoadingUnits as float),2) as Remaining,
case
-- checks if someone changed the criteria to something else to trigger the over run
when x.ProzentReserveAnzahlPaletten > 0 then 'yes'
-- if the lot has a decimal in it to allow over running with no intervention
when CAST(TotalPlannedLoadingUnits as float) - floor(CAST(TotalPlannedLoadingUnits as float)) > 0 then 'yes'
else 'no' end as overPrinting,
CustomerHumanReadableId as CustomerId,
CustomerName as CustomerName,
idMaschine as MachineID,
prolink.lastProlinkUpdate as lastProlinkUpdate,
IdEtikettenLayoutPalette as palletLabel,
AnzahlKopienPalette as pallerCopies,
IdEtikettenLayoutKarton as cartonLabel,
AnzahlKopienKarton as cartonCopies,
IsTechnicallyReleased
--*
from AlplaPROD_test1.dbo.V_Maschinen_ProdPlanungen x (nolock)
join
[test1_AlplaPROD2.0_Read].[productionControlling].[ProducedLot] on
x.IdProdPlanung =
[test1_AlplaPROD2.0_Read].[productionControlling].[ProducedLot].ProductionLotHumanReadableId
left join
[test1_AlplaPROD2.0_Read].masterData.Printer as b on
x.IdEtikettenDrucker = b.HumanReadableId
-- adding in prolink lot
left join
(SELECT * from (SELECT IdMaschine as prolinkMachineId,
Produktionslos as lot,
Upd_Date as lastProlinkUpdate,
ROW_NUMBER() OVER (PARTITION BY IdMaschine ORDER BY Upd_Date DESC) RN_Prolink
FROM AlplaPROD_test1.dbo.T_HistoryProduktionsdaten (nolock)
WHERE Upd_Date BETWEEN DATEADD(DD, - 300, getdate()) AND DATEADD(DD, 1, getdate())) p
WHERE RN_Prolink = 1
) as prolink on
x.idMaschine = prolink.prolinkMachineId
where IsTechnicallyReleased = 1
`;

View File

@@ -0,0 +1,9 @@
export const machineCheck = `
SELECT [HumanReadableId]
,[Name]
,[Location]
,[Active]
,[ImportSource]
,[StagingMainMaterialMandatory]
FROM [test1_AlplaPROD2.0_Read].[masterData].[Machine] (nolock)
where Active = 1 and [Location] = [loc]`;

View File

@@ -0,0 +1,140 @@
// export const mmQuery = `
// SELECT lot.ProductionLotHumanReadableId,
// case when SourcingState in (1, 2) then 1
// when x.ProvidedAmount > 0 then 1
// when x.EffectiveConsumption > 0 then 1
// else 0 end as Staged,
// x.ProvidedAmount as Provided,
// x.EffectiveConsumption as consumption,
// x.TotalDemand as totalNeeded,
// /* remaining needed to complete the lot */
// x.TotalDemand - x.EffectiveConsumption as remainingNeeded,
// /* do we have enough staged or scanned to the lot? */
// case when (case when x.ProvidedAmount <> 0 then x.ProvidedAmount else x.EffectiveConsumption end) > x.TotalDemand then 'good' else 'bad' end as noShortage ,
// x.IsManualProcess as isManual,
// MaterialHumanReadableId
// FROM [test1_AlplaPROD2.0_Read].[issueMaterial].[MaterialDemand] x (nolock)
// left join
// [test1_AlplaPROD2.0_Read].[issueMaterial].[ProductionLot] as lot on
// x.ProductionLotId = lot.Id
// where lot.ProductionLotHumanReadableId = [lotNumber]
// and IsMainMaterial = 1
// `;
export const mmQuery = `
use [test1_AlplaPROD2.0_Read]
declare @lot as NVARCHAR(max) = [lotNumber]
/*
checks all needed material including pkg
we only want to monitor the manual materials and the mm materail to make sure they are good.
for auto consume materails this will be compared with another query.
*/
/*
Material demands for this lot
*/
select
MaterialHumanReadableId
,MaterialDescription
-- check box is staged so we could book in even if we used preprint.
,case when SourcingState in (1, 2) then 1
when x.ProvidedAmount > 0 then 1
when x.EffectiveConsumption > 0 then 1
else 0 end as Staged
,x.IsManualProcess as isManual
,IsMainMaterial
-- lot stuff
,lot.TotalPlannedLoadingUnits
,lot.TotalProducedLoadingUnits
,lot.TotalPlannedLoadingUnits - lot.TotalProducedLoadingUnits as remainingPallets
,x.ProvidedAmount as Provided -- this is what has been provided most of the time this is due to a silo attachment
,x.EffectiveConsumption as consumption -- this is how much was consummed via cmd 112
,x.TotalDemand as totalDemand -- the total demand needed to finish the lot out
,case when cp.Pieces >= 0.001 then (lot.TotalProducedLoadingUnits+1) * cp.Pieces else
(a.Weight *((case when cp.Percentage is null then 80 else cp.Percentage end) / 100) * ((lot.TotalProducedLoadingUnits+1) * p.LoadingUnitPieces)) / 1000 end totalNeeded
,case when IsMainMaterial = 1 then
case when (case when x.ProvidedAmount <> 0
then x.ProvidedAmount else x.EffectiveConsumption end) >
(case when cp.Pieces >= 0.001 then (lot.TotalProducedQuantity+1) * cp.Pieces else
(a.Weight *((case when cp.Percentage is null then 80 else cp.Percentage end) / 100) * ((lot.TotalProducedLoadingUnits+1) * p.LoadingUnitPieces)) / 1000 end)
then 'mmGood'
else 'noMM' end else null end as noMMShortage
-- pkg check auto
,case when pkg.QuantityPosition is null then null else
(case when l.qty > ((lot.TotalProducedLoadingUnits+1) * pkg.QuantityPosition) and IsManualProcess = 0 then 'pkgAutoGood' else 'noAutoPkg' end) end as noPKGAutoShortage
-- plg check manual
,case when pkg.QuantityPosition is null then null else
(case when x.EffectiveConsumption > ((lot.TotalProducedLoadingUnits+1) * pkg.QuantityPosition) and IsManualProcess = 1 then 'pkgManGood' else 'noManPkg' end) end as noPKGManualShortage
-- manualMateiral
,case when IsMainMaterial = 0 and IsManualProcess = 1 then
case when (case when x.ProvidedAmount <> 0
then x.ProvidedAmount else x.EffectiveConsumption end) >
(case when cp.Pieces >= 0.001 then (lot.TotalProducedQuantity+1) * cp.Pieces else
(a.Weight *((case when cp.Percentage is null then 80 else cp.Percentage end) / 100) * ((lot.TotalProducedLoadingUnits+1) * p.LoadingUnitPieces)) / 1000 end)
then 'manualGood'
else 'noOK' end else null end as noManualShortage
-- autoconsume
,case when cp.Percentage is null then
case when l.qty > ((lot.TotalProducedLoadingUnits +1) * pkg.QuantityPosition) then 'autoConsumeOk' else 'autoConsumeNOK' end else
(case when l.qty > (a.Weight *(cp.Percentage / 100) * ((lot.TotalProducedLoadingUnits+1) * p.LoadingUnitPieces)) / 1000 and IsManualProcess = 0
then 'autoConsumeOk' else 'autoConsumeNOK' end) end as autoConsumeCheck
-- stock amounts
,l.qty as invForAutoConsume
,case when cp.Percentage is null then 0 else cp.Percentage end as Percentage
,pkg.QuantityPosition
,(lot.TotalProducedQuantity+1) * cp.Pieces
from [issueMaterial].[MaterialDemand] x (nolock)
/* production lot info */
left join
[productionControlling].[ProducedLot] as lot on
lot.Id = x.ProductionLotId
/* packagaing */
left join
[masterData].[PackagingInstructionPosition] as pkg on
pkg.PackagingInstructionId = lot.PackagingId
and pkg.ArticleId = x.MaterialId
-- get the pkg stuff so we have the total amount per pallet.
left join
[masterData].[PackagingInstruction] as p on
p.id = lot.PackagingId
/* av data */
left join
[masterData].[Article] as a on
a.id = lot.ArticleId
/* compound*/
left join
[masterData].[CompoundPosition] as cp on
cp.CompoundId = a.CompoundId
and cp.ArticleId = x.MaterialId
/* current stock info for auto consumption*/
left join
(select
IdArtikelVarianten
,ArtikelVariantenBez
,sum(VerfuegbareMengeSum) as qty
from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes as i (nolock)
left join
AlplaPROD_test1.dbo.V_LagerAbteilungen as l (nolock) on
l.IdLagerAbteilung = i.IdLagerAbteilung
where autoverbrauch = 1 and aktiv = 1
group by IdArtikelVarianten,ArtikelVariantenBez
) as l on
l.IdArtikelVarianten = MaterialHumanReadableId
where lot.ProductionLotHumanReadableId = @lot and MaterialDescription not like '%nopal%'
and MaterialDescription NOT LIKE '%bb%'
and MaterialDescription NOT LIKE '%mcg%'
`;

View File

@@ -0,0 +1,25 @@
export const prolinkQuery = `
select * from (
select *
From(select
V_Maschinen_ProdPlanungen.MaschinenStandort as Machine,
V_Maschinen_ProdPlanungen.IdProdPlanung as AlplaLabelOnline,
prolink.lot Prolink,
case when AlplaPROD_test1.dbo.V_Maschinen_ProdPlanungen.IdProdPlanung <> prolink.lot
Then 'IncorrectLot'
Else 'Good' end as LotCheck
from AlplaPROD_test1.dbo.V_Maschinen_ProdPlanungen (nolock)
left join
(
SELECT *
FROM (SELECT IdMaschine,
Produktionslos as lot,
Startzeit as StartTime,
Upd_Date,
ROW_NUMBER() OVER (PARTITION BY IdMaschine ORDER BY Upd_Date DESC) RN_Prolink
FROM AlplaPROD_test1.dbo.T_HistoryProduktionsdaten (nolock)
WHERE Upd_Date BETWEEN DATEADD(DD, - 10, getdate()) AND DATEADD(DD, 1, getdate())) a
WHERE RN_Prolink = 1
) as prolink on AlplaPROD_test1.dbo.V_Maschinen_ProdPlanungen.IdMaschine=prolink.IdMaschine) a
) a
`;

View File

@@ -0,0 +1,17 @@
export const userCheck = `
SELECT *,
'[' + STUFF((
SELECT ',' + '"' + REPLACE(REPLACE(ur.name, '\', '\\'), '"', '\"') + '"'
FROM [test1_AlplaPROD2.0_Read].[user].[Roles] (nolock) ur
WHERE ur.userid = u.id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'
), 1, 1, '') + ']' AS roles,
'[' + STUFF((
SELECT ',' + cast(ulr.roleid as nvarchar(max))
FROM [test1_AlplaPROD2.0_Read].[user].[LegacyRoles] (nolock) ulr
WHERE ulr.userid = u.id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'
), 1, 1, '') + ']' AS legacyRoles
FROM [test1_AlplaPROD2.0_Read].[user].[User] (nolock) u
where Loginname = '[userName]'
`;

View File

@@ -0,0 +1,40 @@
export const articleInfo = `
use [test1_AlplaPROD2.0_Read]
select a.Id,
a.HumanReadableId as av,
a.Alias as alias,
p.LoadingUnitsPerTruck as loadingUnitsPerTruck,
p.LoadingUnitsPerTruck * p.LoadingUnitPieces as qtyPerTruck,
p.LoadingUnitPieces,
case when i.MinQuantity IS NOT NULL then round(cast(i.MinQuantity as float), 2) else 0 end as min,
case when i.MaxQuantity IS NOT NULL then round(cast(i.MaxQuantity as float),2) else 0 end as max
from masterData.Article (nolock) as a
/* sales price */
left join
(select *
from (select
id,
PackagingId,
ArticleId,
DefaultCustomer,
ROW_NUMBER() OVER (PARTITION BY ArticleId ORDER BY ValidAfter DESC) AS RowNum
from masterData.SalesPrice (nolock)
where DefaultCustomer = 1) as x
where RowNum = 1
) as s
on a.id = s.ArticleId
/* pkg instuctions */
left join
masterData.PackagingInstruction (nolock) as p
on s.PackagingId = p.id
/* stock limits */
left join
masterData.StockLimit (nolock) as i
on a.id = i.ArticleId
where a.active = 1 and a.HumanReadableId in ([articles])
`;

View File

@@ -0,0 +1,19 @@
export const psiDeliveredData = `
use AlplaPROD_test1
declare @start_date nvarchar(30) = [startDate] --'2025-01-01'
declare @end_date nvarchar(30) = [endDate] --'2025-08-09'
select IdArtikelVarianten,
ArtikelVariantenBez,
sum(Menge) totalDelivered,
case when convert(time, upd_date) between '00:00' and '07:00' then convert(date, upd_date - 1) else convert(date, upd_date) end as ShippingDate
from dbo.V_LadePlanungenLadeAuftragAbruf (nolock)
where upd_date between CONVERT(datetime, @start_date + ' 7:00') and CONVERT(datetime, @end_date + ' 7:00') and IdArtikelVarianten in ([articles])
group by IdArtikelVarianten, upd_date,
ArtikelVariantenBez
`;

View File

@@ -0,0 +1,27 @@
export const psiDeliveredData = `
use [test1_AlplaPROD2.0_Read]
declare @start_date nvarchar(30) = [startDate] --'2025-01-01'
declare @end_date nvarchar(30) = [endDate] --'2025-08-09'
select
ArticleHumanReadableId,
ArticleAlias,
cast(Quantity as int) Quantity,
--cast(DeliveryDate as time) as deliveryTime,
--cast(DeliveryDate as date) as originalDeliveryDate,
case when cast(DeliveryDate as time) between '00:00' and '07:00'
then DATEADD(DAY, -1, CONVERT(DATE, DeliveryDate))
else cast(DeliveryDate as date)
end as ShippingDate
--,*
from [order].[Release]
where case when cast(DeliveryDate as time) between '00:00' and '07:00'
then DATEADD(DAY, -1, CONVERT(DATE, DeliveryDate))
else cast(DeliveryDate as date)
end between @start_date and @end_date
and ArticleHumanReadableId in ([articles])
order by DeliveryDate`;

View File

@@ -0,0 +1,34 @@
export const planningNumbersByAVDate = `
use AlplaPROD_test1
declare @start_date nvarchar(30) = '[startDate]' --'2025-01-01'
declare @end_date nvarchar(30) = '[endDate]' --'2025-08-09'
/*
articles will need to be passed over as well as the date structure we want to see
*/
select x.IdArtikelvarianten As Article,
ProduktionAlias as Description,
standort as MachineId,
MaschinenBezeichnung as MachineName,
--MaschZyklus as PlanningCycleTime,
x.IdProdPlanung as LotNumber,
FORMAT(ProdTag, 'MM/dd/yyyy') as ProductionDay,
x.planMenge as TotalPlanned,
ProduktionMenge as QTYPerDay,
round(ProduktionMengeVPK, 2) PalDay,
Status as finished
--MaschStdAuslastung as nee
from dbo.V_ProdLosProduktionJeProdTag_PLANNING (nolock) as x
left join
dbo.V_ProdPlanung (nolock) as p on
x.IdProdPlanung = p.IdProdPlanung
where ProdTag between @start_date and @end_date
and p.IdArtikelvarianten in ([articles])
--and V_ProdLosProduktionJeProdTag_PLANNING.IdKunde = 10
--and IdProdPlanung = 18442
order by ProdTag desc
`;

View File

@@ -0,0 +1,21 @@
export const productionNumbers = `
use [test1_AlplaPROD2.0_Reporting]
declare @startDate nvarchar(30) = '[startDate]' --'2024-12-30'
declare @endDate nvarchar(30) = '[endDate]' --'2025-08-09'
select MachineLocation,
ArticleHumanReadableId as article,
sum(Quantity) as Produced,
count(Quantity) as palletsProdued,
FORMAT(convert(date, ProductionDay), 'M/d/yyyy') as ProductionDay,
ProductionLotHumanReadableId as productionLot
from [reporting_productionControlling].[ScannedUnit] (nolock)
where convert(date, ProductionDay) between @startDate and @endDate and ArticleHumanReadableId in ([articles]) and BookedOut is null
group by MachineLocation, ArticleHumanReadableId,ProductionDay, ProductionLotHumanReadableId
order by ProductionDay
`;

View File

@@ -0,0 +1,34 @@
export const planningNumbersByAVDate = `
use AlplaPROD_test1
declare @start_date nvarchar(30) = '[startDate]' --'2025-01-01'
declare @end_date nvarchar(30) = '[endDate]' --'2025-08-09'
/*
articles will need to be passed over as well as the date structure we want to see
*/
select x.IdArtikelvarianten As Article,
ProduktionAlias as Description,
standort as MachineId,
MaschinenBezeichnung as MachineName,
--MaschZyklus as PlanningCycleTime,
x.IdProdPlanung as LotNumber,
FORMAT(ProdTag, 'MM/dd/yyyy') as ProductionDay,
x.planMenge as TotalPlanned,
ProduktionMenge as QTYPerDay,
round(ProduktionMengeVPK, 2) PalDay,
Status as finished
--MaschStdAuslastung as nee
from dbo.V_ProdLosProduktionJeProdTag_PLANNING (nolock) as x
left join
dbo.V_ProdPlanung (nolock) as p on
x.IdProdPlanung = p.IdProdPlanung
where ProdTag between @start_date and @end_date
and p.IdArtikelvarianten in ([articles])
--and V_ProdLosProduktionJeProdTag_PLANNING.IdKunde = 10
--and IdProdPlanung = 18442
order by ProdTag desc
`;

View File

@@ -0,0 +1,14 @@
export const qrequestQuery = `
select IdArtikelVarianten as article,
ArtikelVariantenBez as description,
Lfdnr as runningNr,
Produktionslos as lotNr,
IdWarenlager as idWarehouse,
WarenLagerKurzBez as warehouseAtRequest,
IdLagerAbteilung as idLocation,
LagerAbteilungKurzBez as locationAtRequest,
BewegungsDatumMax as lastMove
from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes (nolock)
where /* VerfuegbareMengeSum = 0 and */ IdLagerAbteilung not in (0, 20000, 21000) and lfdnr = [runningNumber]
`;

View File

@@ -0,0 +1,42 @@
export const notconnectedToMachine = `
select distinct HumanReadableId as machineId
,Location as location
,name
--,[SiloHumanReadableId]
from [test1_AlplaPROD2.0_Read].[masterData].[Machine] (nolock) m
left join
[test1_AlplaPROD2.0_Read].[issueMaterial].[SiloAssignment] (nolock) s
on s.MachineId = m.id
where m.id not in (
SELECT
[MachineId]
FROM [test1_AlplaPROD2.0_Read].[issueMaterial].[SiloAssignment]
where [SiloHumanReadableId] = [siloID]
)
and name not like '%REWORK%'
`;
export const connectedToMachine = `
SELECT
[SiloHumanReadableId]
,[SiloDescription]
,[MaterialHumanReadableId]
,[MaterialDescription]
,[ConnectionDate]
,m.HumanReadableId as machineId
,m.Location as location
,m.Name as name
FROM [test1_AlplaPROD2.0_Read].[issueMaterial].[SiloAssignment] s
left join
[test1_AlplaPROD2.0_Read].[masterData].[Machine] m
on m.id = s.MachineId
where [SiloHumanReadableId] = [siloID]
`;

View File

@@ -0,0 +1,32 @@
export const siloQuery = `
SELECT
V_LagerAbteilungen.Bezeichnung AS Description,
V_LagerAbteilungen.IdWarenLager AS WarehouseID,
V_LagerAbteilungen.IdLagerAbteilung AS LocationID,
case when ROUND(SUM(einlagerungsmengesum), 2) is null then 0 else ROUND(SUM(einlagerungsmengesum), 2) end AS Stock_Total
,case when ROUND(SUM(einlagerungsmengesum), 2) is null then COALESCE(b.upd_Date, '1900-01-01') else COALESCE(LastAdjustment, '1900-01-01') end AS LastAdjustment
FROM AlplaPROD_test1.dbo.V_LagerAbteilungen (NOLOCK)
left JOIN
AlplaPROD_test1.dbo.V_LagerPositionenBarcodes ON
AlplaPROD_test1.dbo.V_LagerAbteilungen.IdLagerAbteilung =
AlplaPROD_test1.dbo.V_LagerPositionenBarcodes.IdLagerAbteilung
LEFT JOIN (
SELECT
IdLagerAbteilung,
MAX(CASE WHEN CONVERT(CHAR(10), Buchungsdatum, 120) IS NULL THEN '1900-01-01' ELSE CONVERT(CHAR(10), Buchungsdatum, 120) END) AS LastAdjustment
FROM AlplaPROD_test1.dbo.V_LagerBuchungen (NOLOCK)
WHERE urheber = 2900
GROUP BY IdLagerAbteilung
) AS LastAdj ON AlplaPROD_test1.dbo.V_LagerAbteilungen.IdLagerAbteilung = LastAdj.IdLagerAbteilung
/* add the actual inventory now that we will display an empty silo and need to add this date */
left join
AlplaPROD_test1.dbo.V_LagerAbteilungenInventuren as b on
AlplaPROD_test1.dbo.V_LagerAbteilungen.IdLagerAbteilung = b.IdLagerAbteilung
WHERE materialsilo = 1
AND aktiv = 1
GROUP BY V_LagerAbteilungen.Bezeichnung, V_LagerAbteilungen.IdWarenLager, V_LagerAbteilungen.IdLagerAbteilung, LastAdjustment, b.upd_Date
ORDER BY V_LagerAbteilungen.Bezeichnung
`;

View File

@@ -0,0 +1,15 @@
export const activeWarehouseLanes = `
select
w.IdWarenLager as warehouseId,
w.Bezeichnung as warehouseDescription,
IdLagerAbteilung as laneId,
b.Bezeichnung as laneDescription
--,*
from [AlplaPROD_test1].[dbo].[T_LagerAbteilungen] (nolock) b
left join
AlplaPROD_test1.dbo.T_WarenLager (nolock) as w
on b.IdWarenLager = w.IdWarenLager
where b.aktiv = 1 and w.idwarenlager not in (5,6)
`;

View File

@@ -0,0 +1,80 @@
export const cycleCountCheck = `
-- Define the structure of the result set from the stored procedure
DECLARE @results TABLE (
IdLocation INT,
LastMoveDate Date
)
-- insert into the temp table
insert into @results
select IdLagerAbteilung, MAX(CaSE WHEN CONVERT(char(10), Buchungsdatum, 120) IS NULL THEN '1900-01-01' ELSE CONVERT(char(10), Buchungsdatum, 120) END) AS LastLocMov
from AlplaPROD_test1.dbo.V_LagerBuchungen x(nolock)
group by IdLagerAbteilung
select * from (
select x.IdLagerAbteilung as laneID,
x.IdWarenLager as warehouseID,
w.Bezeichnung as warehouseName,
w.LagerTyp as warehouseIDTyp,
w.Standort as warehouseLocation,
x.Bezeichnung as Description,
LastMoveDate,
CASE WHEN CONVERT(char(10), i.Datum, 120) is null then getdate() - 365 else CONVERT(char(10), i.Datum, 120) end as LastInv,
--create the types of warehouses to choose from
case
-- empty
when (sum(EinlagerungsMengeSum) is null and Datum < LastMoveDate) or (
(sum(EinlagerungsMengeSum) is null and Datum < DATEADD(day, -[ageOfRow], getdate()))
) then 'EMPTY'
-- finished goods
when w.LagerTyp = 2 and w.Standort = 10 then 'FG'
-- external finished goods
when w.LagerTyp = 2 and w.Standort = 20 then 'EXTERNAL'
-- silos
when w.LagerTyp in (3) and x.MaterialSilo = 1 then 'BULK'
-- MATERIALS
when w.LagerTyp = 3 and x.MaterialSilo = 0 then 'MATERIALS'
-- MATERIALS
when w.LagerTyp = 11 then 'WASTE'
-- MATERIALS
when w.LagerTyp = 9 then 'PACKAGING'
end as rowType,
CASE WHEN DateDiff(DAY,i.Datum,getDate()) is null then 1000 else DateDiff(DAY,i.Datum,getDate()) end as DaysSinceLast
from AlplaPROD_test1.dbo.T_LagerAbteilungen as x (NOLOCK)
-- last move
left join
@results as b on
x.IdLagerAbteilung = b.IdLocation
-- last inv
left join
(select * from [AlplaPROD_test1].[dbo].[T_LagerAbteilungenInventuren] (nolock)) as i on x.IdLagerAbteilung =
i.IdLagerAbteilung
-- useing this to determin only if the lane is empty
left join
(select * from [AlplaPROD_test1].dbo.V_LagerPositionenBarcodes (nolock)) as y on x.IdLagerAbteilung =
y.IdLagerAbteilung
-- get the warehosue type
left join
(select * from [AlplaPROD_test1].dbo.T_WarenLager (nolock)) as w on x.IdWarenLager = w.IdWarenLager
where x.aktiv = 1 and x.IdWarenLager not in (1,5,6)
group by x.IdLagerAbteilung,
x.IdWarenLager,
w.LagerTyp,
w.Standort,
x.Bezeichnung,
LastMoveDate,
i.Datum,
x.MaterialSilo,
w.Bezeichnung
) xb
`;

View File

@@ -0,0 +1,36 @@
export const labelInfo = `
declare @runningNumber nvarchar(max) = [runningNr]
select e.Barcode,
e.RunningNumber as runnungNumber,
externalRunningNumber= null,
e.ArticleHumanReadableId as av,
e.LabelManagementHumanReadableId as labelLayout,
case when EinlagerungsMengeSum IS NULL then 'notOnStock' else 'onStock' end as stockStatus
from [test1_AlplaPROD2.0_Read].[labelling].[InternalLabel] (nolock) as e
left join
alplaprod_test1.dbo.V_LagerPositionenBarcodes (nolock) as l on
e.RunningNumber = l.Lfdnr
WHERE e.RunningNumber IN (@runningNumber)
union all
select ext.Barcode
,RunningNumber as runnungNumber
,SsccEanRunningNumber as externalRunningNumber
,ArticleHumanReadableId
,case when LabelManagementHumanReadableId is null then (select HumanReadableId from [test1_AlplaPROD2.0_Read].[masterData].[LabelManagement] (nolock) where LabelMarkerId = 7 and Active = 1) else LabelManagementHumanReadableId end as labelLayout
,case when EinlagerungsMengeSum IS NULL then 'notOnStock' else 'onStock' end as stockStatus
from [test1_AlplaPROD2.0_Read].[labelling].[ExternalLabel] (nolock) as ext
left join
alplaprod_test1.dbo.V_LagerPositionenBarcodes (nolock) as l on
ext.RunningNumber = l.Lfdnr
WHERE ext.SsccEanRunningNumber IN (@runningNumber) and
ext.RunningNumber NOT IN (
SELECT RunningNumber FROM [test1_AlplaPROD2.0_Read].[labelling].[InternalLabel] WHERE RunningNumber IN (@runningNumber)
)
`;

View File

@@ -0,0 +1,13 @@
export const ppooQuery = `
select MachineLocation,
[RunningNumber],
ArticleHumanReadableId,
ArticleDescription,
convert(Date, ProductionDay) as productionDay,
ProductionDate
FROM [test1_AlplaPROD2.0_Reporting].[reporting_productionControlling].[ScannedUnit] (nolock)
where [RunningNumber] in (select Lfdnr from AlplaPROD_test1.dbo.V_LagerPositionenBarcodes (nolock) where IdLagerAbteilung = 00000)
order by ProductionDate
`;

View File

@@ -0,0 +1,46 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi";
import {authMiddleware} from "../../auth/middleware/authMiddleware.js";
import {apiHit} from "../../../globalUtils/apiHits.js";
import {closePool} from "../prodSqlServer.js";
const app = new OpenAPIHono();
const responseSchema = z.object({
success: z.boolean().openapi({example: true}),
message: z.string().optional().openapi({example: "user access"}),
});
app.openapi(
createRoute({
tags: ["Server:PRODSQL"],
summary: "Close connection",
method: "get",
path: "/",
middleware: authMiddleware,
description: "Closes the connection to the prod sql server.",
responses: {
200: {
content: {"application/json": {schema: responseSchema}},
description: "stopped",
},
400: {
content: {"application/json": {schema: responseSchema}},
description: "Failed to stop",
},
},
}),
async (c) => {
apiHit(c, {endpoint: "api/sqlProd/close"});
try {
const pool = await closePool();
//return apiReturn(c, true, access?.message, access?.data, 200);
return c.json({success: pool.success, message: pool.message}, 200);
} catch (error) {
console.log(error);
//return apiReturn(c, false, "Error in setting the user access", error, 400);
return c.json({success: false, message: "Error in closing connection", data: error}, 400);
}
}
);
export default app;

View File

@@ -0,0 +1,48 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi";
import {authMiddleware} from "../../auth/middleware/authMiddleware.js";
import {apiHit} from "../../../globalUtils/apiHits.js";
import {closePool, initializeProdPool} from "../prodSqlServer.js";
const app = new OpenAPIHono();
const responseSchema = z.object({
success: z.boolean().openapi({example: true}),
message: z.string().optional().openapi({example: "user access"}),
});
app.openapi(
createRoute({
tags: ["Server:PRODSQL"],
summary: "restart sql connection",
method: "get",
path: "/",
middleware: authMiddleware,
description: "Restarts the sql connection.",
responses: {
200: {
content: {"application/json": {schema: responseSchema}},
description: "Succefull restart",
},
400: {
content: {"application/json": {schema: responseSchema}},
description: "Failed to restart server",
},
},
}),
async (c) => {
apiHit(c, {endpoint: "api/sqlProd/restart"});
try {
const poolClose = await closePool();
await new Promise((resolve) => setTimeout(resolve, 5000));
const poolStart = await initializeProdPool();
//return apiReturn(c, true, access?.message, access?.data, 200);
return c.json({success: poolStart.success, message: "The connection has been restarted."}, 200);
} catch (error) {
console.log(error);
//return apiReturn(c, false, "Error in setting the user access", error, 400);
return c.json({success: false, message: "Error in restarting the connection", data: error}, 400);
}
}
);
export default app;

View File

@@ -0,0 +1,46 @@
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi";
import {authMiddleware} from "../../auth/middleware/authMiddleware.js";
import {apiHit} from "../../../globalUtils/apiHits.js";
import {initializeProdPool} from "../prodSqlServer.js";
const app = new OpenAPIHono();
const responseSchema = z.object({
success: z.boolean().openapi({example: true}),
message: z.string().optional().openapi({example: "user access"}),
});
app.openapi(
createRoute({
tags: ["Server:PRODSQL"],
summary: "Connects to the sql server",
method: "get",
path: "/",
middleware: authMiddleware,
description: "Initilized the connetion",
responses: {
200: {
content: {"application/json": {schema: responseSchema}},
description: "restarred",
},
400: {
content: {"application/json": {schema: responseSchema}},
description: "Failed start",
},
},
}),
async (c) => {
apiHit(c, {endpoint: "api/sqlProd/connect"});
try {
const pool = await initializeProdPool();
//return apiReturn(c, true, access?.message, access?.data, 200);
return c.json({success: pool.success, message: pool.message}, 200);
} catch (error) {
console.log(error);
//return apiReturn(c, false, "Error in setting the user access", error, 400);
return c.json({success: false, message: "Error in initalizing the connection", data: error}, 400);
}
}
);
export default app;

View File

@@ -0,0 +1,18 @@
import {OpenAPIHono} from "@hono/zod-openapi";
import {initializeProdPool} from "./prodSqlServer.js";
import closeConnection from "./route/closeProdSql.js";
import connect from "./route/startProdSql.js";
import restart from "./route/restartProdSql.js";
const app = new OpenAPIHono();
setTimeout(async () => {
initializeProdPool();
}, 2 * 1000);
app.route("/sqlprod/connect", connect);
app.route("/sqlprod/close", closeConnection);
app.route("/sqlprod/restart", restart);
export default app;

View File

@@ -0,0 +1,48 @@
import sql from "mssql";
// hardcoding everything to make sure it all works as intended
const server = "usday1vms010";
const dbUser = "ocme";
const dbPassword = "Democrat-Humongous";
export const sqlConfig_ocme = {
server: server,
database: `Alpla_lst`,
user: dbUser,
password: dbPassword,
options: {
encrypt: true,
trustServerCertificate: true,
},
requestTimeout: 90000, // in milliseconds
// ocmePool: {
// max: 20, // Maximum number of connections in the pool
// min: 0, // Minimum number of connections in the pool
// idleTimeoutMillis: 10000, // How long a connection is allowed to be idle before being released
// reapIntervalMillis: 1000, // how often to check for idle resourses to destory
// acquireTimeoutMillis: 100000, // How long until a complete timeout happens
// },
};
export async function runQuery(queryToRun: string, name: string) {
let connection;
try {
// Establish a direct connection to the different server
connection = await sql.connect(sqlConfig_ocme);
// Execute the query
const result = await connection.request().query(queryToRun);
console.log(`${name} query ran successfully on different server`);
return result.recordset;
} catch (err) {
console.log(`Error running ${name} query on different server: ${err}`);
return [];
} finally {
// Close the direct connection
if (connection) {
await connection.close();
}
}
}

View File

@@ -0,0 +1,51 @@
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { createLog } from "../../logger/logger.js";
import { serverSettings } from "../../server/controller/settings/getSettings.js";
export const prodSqlConfig = async () => {
try {
//const serverSetting = await db.select().from(settings);
const serverSetting = serverSettings as any;
// create dummy type data
const server = serverSetting.filter((s: any) => s.name === "dbServer");
const plantToken = serverSetting.filter(
(s: any) => s.name === "plantToken"
);
const dbUser = serverSetting.filter((s: any) => s.name === "dbUser");
// if erroring out double check the password was actually encoded before saving
const dbPassword = serverSetting.filter(
(s: any) => s.name === "dbPass"
);
const sqlConfig = {
server: server[0].value,
database: `AlplaPROD_${plantToken[0].value}_cus`,
user: dbUser[0].value,
password: atob(dbPassword[0].value),
options: {
encrypt: true,
trustServerCertificate: true,
},
requestTimeout: 90000, // in milliseconds
pool: {
max: 20, // Maximum number of connections in the pool
min: 0, // Minimum number of connections in the pool
idleTimeoutMillis: 10000, // How long a connection is allowed to be idle before being released
reapIntervalMillis: 1000, // how often to check for idle resourses to destory
acquireTimeoutMillis: 100000, // How long until a complete timeout happens
},
};
return sqlConfig;
} catch (error) {
createLog(
"info",
"lst",
"sqlProd",
`${JSON.stringify(
error
)} "There was an error getting/setting up the config for the prod sql server."`
);
}
};