Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+47
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isValidTimeZone, parseScheduledAt } from "./campaignSchedule";
|
||||
|
||||
describe("isValidTimeZone", () => {
|
||||
it("accepts IANA zones and rejects garbage", () => {
|
||||
expect(isValidTimeZone("Europe/Berlin")).toBe(true);
|
||||
expect(isValidTimeZone("America/New_York")).toBe(true);
|
||||
expect(isValidTimeZone("Mars/Olympus")).toBe(false);
|
||||
expect(isValidTimeZone("")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseScheduledAt", () => {
|
||||
it("returns null for empty input", () => {
|
||||
expect(parseScheduledAt(null, "Europe/Berlin")).toEqual({ ok: true, date: null });
|
||||
});
|
||||
|
||||
it("interprets wall-clock time in the campaign timezone, not server time", () => {
|
||||
const berlin = parseScheduledAt("2026-07-20T09:00", "Europe/Berlin");
|
||||
const newYork = parseScheduledAt("2026-07-20T09:00", "America/New_York");
|
||||
if (!berlin.ok || !newYork.ok) throw new Error("expected ok results");
|
||||
// CEST is UTC+2 in July, EDT is UTC-4 — same wall clock, 6h apart.
|
||||
expect(berlin.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
expect(newYork.date?.toISOString()).toBe("2026-07-20T13:00:00.000Z");
|
||||
});
|
||||
|
||||
it("respects winter/summer offsets of the same zone", () => {
|
||||
const summer = parseScheduledAt("2026-07-20T09:00", "Europe/Berlin");
|
||||
const winter = parseScheduledAt("2026-01-20T09:00", "Europe/Berlin");
|
||||
if (!summer.ok || !winter.ok) throw new Error("expected ok results");
|
||||
expect(summer.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
expect(winter.date?.toISOString()).toBe("2026-01-20T08:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps explicit offsets untouched", () => {
|
||||
const zulu = parseScheduledAt("2026-07-20T09:00:00Z", "America/New_York");
|
||||
const offset = parseScheduledAt("2026-07-20T09:00:00+02:00", "America/New_York");
|
||||
if (!zulu.ok || !offset.ok) throw new Error("expected ok results");
|
||||
expect(zulu.date?.toISOString()).toBe("2026-07-20T09:00:00.000Z");
|
||||
expect(offset.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
});
|
||||
|
||||
it("rejects invalid timezone or unparseable date", () => {
|
||||
expect(parseScheduledAt("2026-07-20T09:00", "Mars/Olympus")).toEqual({ ok: false });
|
||||
expect(parseScheduledAt("not-a-date", "Europe/Berlin")).toEqual({ ok: false });
|
||||
});
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { fromZonedTime } from "date-fns-tz";
|
||||
|
||||
// Wall-clock inputs ("2026-07-20T09:00") carry no offset; anything with an
|
||||
// explicit offset or Z suffix is already an absolute instant.
|
||||
const EXPLICIT_OFFSET = /(?:Z|[+-]\d{2}:?\d{2})$/i;
|
||||
|
||||
export function isValidTimeZone(timeZone: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-US", { timeZone });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export type ParsedScheduledAt = { ok: true; date: Date | null } | { ok: false };
|
||||
|
||||
/**
|
||||
* Resolves the campaign "scheduledAt" form value to a UTC instant.
|
||||
* Wall-clock strings are interpreted in the campaign's IANA timezone —
|
||||
* NOT in the server's local timezone (that was the pre-fix behavior and
|
||||
* shifted scheduled sends by the server/tz offset difference).
|
||||
*/
|
||||
export function parseScheduledAt(value: string | null, timeZone: string): ParsedScheduledAt {
|
||||
if (!value) return { ok: true, date: null };
|
||||
if (!isValidTimeZone(timeZone)) return { ok: false };
|
||||
const date = EXPLICIT_OFFSET.test(value) ? new Date(value) : fromZonedTime(value, timeZone);
|
||||
if (Number.isNaN(date.getTime())) return { ok: false };
|
||||
return { ok: true, date };
|
||||
}
|
||||
+47
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildKontaktWhere,
|
||||
buildKontaktSqlPredicate,
|
||||
collectLookupRefs,
|
||||
lookupRefKey,
|
||||
MAX_SEGMENT_DEPTH,
|
||||
@@ -36,6 +37,20 @@ describe("validateSegmentTree", () => {
|
||||
expect(validateSegmentTree({ field: "kontaktStatus", in: ["bogus"] })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
});
|
||||
|
||||
it("deduplicates an abusive status list to the three semantic enum values", () => {
|
||||
const result = validateSegmentTree({
|
||||
field: "kontaktStatus",
|
||||
in: Array.from({ length: 70_000 }, (_, index) => ["kontakt", "kunde", "bestandskunde"][index % 3]),
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
tree: { field: "kontaktStatus", in: ["kontakt", "kunde", "bestandskunde"] },
|
||||
});
|
||||
if (result.ok) {
|
||||
expect(buildKontaktSqlPredicate(result.tree).parameters).toHaveLength(3);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a group missing children", () => {
|
||||
expect(validateSegmentTree({ op: "and" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
|
||||
});
|
||||
@@ -107,3 +122,35 @@ describe("buildKontaktWhere", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildKontaktSqlPredicate", () => {
|
||||
it("compiles lookup leaves to tenant-correlated EXISTS clauses with bounded bind parameters", () => {
|
||||
const predicate = buildKontaktSqlPredicate({
|
||||
op: "and",
|
||||
children: [
|
||||
{ field: "tag", tagId: "tag-1" },
|
||||
{
|
||||
op: "or",
|
||||
children: [
|
||||
{ field: "customFieldExists", definitionId: "field-1" },
|
||||
{ field: "customFieldEquals", definitionId: "field-2", value: "DE" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(predicate.sql).toContain('FROM "TagAssignment" AS ta');
|
||||
expect(predicate.sql).toContain('ta."tenantId" = k."tenantId"');
|
||||
expect(predicate.sql).toContain('FROM "CustomFieldValue" AS cf');
|
||||
expect(predicate.sql).toContain('cf."tenantId" = k."tenantId"');
|
||||
expect(predicate.sql).toContain('cf."wert" = $4::jsonb');
|
||||
expect(predicate.sql).not.toContain("tag-1");
|
||||
expect(predicate.sql).not.toContain("field-1");
|
||||
expect(predicate.parameters).toEqual(["tag-1", "field-1", "field-2", '"DE"']);
|
||||
});
|
||||
|
||||
it("preserves empty AND/OR semantics without adding parameters", () => {
|
||||
expect(buildKontaktSqlPredicate({ op: "and", children: [] })).toEqual({ sql: "TRUE", parameters: [] });
|
||||
expect(buildKontaktSqlPredicate({ op: "or", children: [] })).toEqual({ sql: "FALSE", parameters: [] });
|
||||
});
|
||||
});
|
||||
+81
-2
@@ -71,8 +71,11 @@ function validateLeaf(raw: Record<string, unknown>): SegmentLeaf | null {
|
||||
case "kontaktStatus": {
|
||||
if (!Array.isArray(raw.in) || raw.in.length === 0) return null;
|
||||
const allowed: KontaktStatus[] = ["kontakt", "kunde", "bestandskunde"];
|
||||
const values = raw.in.filter((v): v is KontaktStatus => allowed.includes(v as KontaktStatus));
|
||||
return values.length === raw.in.length ? { field, in: values } : null;
|
||||
if (!raw.in.every((value) => allowed.includes(value as KontaktStatus))) return null;
|
||||
// Duplicates do not change IN semantics. Normalize them here so a remote
|
||||
// filter cannot turn one logical node into an unbounded bind list.
|
||||
const values = [...new Set(raw.in as KontaktStatus[])];
|
||||
return { field, in: values };
|
||||
}
|
||||
case "zustaendigerUserId":
|
||||
return typeof raw.eq === "string" && raw.eq.length > 0 ? { field, eq: raw.eq } : null;
|
||||
@@ -173,6 +176,14 @@ export function collectLookupRefs(node: SegmentNode): LookupRef[] {
|
||||
/** A Prisma.KontaktWhereInput-shaped fragment (kept loose to stay DB-free). */
|
||||
export type KontaktWhereFragment = Record<string, unknown>;
|
||||
|
||||
/** A fully parameterized PostgreSQL predicate for the Kontakt alias `k`.
|
||||
* Lookup leaves use correlated EXISTS clauses, so no entity-id collection is
|
||||
* materialized into an `IN (...)` list. */
|
||||
export type KontaktSqlPredicate = {
|
||||
sql: string;
|
||||
parameters: readonly unknown[];
|
||||
};
|
||||
|
||||
function leafToWhere(leaf: SegmentLeaf, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
|
||||
switch (leaf.field) {
|
||||
case "kontaktTyp":
|
||||
@@ -209,3 +220,71 @@ export function buildKontaktWhere(node: SegmentNode, resolved: ReadonlyMap<strin
|
||||
}
|
||||
return leafToWhere(node, resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile a validated segment tree to bounded, parameterized PostgreSQL. Only
|
||||
* static identifiers and validated operators enter the SQL text; all remote
|
||||
* values remain bind parameters. The validation caps the tree at 200 nodes,
|
||||
* which also bounds the number of SQL parameters independently of audience
|
||||
* size.
|
||||
*/
|
||||
export function buildKontaktSqlPredicate(node: SegmentNode): KontaktSqlPredicate {
|
||||
const parameters: unknown[] = [];
|
||||
const bind = (value: unknown): string => {
|
||||
parameters.push(value);
|
||||
return `$${parameters.length}`;
|
||||
};
|
||||
|
||||
const compile = (current: SegmentNode): string => {
|
||||
if (isGroup(current)) {
|
||||
if (current.children.length === 0) return current.op === "and" ? "TRUE" : "FALSE";
|
||||
const operator = current.op === "and" ? " AND " : " OR ";
|
||||
return `(${current.children.map(compile).join(operator)})`;
|
||||
}
|
||||
|
||||
switch (current.field) {
|
||||
case "kontaktTyp":
|
||||
return `k."kontaktTyp" = ${bind(current.eq)}::"KontaktTyp"`;
|
||||
case "kontaktStatus":
|
||||
return `k."kontaktStatus" IN (${current.in.map((value) => `${bind(value)}::"KontaktStatus"`).join(", ")})`;
|
||||
case "zustaendigerUserId":
|
||||
return `k."zustaendigerUserId" = ${bind(current.eq)}`;
|
||||
case "createdBefore":
|
||||
return `k."createdAt" < ${bind(new Date(current.value))}`;
|
||||
case "createdAfter":
|
||||
return `k."createdAt" > ${bind(new Date(current.value))}`;
|
||||
case "hasPrimaerEmail":
|
||||
return current.value ? `k."primaerEmail" IS NOT NULL` : `k."primaerEmail" IS NULL`;
|
||||
case "tag":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "TagAssignment" AS ta
|
||||
WHERE ta."tenantId" = k."tenantId"
|
||||
AND ta."entityType" = 'kontakt'
|
||||
AND ta."entityId" = k."id"
|
||||
AND ta."tagId" = ${bind(current.tagId)}
|
||||
)`;
|
||||
case "customFieldExists":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "CustomFieldValue" AS cf
|
||||
WHERE cf."tenantId" = k."tenantId"
|
||||
AND cf."entityType" = 'kontakt'::"CustomFieldEntityType"
|
||||
AND cf."entityId" = k."id"
|
||||
AND cf."definitionId" = ${bind(current.definitionId)}
|
||||
)`;
|
||||
case "customFieldEquals":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "CustomFieldValue" AS cf
|
||||
WHERE cf."tenantId" = k."tenantId"
|
||||
AND cf."entityType" = 'kontakt'::"CustomFieldEntityType"
|
||||
AND cf."entityId" = k."id"
|
||||
AND cf."definitionId" = ${bind(current.definitionId)}
|
||||
AND cf."wert" = ${bind(JSON.stringify(current.value))}::jsonb
|
||||
)`;
|
||||
}
|
||||
};
|
||||
|
||||
return { sql: compile(node), parameters };
|
||||
}
|
||||
Reference in new issue
Block a user