@htilabs/platform-common-models 0.64.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@htilabs/platform-common-models",
3
- "version": "0.64.0",
3
+ "version": "0.66.0",
4
4
  "description": "Shared constants, types, and models for HTI Labs applications",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The Org's identifier helpers are reachable from the package root as well as
3
+ * from `/org-directory` (0.66.0): an app mints a key where it creates an
4
+ * organization, next to the model it already imports from the root.
5
+ */
6
+ import { describe, expect, it } from "vitest";
7
+
8
+ import * as root from "../index.js";
9
+ import * as orgDirectory from "../orgDirectory/index.js";
10
+
11
+ describe("the Org identifier helpers on the package root", () => {
12
+ it("are the same objects the /org-directory subpath exports", () => {
13
+ expect(root.mintOrgKey).toBe(orgDirectory.mintOrgKey);
14
+ expect(root.isOrgKey).toBe(orgDirectory.isOrgKey);
15
+ expect(root.ORG_KEY_PATTERN).toBe(orgDirectory.ORG_KEY_PATTERN);
16
+ });
17
+
18
+ it("work from the root", () => {
19
+ const key: string = root.mintOrgKey("6A1F5DADD0C33A5A149F3413");
20
+ expect(key).toBe("org-6a1f5dadd0c33a5a149f3413");
21
+ expect(root.isOrgKey(key)).toBe(true);
22
+ expect(root.ORG_KEY_PATTERN.test("The Spring")).toBe(false);
23
+ });
24
+ });
package/src/index.ts CHANGED
@@ -117,6 +117,13 @@ export type {
117
117
  SetOrgTypeInput,
118
118
  } from "./validation/agency.js";
119
119
 
120
+ // ─── The Org's identifier ───────────────────────────────────────────────────
121
+ // An app stores `key: mintOrgKey(_id)` in the same place it creates an
122
+ // organization, which is where it already imports its model from this root.
123
+ // The rest of the org directory stays on the `/org-directory` subpath, which
124
+ // exports these three as well.
125
+ export { ORG_KEY_PATTERN, isOrgKey, mintOrgKey } from "./orgDirectory/orgRecord.js";
126
+
120
127
  // ─── CVC factory model named aliases ────────────────────────────────────────
121
128
  // Per co-am3.7 bead: surface the model factories under explicit
122
129
  // `compileCvcRegistryModel` / `compileCvcEntryModel` names. The underlying
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The Org's identifier (`key`, the UDD Org `id`): its shape, how a new one is
3
+ * minted, that no request body can carry it, and that the shared mount stores
4
+ * it once and uniquely.
5
+ */
6
+ import { Schema, model, models, type Model } from "mongoose";
7
+ import { describe, expect, it } from "vitest";
8
+
9
+ import {
10
+ ORG_KEY_INDEX_NAME,
11
+ ORG_KEY_INDEX_OPTIONS,
12
+ ORG_KEY_INDEX_SPEC,
13
+ addOrgRecordFields,
14
+ organizationSchemaIssues,
15
+ } from "../../schemas/organization.js";
16
+ import {
17
+ ORGANIZATION_BASE_ROW_KEYS,
18
+ ORG_RECORD_FIELD_NAMES,
19
+ OrgIdentityWriteSchema,
20
+ isOrgKey,
21
+ mintOrgKey,
22
+ toDirectoryOrganizationView,
23
+ } from "../index.js";
24
+
25
+ const ID = "64B000000000000000000001";
26
+
27
+ function mounted(): Schema {
28
+ const def: Record<string, unknown> = {};
29
+ for (const key of ORGANIZATION_BASE_ROW_KEYS) def[key] = { type: Schema.Types.Mixed };
30
+ return addOrgRecordFields(new Schema(def));
31
+ }
32
+
33
+ describe("the Org identifier", () => {
34
+ it("is part of the Org record, first", () => {
35
+ expect(ORG_RECORD_FIELD_NAMES[0]).toBe("key");
36
+ expect(organizationSchemaIssues(mounted())).toEqual([]);
37
+ });
38
+
39
+ it("accepts the curated list's slugs and refuses anything else", () => {
40
+ for (const ok of ["the_spring", "ascension_stjohn", "org-custom-8daxtira", "okcpd", "org-64b000000000000000000001"]) {
41
+ expect(isOrgKey(ok), ok).toBe(true);
42
+ }
43
+ for (const bad of ["", " the_spring", "The_Spring", "the spring", "_spring", "a/b", "x".repeat(121), null, 7]) {
44
+ expect(isOrgKey(bad), String(bad)).toBe(false);
45
+ }
46
+ });
47
+
48
+ it("mints a key from the row's own id, never from a name", () => {
49
+ expect(mintOrgKey(ID)).toBe("org-64b000000000000000000001");
50
+ expect(mintOrgKey({ toHexString: () => ID })).toBe("org-64b000000000000000000001");
51
+ expect(isOrgKey(mintOrgKey(ID))).toBe(true);
52
+ expect(() => mintOrgKey("the_spring")).toThrow(/24-hex/);
53
+ });
54
+
55
+ it("is never taken from a request body", () => {
56
+ expect(OrgIdentityWriteSchema.safeParse({ key: "the_spring" }).success).toBe(false);
57
+ expect(OrgIdentityWriteSchema.safeParse({ legalName: "The Spring", key: "x" }).success).toBe(false);
58
+ });
59
+
60
+ it("is stored as a slug, uniquely, and only when set", async () => {
61
+ const schema = mounted();
62
+ const index = schema.indexes().find(([, options]) => options.name === ORG_KEY_INDEX_NAME);
63
+ expect(index?.[0]).toEqual({ key: 1 });
64
+ expect(index?.[1]).toMatchObject({ unique: true, partialFilterExpression: { key: { $type: "string" } } });
65
+ // The exported definition (what the registry fill builds) is the one the mount declares.
66
+ expect(index?.[0]).toEqual({ ...ORG_KEY_INDEX_SPEC });
67
+ expect(index?.[1]).toMatchObject({ ...ORG_KEY_INDEX_OPTIONS });
68
+ // What a model does with a key on save / update / upsert is measured against a real
69
+ // MongoDB in scripts/fill-org-registry.test.ts (run in CI).
70
+
71
+ const M = (models.OrgKeyTestRow as Model<unknown> | undefined) ?? model("OrgKeyTestRow", schema);
72
+ await expect(new M({ name: "A", key: "the_spring" }).validate()).resolves.toBeUndefined();
73
+ await expect(new M({ name: "A" }).validate()).resolves.toBeUndefined();
74
+ await expect(new M({ name: "A", key: "The Spring" }).validate()).rejects.toThrow(/lower-case slug/);
75
+ });
76
+
77
+ it("reads back on the shared view, null when a row has none or a malformed one", () => {
78
+ expect(toDirectoryOrganizationView({ _id: ID, name: "A", type: "unknown", key: "the_spring" })?.key).toBe("the_spring");
79
+ expect(toDirectoryOrganizationView({ _id: ID, name: "A", type: "unknown" })?.key).toBeNull();
80
+ expect(toDirectoryOrganizationView({ _id: ID, name: "A", type: "unknown", key: "Not A Key" })?.key).toBeNull();
81
+ // A legacy row's own `id` field is not read as the identifier; the fill stamps `key` from it.
82
+ expect(toDirectoryOrganizationView({ _id: ID, name: "A", id: "the_spring", acronym: "S" })?.key).toBeNull();
83
+ });
84
+ });
@@ -21,9 +21,12 @@
21
21
  * The UDD spells these snake_case (`legal_name`, `parent_org_id`, ...). The
22
22
  * live platform-db writers use camelCase, so the stored names are the UDD's in
23
23
  * camelCase, as for the org-type fields (`schemas/agency.ts`) and the program
24
- * row (`schemas/organization-program.ts`). One exception: the UDD `acronym` is
25
- * stored as `shortName`. A top-level `acronym` key marks a pre-pl-958 PAVE row
26
- * (`organizationRowShape`), and PAVE 2.0 already writes `shortName`.
24
+ * row (`schemas/organization-program.ts`). Two exceptions. The UDD `acronym` is
25
+ * stored as `shortName`: a top-level `acronym` key marks a pre-pl-958 PAVE row
26
+ * (`organizationRowShape`), and PAVE 2.0 already writes `shortName`. And the
27
+ * UDD `id` (the Org's one identifier, a slug such as `the_spring`) is stored as
28
+ * `key`: Mongoose gives every document an `id` of its own (the `_id` as a
29
+ * string), and the Admin Hub's curated store already names it `key`.
27
30
  *
28
31
  * ## What is NOT here
29
32
  *
@@ -87,6 +90,7 @@ export function isListedOrganization(row: {
87
90
  * fragment's declaration order (`orgRecordSchemaDefinition`).
88
91
  */
89
92
  export const ORG_RECORD_FIELD_NAMES = Object.freeze([
93
+ "key",
90
94
  "legalName",
91
95
  "commonName",
92
96
  "shortName",
@@ -159,6 +163,40 @@ export const ORGANIZATION_ENVELOPE_KEYS = Object.freeze([
159
163
  "updatedTime",
160
164
  ] as const);
161
165
 
166
+ // ─── The identifier ─────────────────────────────────────────────────
167
+
168
+ /**
169
+ * The Org's identifier (UDD Org `id`; stored as `key`): the one value that
170
+ * names the same organization in every database, where `_id` is each
171
+ * database's own. A lower-case slug: `the_spring`, `ascension_stjohn`,
172
+ * `org-custom-8daxtira`, `org-6a1f5dadd0c33a5a149f3413`.
173
+ *
174
+ * Rules (the curated store's, Kickoff 13 item 3): unique; never changes once
175
+ * set; never taken from a request body (`OrgIdentityWriteSchema` is strict and
176
+ * does not name it); a new organization's key never encodes its name
177
+ * ({@link mintOrgKey}). A row written before 0.65.0 has none until the
178
+ * registry fill stamps one from a reviewed sheet.
179
+ */
180
+ export const ORG_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,119}$/;
181
+
182
+ /** Whether a value is a well-formed Org identifier. */
183
+ export function isOrgKey(value: unknown): value is string {
184
+ return typeof value === "string" && ORG_KEY_PATTERN.test(value);
185
+ }
186
+
187
+ /**
188
+ * The identifier for an organization created without one (added inside an
189
+ * app, or by a steward typing a new organization): `org-<its _id>`. It encodes
190
+ * no name, so a later rename never makes it wrong.
191
+ */
192
+ export function mintOrgKey(id: string | { toHexString(): string }): string {
193
+ const hex = (typeof id === "string" ? id : id.toHexString()).trim().toLowerCase();
194
+ if (!/^[0-9a-f]{24}$/.test(hex)) {
195
+ throw new Error("mintOrgKey: needs the organization's 24-hex _id");
196
+ }
197
+ return `org-${hex}`;
198
+ }
199
+
162
200
  // ─── Write shape ────────────────────────────────────────────────────
163
201
 
164
202
  /** A trimmed, non-empty line of text, or null to clear the field. */
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  import { OrganizationProgramRowSchema, type OrganizationProgramRow } from "./schemas.js";
10
- import { isListedOrganization, type OrgReviewStatus } from "./orgRecord.js";
10
+ import { isListedOrganization, isOrgKey, type OrgReviewStatus } from "./orgRecord.js";
11
11
  import { isLiveOrganizationProgram, isProgramReviewStatus } from "./vocabulary.js";
12
12
 
13
13
  /** A driver ObjectId, or anything that prints itself as one. */
@@ -136,6 +136,8 @@ export interface DirectoryOrganizationView {
136
136
  agencyScope: string | null;
137
137
  canonicalKey: string | null;
138
138
  // ── The Org record (`orgRecord.ts`); null = not captured ──
139
+ /** The Org's identifier (the UDD `id`): the same in every database. Null on a row not yet given one. */
140
+ key: string | null;
139
141
  legalName: string | null;
140
142
  commonName: string | null;
141
143
  /**
@@ -193,6 +195,7 @@ export function toDirectoryOrganizationView(raw: unknown): DirectoryOrganization
193
195
  agencyId: directoryIdString(r.agencyId),
194
196
  agencyScope: directoryIdString(r.agencyScope),
195
197
  canonicalKey: text(r.canonicalKey),
198
+ key: isOrgKey(r.key) ? r.key : null,
196
199
  legalName: line(r.legalName),
197
200
  commonName: line(r.commonName),
198
201
  shortName: line(r.shortName) ?? line(r.acronym),
@@ -138,6 +138,9 @@ export {
138
138
  // (`addOrgRecordFields`) and the whole-row check (`organizationSchemaIssues`)
139
139
  export {
140
140
  orgRecordSchemaDefinition,
141
+ ORG_KEY_INDEX_NAME,
142
+ ORG_KEY_INDEX_OPTIONS,
143
+ ORG_KEY_INDEX_SPEC,
141
144
  orgAsBuiltSchemaDefinition,
142
145
  addOrgRecordFields,
143
146
  organizationSchemaIssues,
@@ -22,6 +22,7 @@ import {
22
22
  ORG_AS_BUILT_FIELD_NAMES,
23
23
  ORG_RECORD_FIELD_NAMES,
24
24
  ORG_REVIEW_STATUS_VALUES,
25
+ isOrgKey,
25
26
  } from "../orgDirectory/orgRecord.js";
26
27
  import {
27
28
  installVspTwoStepHooks,
@@ -31,6 +32,22 @@ import {
31
32
 
32
33
  const HEX_24 = /^[0-9a-fA-F]{24}$/;
33
34
 
35
+ /** The name of the unique index on `key` (the same in every app, so they never conflict). */
36
+ export const ORG_KEY_INDEX_NAME = "org_key_unique";
37
+
38
+ /**
39
+ * The unique index on `key`, as one definition: the mount below declares it,
40
+ * and the registry fill's key sheet builds the same index before it writes.
41
+ * Partial: a row with no key, or a null one, is not indexed, so it never
42
+ * collides. Copy these before handing them to a driver (they are frozen).
43
+ */
44
+ export const ORG_KEY_INDEX_SPEC = Object.freeze({ key: 1 as const });
45
+ export const ORG_KEY_INDEX_OPTIONS = Object.freeze({
46
+ name: ORG_KEY_INDEX_NAME,
47
+ unique: true,
48
+ partialFilterExpression: Object.freeze({ key: Object.freeze({ $type: "string" }) }),
49
+ });
50
+
34
51
  /** An id in auth's stored form: an ObjectId, or a non-empty string (a dev seed's slug). */
35
52
  function isStoredDirectoryId(value: unknown): boolean {
36
53
  if (value == null) return true;
@@ -48,6 +65,37 @@ function isStoredDirectoryId(value: unknown): boolean {
48
65
  * so "not captured" stays distinct from an answer.
49
66
  */
50
67
  export const orgRecordSchemaDefinition = {
68
+ /**
69
+ * The Org's identifier (the UDD `id`): the same value in every database.
70
+ * Never taken from a request body.
71
+ *
72
+ * `immutable` means the model stores a key only while it is creating the
73
+ * row. Measured on Mongoose 9.3.1 against MongoDB (the fill's test file
74
+ * holds each line):
75
+ *
76
+ * - `new Model({ key }).save()` and `Model.create({ key })` store it.
77
+ * - An upsert stores it when the upsert inserts the row (`$setOnInsert`, or
78
+ * `$set`, which Mongoose moves to `$setOnInsert`); on a row that already
79
+ * exists the upsert leaves `key` as it was.
80
+ * - On a row that already exists, `doc.key = …; doc.save()` and
81
+ * `updateOne` / `findOneAndUpdate` with `$set: { key }` do NOT write it,
82
+ * and do not report an error. That holds whether the row has a key or has
83
+ * none yet, so a model cannot give an old row its first key either.
84
+ *
85
+ * So an app stores `key: mintOrgKey(_id)` where it creates the
86
+ * organization (`new Model().save()`, `create()`, or `$setOnInsert` on an
87
+ * upsert). Rows that already exist get theirs from the registry fill's key
88
+ * sheet, which writes with the plain MongoDB driver.
89
+ */
90
+ key: {
91
+ type: String,
92
+ trim: true,
93
+ immutable: true,
94
+ validate: {
95
+ validator: (value: unknown): boolean => value == null || isOrgKey(value),
96
+ message: "key must be a lower-case slug (a-z, 0-9, _ and -)",
97
+ },
98
+ },
51
99
  /** The canonical reporting name (HMIS, funders). Readers fall back to `name`. */
52
100
  legalName: { type: String, trim: true },
53
101
  /** The name people use, when it differs from `name`. */
@@ -125,6 +173,15 @@ export function addOrgRecordFields<S extends Schema>(
125
173
  options: AddAgencyOrgTypeFieldsOptions = {},
126
174
  ): S {
127
175
  schema.add(orgRecordSchemaDefinition);
176
+ // One organization per identifier. Partial: a row without a key (every row
177
+ // written before 0.65.0) is not indexed, so it never collides.
178
+ schema.index(
179
+ { ...ORG_KEY_INDEX_SPEC },
180
+ {
181
+ ...ORG_KEY_INDEX_OPTIONS,
182
+ partialFilterExpression: { key: { ...ORG_KEY_INDEX_OPTIONS.partialFilterExpression.key } },
183
+ },
184
+ );
128
185
  for (const key of ORG_AS_BUILT_FIELD_NAMES) {
129
186
  if (schema.pathType(key) === "adhocOrUndefined") {
130
187
  schema.add({ [key]: orgAsBuiltSchemaDefinition[key] });
@@ -134,6 +191,7 @@ export function addOrgRecordFields<S extends Schema>(
134
191
  }
135
192
 
136
193
  const EXPECTED_INSTANCE: Record<string, string> = {
194
+ key: "String",
137
195
  legalName: "String",
138
196
  commonName: "String",
139
197
  shortName: "String",