@indigoai-us/hq-cli 5.51.0 → 5.53.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.
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Unit tests for `hq company settings set` (company.ts).
3
+ *
4
+ * Mirrors members.test.ts: mock ensureCognitoToken + getEntityUid, spy on
5
+ * global fetch, drive through a Commander program, assert the PUT
6
+ * /company-settings request shape + exit behavior.
7
+ */
8
+
9
+ import { Command } from "commander";
10
+ import {
11
+ afterEach,
12
+ beforeEach,
13
+ describe,
14
+ expect,
15
+ it,
16
+ vi,
17
+ type MockInstance,
18
+ } from "vitest";
19
+
20
+ vi.mock("../utils/cognito-session.js", async (importOriginal) => {
21
+ const original =
22
+ await importOriginal<typeof import("../utils/cognito-session.js")>();
23
+ return {
24
+ ...original,
25
+ ensureCognitoToken: vi.fn(async () => "test-token"),
26
+ };
27
+ });
28
+
29
+ vi.mock("../utils/vault-api.js", async (importOriginal) => {
30
+ const original = await importOriginal<typeof import("../utils/vault-api.js")>();
31
+ return {
32
+ ...original,
33
+ getEntityUid: vi.fn(async () => "cmp_acme"),
34
+ };
35
+ });
36
+
37
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
38
+ import { getEntityUid } from "../utils/vault-api.js";
39
+ import { registerCompanyCommand } from "./company.js";
40
+
41
+ function jsonResponse(status: number, body: unknown): Response {
42
+ return new Response(JSON.stringify(body), {
43
+ status,
44
+ headers: { "Content-Type": "application/json" },
45
+ });
46
+ }
47
+
48
+ let fetchSpy: MockInstance<typeof fetch>;
49
+ let exitSpy: MockInstance<typeof process.exit>;
50
+ const mockEnsureCognitoToken = vi.mocked(ensureCognitoToken);
51
+ const mockGetEntityUid = vi.mocked(getEntityUid);
52
+
53
+ beforeEach(() => {
54
+ vi.clearAllMocks();
55
+ fetchSpy = vi.spyOn(globalThis, "fetch");
56
+ mockEnsureCognitoToken.mockResolvedValue("test-token");
57
+ mockGetEntityUid.mockResolvedValue("cmp_acme");
58
+ exitSpy = vi
59
+ .spyOn(process, "exit")
60
+ .mockImplementation((code?: number) => {
61
+ throw new Error(`process.exit(${code})`);
62
+ }) as unknown as MockInstance<typeof process.exit>;
63
+ vi.spyOn(console, "log").mockImplementation(() => {});
64
+ vi.spyOn(console, "error").mockImplementation(() => {});
65
+ });
66
+
67
+ afterEach(() => {
68
+ vi.restoreAllMocks();
69
+ });
70
+
71
+ function buildProgram(): Command {
72
+ const program = new Command();
73
+ program.name("hq").exitOverride();
74
+ registerCompanyCommand(program);
75
+ return program;
76
+ }
77
+
78
+ async function run(args: string[]): Promise<void> {
79
+ await buildProgram().parseAsync(["node", "hq", ...args]);
80
+ }
81
+
82
+ describe("hq company settings set", () => {
83
+ it("PUTs crmEnabled=true with the resolved companyUid", async () => {
84
+ fetchSpy.mockResolvedValueOnce(
85
+ jsonResponse(200, { companySettings: { crmEnabled: true } }),
86
+ );
87
+
88
+ await run([
89
+ "company",
90
+ "settings",
91
+ "set",
92
+ "--company",
93
+ "acme",
94
+ "--crm-enabled",
95
+ "true",
96
+ ]);
97
+
98
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
99
+ const [url, init] = fetchSpy.mock.calls[0];
100
+ expect(String(url)).toContain("/company-settings");
101
+ expect(init?.method).toBe("PUT");
102
+ const sent = JSON.parse(init?.body as string);
103
+ expect(sent).toMatchObject({ companyUid: "cmp_acme", crmEnabled: true });
104
+ expect(sent.ontologyEnabled).toBeUndefined();
105
+ });
106
+
107
+ it("PUTs both flags when both are supplied", async () => {
108
+ fetchSpy.mockResolvedValueOnce(jsonResponse(200, {}));
109
+
110
+ await run([
111
+ "company",
112
+ "settings",
113
+ "set",
114
+ "--company",
115
+ "acme",
116
+ "--crm-enabled",
117
+ "false",
118
+ "--ontology-enabled",
119
+ "true",
120
+ ]);
121
+
122
+ const sent = JSON.parse(fetchSpy.mock.calls[0][1]?.body as string);
123
+ expect(sent).toMatchObject({
124
+ companyUid: "cmp_acme",
125
+ crmEnabled: false,
126
+ ontologyEnabled: true,
127
+ });
128
+ });
129
+
130
+ it("requires at least one flag", async () => {
131
+ await expect(
132
+ run(["company", "settings", "set", "--company", "acme"]),
133
+ ).rejects.toThrow("process.exit(1)");
134
+ expect(fetchSpy).not.toHaveBeenCalled();
135
+ });
136
+
137
+ it("requires --company", async () => {
138
+ await expect(
139
+ run(["company", "settings", "set", "--crm-enabled", "true"]),
140
+ ).rejects.toThrow("process.exit(1)");
141
+ expect(fetchSpy).not.toHaveBeenCalled();
142
+ });
143
+
144
+ it("rejects a non-boolean flag value", async () => {
145
+ await expect(
146
+ run([
147
+ "company",
148
+ "settings",
149
+ "set",
150
+ "--company",
151
+ "acme",
152
+ "--crm-enabled",
153
+ "yes",
154
+ ]),
155
+ ).rejects.toThrow("process.exit(1)");
156
+ expect(fetchSpy).not.toHaveBeenCalled();
157
+ });
158
+
159
+ it("exits 1 on a 403 (non-owner)", async () => {
160
+ fetchSpy.mockResolvedValueOnce(
161
+ jsonResponse(403, { error: "Requires owner role", code: "FORBIDDEN" }),
162
+ );
163
+
164
+ await expect(
165
+ run([
166
+ "company",
167
+ "settings",
168
+ "set",
169
+ "--company",
170
+ "acme",
171
+ "--crm-enabled",
172
+ "true",
173
+ ]),
174
+ ).rejects.toThrow("process.exit(1)");
175
+ expect(exitSpy).toHaveBeenCalledWith(1);
176
+ });
177
+ });
@@ -0,0 +1,132 @@
1
+ import { Command } from "commander";
2
+ import chalk from "chalk";
3
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
4
+ import { vaultApiFetch, getEntityUid } from "../utils/vault-api.js";
5
+
6
+ /**
7
+ * `hq company settings set` — owner-only per-company settings toggles
8
+ * (agency group-grants US-007 / hq-native-crm US-003). Wraps
9
+ * `PUT /company-settings`, setting the runtime-flippable `crmEnabled` /
10
+ * `ontologyEnabled` flags so an owner can enable the native CRM (and the
11
+ * ontology gardener) for a company without a redeploy.
12
+ *
13
+ * Conventions mirror `secrets.ts`: ensureCognitoToken() → getEntityUid() →
14
+ * vaultApiFetch() → error-check → chalk output.
15
+ */
16
+
17
+ interface SettingsSetFlags {
18
+ crmEnabled?: string;
19
+ ontologyEnabled?: string;
20
+ }
21
+
22
+ /**
23
+ * Parse a `--flag <true|false>` string into a boolean, or throw. Commander
24
+ * passes the raw string; we validate strictly so a typo never silently writes
25
+ * the wrong value.
26
+ */
27
+ function parseBoolFlag(value: string, flag: string): boolean {
28
+ const v = value.trim().toLowerCase();
29
+ if (v === "true") return true;
30
+ if (v === "false") return false;
31
+ throw new Error(`${flag} must be 'true' or 'false' (got '${value}')`);
32
+ }
33
+
34
+ export function registerCompanyCommand(program: Command): void {
35
+ const company = program
36
+ .command("company")
37
+ .description("Company-level settings")
38
+ .option("--company <slug>", "Company slug (resolves to companyUid)");
39
+
40
+ const settings = company
41
+ .command("settings")
42
+ .description("Per-company settings (owner-only)");
43
+
44
+ settings
45
+ .command("set")
46
+ .description(
47
+ "Set per-company settings (PUT /company-settings). Require at least one " +
48
+ "of --crm-enabled / --ontology-enabled.",
49
+ )
50
+ .option(
51
+ "--crm-enabled <true|false>",
52
+ "Enable/disable the native CRM for this company",
53
+ )
54
+ .option(
55
+ "--ontology-enabled <true|false>",
56
+ "Enable/disable the ontology gardener for this company",
57
+ )
58
+ .action(async (opts: SettingsSetFlags) => {
59
+ try {
60
+ const companySlug = company.opts().company as string | undefined;
61
+ if (!companySlug) {
62
+ console.error(chalk.red("Error: --company <slug> is required."));
63
+ process.exit(1);
64
+ }
65
+ if (opts.crmEnabled === undefined && opts.ontologyEnabled === undefined) {
66
+ console.error(
67
+ chalk.red(
68
+ "Error: provide at least one of --crm-enabled / --ontology-enabled.",
69
+ ),
70
+ );
71
+ process.exit(1);
72
+ }
73
+
74
+ const body: Record<string, unknown> = {};
75
+ if (opts.crmEnabled !== undefined) {
76
+ body.crmEnabled = parseBoolFlag(opts.crmEnabled, "--crm-enabled");
77
+ }
78
+ if (opts.ontologyEnabled !== undefined) {
79
+ body.ontologyEnabled = parseBoolFlag(
80
+ opts.ontologyEnabled,
81
+ "--ontology-enabled",
82
+ );
83
+ }
84
+
85
+ const token = await ensureCognitoToken();
86
+ const companyUid = await getEntityUid(token, { companySlug });
87
+ body.companyUid = companyUid;
88
+
89
+ const res = await vaultApiFetch({
90
+ token,
91
+ path: "/company-settings",
92
+ method: "PUT",
93
+ body,
94
+ });
95
+
96
+ if (!res.ok) {
97
+ const errBody = (await res.json().catch(() => ({}))) as Record<
98
+ string,
99
+ unknown
100
+ >;
101
+ if (res.status === 403) {
102
+ console.error(
103
+ chalk.red(
104
+ "Requires owner role on this company to change its settings.",
105
+ ),
106
+ );
107
+ process.exit(1);
108
+ }
109
+ console.error(
110
+ chalk.red(
111
+ `Failed to update company settings: ${(errBody.error as string) ?? res.statusText}`,
112
+ ),
113
+ );
114
+ process.exit(1);
115
+ }
116
+
117
+ const applied = Object.entries(body)
118
+ .filter(([k]) => k !== "companyUid")
119
+ .map(([k, v]) => `${k}=${v}`)
120
+ .join(", ");
121
+ console.log(
122
+ chalk.green(`Company settings updated for ${companySlug}: ${applied}`),
123
+ );
124
+ } catch (err) {
125
+ console.error(
126
+ chalk.red("Error:"),
127
+ err instanceof Error ? err.message : String(err),
128
+ );
129
+ process.exit(1);
130
+ }
131
+ });
132
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Unit tests for `hq crm entity upsert` (crm.ts).
3
+ *
4
+ * Mirrors members.test.ts: mock ensureCognitoToken + getEntityUid, spy on
5
+ * global fetch (vaultApiFetch's transport), drive the command through a
6
+ * Commander program, and assert the request shape + output / exit behavior.
7
+ */
8
+
9
+ import { Command } from "commander";
10
+ import {
11
+ afterEach,
12
+ beforeEach,
13
+ describe,
14
+ expect,
15
+ it,
16
+ vi,
17
+ type MockInstance,
18
+ } from "vitest";
19
+
20
+ vi.mock("../utils/cognito-session.js", async (importOriginal) => {
21
+ const original =
22
+ await importOriginal<typeof import("../utils/cognito-session.js")>();
23
+ return {
24
+ ...original,
25
+ ensureCognitoToken: vi.fn(async () => "test-token"),
26
+ };
27
+ });
28
+
29
+ vi.mock("../utils/vault-api.js", async (importOriginal) => {
30
+ const original = await importOriginal<typeof import("../utils/vault-api.js")>();
31
+ return {
32
+ ...original,
33
+ getEntityUid: vi.fn(async () => "cmp_acme"),
34
+ };
35
+ });
36
+
37
+ import { ensureCognitoToken } from "../utils/cognito-session.js";
38
+ import { getEntityUid } from "../utils/vault-api.js";
39
+ import { registerCrmCommand } from "./crm.js";
40
+
41
+ function jsonResponse(status: number, body: unknown): Response {
42
+ return new Response(JSON.stringify(body), {
43
+ status,
44
+ headers: { "Content-Type": "application/json" },
45
+ });
46
+ }
47
+
48
+ let fetchSpy: MockInstance<typeof fetch>;
49
+ let exitSpy: MockInstance<typeof process.exit>;
50
+ const mockEnsureCognitoToken = vi.mocked(ensureCognitoToken);
51
+ const mockGetEntityUid = vi.mocked(getEntityUid);
52
+
53
+ beforeEach(() => {
54
+ vi.clearAllMocks();
55
+ fetchSpy = vi.spyOn(globalThis, "fetch");
56
+ mockEnsureCognitoToken.mockResolvedValue("test-token");
57
+ mockGetEntityUid.mockResolvedValue("cmp_acme");
58
+ // process.exit(1) on the error paths — throw so the test can assert instead
59
+ // of tearing down the worker.
60
+ exitSpy = vi
61
+ .spyOn(process, "exit")
62
+ .mockImplementation((code?: number) => {
63
+ throw new Error(`process.exit(${code})`);
64
+ }) as unknown as MockInstance<typeof process.exit>;
65
+ vi.spyOn(console, "log").mockImplementation(() => {});
66
+ vi.spyOn(console, "error").mockImplementation(() => {});
67
+ });
68
+
69
+ afterEach(() => {
70
+ vi.restoreAllMocks();
71
+ });
72
+
73
+ function buildProgram(): Command {
74
+ const program = new Command();
75
+ program.name("hq").exitOverride();
76
+ registerCrmCommand(program);
77
+ return program;
78
+ }
79
+
80
+ async function run(args: string[]): Promise<void> {
81
+ await buildProgram().parseAsync(["node", "hq", ...args]);
82
+ }
83
+
84
+ describe("hq crm entity upsert", () => {
85
+ it("flag form: POSTs a single entity to /crm/entities with external_ids", async () => {
86
+ fetchSpy.mockResolvedValueOnce(
87
+ jsonResponse(200, {
88
+ status: "written",
89
+ created: 1,
90
+ updated: 0,
91
+ skipped: 0,
92
+ errors: [],
93
+ }),
94
+ );
95
+
96
+ await run([
97
+ "crm",
98
+ "entity",
99
+ "upsert",
100
+ "--company",
101
+ "acme",
102
+ "--type",
103
+ "contact",
104
+ "--name",
105
+ "Jane Prospect",
106
+ "--attio-id",
107
+ "rec_jane",
108
+ ]);
109
+
110
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
111
+ const [url, init] = fetchSpy.mock.calls[0];
112
+ expect(String(url)).toContain("/crm/entities");
113
+ expect(init?.method).toBe("POST");
114
+ const sent = JSON.parse(init?.body as string);
115
+ expect(sent.companyUid).toBe("cmp_acme");
116
+ expect(sent.entities).toHaveLength(1);
117
+ expect(sent.entities[0]).toMatchObject({
118
+ type: "contact",
119
+ canonical_name: "Jane Prospect",
120
+ external_ids: { attio: "rec_jane" },
121
+ });
122
+ });
123
+
124
+ it("exits 1 with a helpful message on 403 CRM_DISABLED", async () => {
125
+ fetchSpy.mockResolvedValueOnce(
126
+ jsonResponse(403, {
127
+ error: "the native CRM is not enabled for this company",
128
+ code: "CRM_DISABLED",
129
+ }),
130
+ );
131
+
132
+ await expect(
133
+ run([
134
+ "crm",
135
+ "entity",
136
+ "upsert",
137
+ "--company",
138
+ "acme",
139
+ "--type",
140
+ "contact",
141
+ "--name",
142
+ "Jane",
143
+ ]),
144
+ ).rejects.toThrow("process.exit(1)");
145
+ expect(exitSpy).toHaveBeenCalledWith(1);
146
+ });
147
+
148
+ it("requires --company", async () => {
149
+ await expect(
150
+ run(["crm", "entity", "upsert", "--type", "contact", "--name", "Jane"]),
151
+ ).rejects.toThrow("process.exit(1)");
152
+ // Never made the request — failed before token resolution.
153
+ expect(fetchSpy).not.toHaveBeenCalled();
154
+ });
155
+
156
+ it("requires --type when no --json is given", async () => {
157
+ await expect(
158
+ run(["crm", "entity", "upsert", "--company", "acme", "--name", "Jane"]),
159
+ ).rejects.toThrow("process.exit(1)");
160
+ expect(fetchSpy).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it("rejects an unknown --type", async () => {
164
+ await expect(
165
+ run([
166
+ "crm",
167
+ "entity",
168
+ "upsert",
169
+ "--company",
170
+ "acme",
171
+ "--type",
172
+ "widget",
173
+ "--name",
174
+ "Jane",
175
+ ]),
176
+ ).rejects.toThrow("process.exit(1)");
177
+ expect(fetchSpy).not.toHaveBeenCalled();
178
+ });
179
+ });