sozsoft-platform/configs/seeds/postgres/object/Mm_S_MaintenanceInstructionSchedule.sql
2026-10-18 02:59:45 +03:00

51 lines
2.7 KiB
PL/PgSQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Zamanlanmış işin BeforeSp'si PostgreSQL'de "SELECT * FROM public.<ad>()" ile çağrıldığı için
-- prosedür değil, void dönen fonksiyondur.
CREATE OR REPLACE FUNCTION public."Mm_S_MaintenanceInstructionSchedule"()
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
v_Today date := LOCALTIMESTAMP::date;
BEGIN
-- Zamanlanmış iş (Maintenance Instruction Schedule, her gece 01:00). Aktif bakım talimatlarının
-- sonraki bakım tarihini Başlangıç Tarihi + k × periyot dizisinde bugüne eşit ya da bugünden sonraki
-- ilk tarihe taşır; Bitiş Tarihi geçmişse ya da talimat pasifse tarih boşalır. İş emri tablosu
-- geldiğinde vadesi gelen ve onaylanmış talimattan iş emri bu fonksiyonda açılır.
-- İş host ve her kiracı için çağrılır, fonksiyon parametre almaz; bütün kiracıların satırlarını işler
-- ve aynı gün tekrar çalışması sonucu değiştirmez.
UPDATE "Mm_T_MaintenanceInstruction" i SET
"NextDueDate" = CASE WHEN n."NextDate" > i."EndDate" THEN NULL ELSE n."NextDate" END
FROM (
SELECT c."Id",
CASE
WHEN c."StartDate" >= v_Today THEN c."StartDate"
WHEN c."Candidate" >= v_Today THEN c."Candidate"
WHEN c."IsMonth" THEN (c."StartDate" + make_interval(months => (c."K" + 1) * c."Step"))::date
ELSE c."StartDate" + (c."K" + 1) * c."Step"
END AS "NextDate"
FROM (
SELECT k.*,
CASE WHEN k."IsMonth" THEN (k."StartDate" + make_interval(months => k."K" * k."Step"))::date
ELSE k."StartDate" + k."K" * k."Step" END AS "Candidate"
FROM (
SELECT s.*,
(CASE WHEN s."IsMonth"
THEN ((EXTRACT(YEAR FROM v_Today) - EXTRACT(YEAR FROM s."StartDate")) * 12
+ EXTRACT(MONTH FROM v_Today) - EXTRACT(MONTH FROM s."StartDate"))::integer
ELSE v_Today - s."StartDate" END) / s."Step" AS "K"
FROM (
SELECT x."Id", x."StartDate",
x."PeriodUnit" IN ('Month', 'Year') AS "IsMonth",
CASE x."PeriodUnit" WHEN 'Week' THEN 7 * x."PeriodValue" WHEN 'Year' THEN 12 * x."PeriodValue" ELSE x."PeriodValue" END AS "Step"
FROM "Mm_T_MaintenanceInstruction" x
WHERE x."IsDeleted" = FALSE AND x."IsActive" = TRUE AND x."PeriodValue" > 0
) s
) k
) c
) n
WHERE n."Id" = i."Id";
UPDATE "Mm_T_MaintenanceInstruction" SET "NextDueDate" = NULL
WHERE "NextDueDate" IS NOT NULL AND ("IsDeleted" = TRUE OR "IsActive" = FALSE OR "PeriodValue" <= 0);
END;
$$;