Iru Laptop Refresh with CDW Orders
Draft
Iru Laptop Refresh with CDW Orders
Draft
Press a step to see its codeList the Macs in Iru, lines 244 to 270Look up each person, lines 272 to 286Summarize the batch, lines 288 to 301Order each replacement from CDW, lines 303 to 334

List the Macs in Iru

Iru has no purchase date, so a Mac's age counts from its first enrollment.

for (let page = 0; page < MAX_PAGES && !done; page++)

response.status_code !== 200

Fail

`Iru returned ${response.status_code} listing devices. Check the ` + "API URL and that IRU_API_TOKEN can list…

Look up each person

Title and department pick the model; the address is where CDW ships.

for (const email of candidates.slice(0, MAX_BATCH))

Summarize the batch

due.length === 0 || !params.place_orders

Return

return

Order each replacement from CDW

One person's order failing doesn't stop the others.

for (const refresh of due)

Return

return

body
true
false
done
done
true
false
done
1// Find the Macs in Iru that are due for a refresh, pick each person's
2// replacement from your hardware standard by title and department, and, once
3// someone has approved the batch, order each replacement from CDW, shipped to
4// the person's home.
5//
6// Run it twice: a scheduled automation runs it with place_orders off and
7// emails empty, to list everyone due across the fleet; after approval, a
8// runbook runs it with place_orders on and the approved people's emails.
9//
10// Before publishing: replace acme.api.kandji.io with your Iru API URL
11// (Settings > Access > API in Iru; EU tenants use api.eu.kandji.io), in
12// `domains` and the request below. Set IRU_API_TOKEN to an Iru API token
13// that can list devices. Set CDW_SUBSCRIPTION_KEY to a key for the Customers
14// product in CDW's developer portal. Replace CDW_CUSTOMER_ID with the
15// customer ID your CDW account team registered, and fill in SPEC from your
16// hardware standard.
17
18type Spec = { model: string; cdwItem: string; price: number };
19
20type ShipTo = {
21 name: string;
22 street: string;
23 city: string;
24 state: string;
25 zip: string;
26 country: string;
27};
28
29type Person = {
30 email: string;
31 name: string;
32 role: string;
33 shipTo: ShipTo | null;
34};
35
36type Mac = { name: string; serial: string; model: string; enrolled: string };
37
38type Refresh = { person: Person; mac: Mac; spec: Spec };
39
40export const input = z.object({
41 emails: z
42 .array(z.string().email())
43 .max(50)
44 .default([])
45 .describe(
46 "Work emails to check. Leave empty to check every Mac in Iru and " +
47 "list everyone due",
48 ),
49 min_age_years: z
50 .number()
51 .min(1)
52 .max(6)
53 .default(3)
54 .describe("Replace Macs at least this many years old"),
55 place_orders: z
56 .boolean()
57 .default(false)
58 .describe(
59 "Place the CDW orders. Off, it only reports who is due and what " +
60 "each person gets",
61 ),
62});
63
64// Iru is read only. CDW takes the orders.
65export const domains = {
66 "acme.api.kandji.io": "read",
67 "apiconnect.cdw.com": "read_write",
68};
69
70const CDW_CUSTOMER_ID = "your-cdw-customer-id";
71
72// Your hardware standard: the first entry whose keyword appears in a
73// person's title or department wins, and everyone else gets DEFAULT_SPEC.
74// CDW item numbers and prices come from your CDW quote.
75const SPEC: Array<Spec & { keywords: string[] }> = [
76 {
77 keywords: ["engineer", "data", "machine learning"],
78 model: 'MacBook Pro 16" M4 Pro, 48GB',
79 cdwItem: "8100121",
80 price: 2899,
81 },
82 {
83 keywords: ["design", "video", "brand"],
84 model: 'MacBook Pro 14" M4 Max, 36GB',
85 cdwItem: "8100134",
86 price: 3199,
87 },
88];
89const DEFAULT_SPEC: Spec = {
90 model: 'MacBook Air 15" M4, 24GB',
91 cdwItem: "8100150",
92 price: 1599,
93};
94
95// Iru returns at most 300 devices a page; ten pages cover 3,000 Macs. One
96// run checks at most 50 people, oldest Macs first.
97const PAGE_SIZE = 300;
98const MAX_PAGES = 10;
99const MAX_BATCH = 50;
100
101const YEAR_MS = 365.25 * 24 * 60 * 60 * 1000;
102
103const usd = (amount: number): string => `$${amount.toLocaleString("en-US")}`;
104
105const isObject = (value: unknown): value is Record<string, unknown> =>
106 typeof value === "object" && value !== null;
107
108const text = (value: unknown, key: string): string =>
109 isObject(value) && typeof value[key] === "string" ? value[key].trim() : "";
110
111// Iru gives a device's user as an object with an email, or as a string.
112const userEmail = (device: unknown): string => {
113 const user = isObject(device) ? device.user : null;
114 const email = typeof user === "string" ? user : text(user, "email");
115 return email.includes("@") ? email.toLowerCase() : "";
116};
117
118const toMac = (device: unknown): Mac => ({
119 name: text(device, "device_name") || "Unnamed Mac",
120 serial: text(device, "serial_number"),
121 model: text(device, "model") || "Mac",
122 enrolled: text(device, "first_enrollment").slice(0, 10),
123});
124
125// Each person's oldest Mac, by first enrollment: the one a refresh replaces.
126const oldestMacs = (devices: unknown[]): Map<string, Mac> => {
127 const oldest = new Map<string, Mac>();
128 for (const device of devices) {
129 const email = userEmail(device);
130 const mac = toMac(device);
131 const current = oldest.get(email);
132 const older = current === undefined || mac.enrolled < current.enrolled;
133 if (email && mac.serial && mac.enrolled && older) {
134 oldest.set(email, mac);
135 }
136 }
137 return oldest;
138};
139
140const ageYears = (mac: Mac): number =>
141 (Date.now() - Date.parse(mac.enrolled)) / YEAR_MS;
142
143// Everyone with a Mac old enough to replace, oldest first.
144const dueEmails = (macs: Map<string, Mac>, minAgeYears: number): string[] =>
145 [...macs.entries()]
146 .filter(([, mac]) => ageYears(mac) >= minAgeYears)
147 .sort(([, a], [, b]) => a.enrolled.localeCompare(b.enrolled))
148 .map(([email]) => email);
149
150// The Okta profile's address fields, kept current by your HR system's sync.
151const toShipTo = (name: string, profile: unknown): ShipTo | null => {
152 const shipTo = {
153 name,
154 street: text(profile, "streetAddress"),
155 city: text(profile, "city"),
156 state: text(profile, "state"),
157 zip: text(profile, "zipCode"),
158 country: text(profile, "countryCode") || "US",
159 };
160 return shipTo.street && shipTo.city && shipTo.zip ? shipTo : null;
161};
162
163const toPerson = (email: string, profile: unknown): Person => {
164 const name = text(profile, "displayName") || email;
165 return {
166 email,
167 name,
168 role: `${text(profile, "title")} ${text(profile, "department")}`,
169 shipTo: toShipTo(name, profile),
170 };
171};
172
173const specFor = (person: Person): Spec => {
174 const role = person.role.toLowerCase();
175 return (
176 SPEC.find((spec) => spec.keywords.some((word) => role.includes(word))) ??
177 DEFAULT_SPEC
178 );
179};
180
181// A refresh for the person, or why they are left out of this batch.
182const checkRefresh = (
183 email: string,
184 profile: unknown,
185 mac: Mac | null,
186 minAgeYears: number,
187): Refresh | string => {
188 if (profile === null) {
189 return `• ${email}: not in the directory`;
190 }
191 const person = toPerson(email, profile);
192 if (mac === null) {
193 return `• ${person.name}: no Mac assigned in Iru`;
194 }
195 const age = ageYears(mac).toFixed(1);
196 if (ageYears(mac) < minAgeYears) {
197 return `• ${person.name}: ${mac.model} is ${age} years old, not due yet`;
198 }
199 if (person.shipTo === null) {
200 return `• ${person.name}: no home address on their Okta profile`;
201 }
202 return { person, mac, spec: specFor(person) };
203};
204
205const isRefresh = (check: Refresh | string): check is Refresh =>
206 typeof check !== "string";
207
208const refreshLine = ({ person, mac, spec }: Refresh): string =>
209 `• ${person.name} (${person.email}): ${mac.model} (${mac.serial}, ` +
210 `${ageYears(mac).toFixed(1)} years) → ${spec.model}, ${usd(spec.price)}`;
211
212// One order per person, keyed by the serial of the Mac it replaces. The
213// header fields are CDW's; check the ship-to and line field names against
214// the Customer Order API schema in your developer portal subscription.
215const orderFor = ({ person, mac, spec }: Refresh, today: string) => ({
216 orderHeader: {
217 customerId: CDW_CUSTOMER_ID,
218 orderId: `REFRESH-${mac.serial}`,
219 orderDate: today,
220 orderAmount: spec.price.toFixed(2),
221 currency: "USD",
222 shipTo: person.shipTo,
223 },
224 orderLines: [
225 {
226 lineNumber: 1,
227 cdwItemNumber: spec.cdwItem,
228 quantity: 1,
229 unitPrice: spec.price.toFixed(2),
230 description: `${spec.model} for ${person.email}`,
231 },
232 ],
233});
234
235const accepted = (response: { status_code: number; body: unknown }) =>
236 response.status_code >= 200 &&
237 response.status_code < 300 &&
238 text(response.body, "statusCode") !== "REJECTED";
239
240const orderLine = ({ refresh }: { refresh: Refresh }): string =>
241 `• ${refresh.person.name}: order REFRESH-${refresh.mac.serial}`;
242
243export default async function run(params: z.infer<typeof input>) {
244 // **List the Macs in Iru**
245 // Iru has no purchase date, so a Mac's age counts from its first enrollment.
246 const devices: unknown[] = [];
247 let done = false;
248 for (let page = 0; page < MAX_PAGES && !done; page++) {
249 const response = await http.get(
250 "https://acme.api.kandji.io/api/v1/devices",
251 {
252 query: {
253 platform: "Mac",
254 limit: String(PAGE_SIZE),
255 offset: String(page * PAGE_SIZE),
256 },
257 auth: { type: "bearer", token: env.IRU_API_TOKEN },
258 },
259 );
260 if (response.status_code !== 200) {
261 fail(
262 `Iru returned ${response.status_code} listing devices. Check the ` +
263 "API URL and that IRU_API_TOKEN can list devices.",
264 );
265 }
266 const batch = Array.isArray(response.body) ? response.body : [];
267 devices.push(...batch);
268 done = batch.length < PAGE_SIZE;
269 }
270 const macs = oldestMacs(devices);
271
272 // **Look up each person**
273 // Title and department pick the model; the address is where CDW ships.
274 const asked = params.emails.map((email) => email.toLowerCase());
275 const candidates =
276 asked.length > 0 ? asked : dueEmails(macs, params.min_age_years);
277 const checks: Array<Refresh | string> = [];
278 for (const email of candidates.slice(0, MAX_BATCH)) {
279 const profile = await risotto.get_user_profile({ email });
280 const mac = macs.get(email) ?? null;
281 checks.push(checkRefresh(email, profile, mac, params.min_age_years));
282 }
283 const due = checks.filter(isRefresh);
284 const skipped = checks.filter(
285 (check): check is string => typeof check === "string",
286 );
287
288 // **Summarize the batch**
289 const total = due.reduce((sum, { spec }) => sum + spec.price, 0);
290 const cutOff =
291 candidates.length > MAX_BATCH
292 ? ` Showing the oldest ${MAX_BATCH} of ${candidates.length}.`
293 : "";
294 const summary = [
295 `${due.length} due for a refresh, ${usd(total)} in all.${cutOff}`,
296 ...due.map(refreshLine),
297 ...(skipped.length > 0 ? ["Left out:", ...skipped] : []),
298 ].join("\n");
299 if (due.length === 0 || !params.place_orders) {
300 return summary;
301 }
302
303 // **Order each replacement from CDW**
304 // One person's order failing doesn't stop the others.
305 const today = new Date().toISOString().slice(0, 10);
306 const orders: Array<{ refresh: Refresh; status: number; ok: boolean }> = [];
307 for (const refresh of due) {
308 const response = await http.post(
309 "https://apiconnect.cdw.com/v1/customers/orders",
310 {
311 auth: {
312 type: "api_key_header",
313 header: "Ocp-Apim-Subscription-Key",
314 value: env.CDW_SUBSCRIPTION_KEY,
315 },
316 json: orderFor(refresh, today),
317 },
318 );
319 orders.push({
320 refresh,
321 status: response.status_code,
322 ok: accepted(response),
323 });
324 }
325 const placed = orders.filter(({ ok }) => ok).map(orderLine);
326 const failed = orders
327 .filter(({ ok }) => !ok)
328 .map((order) => `${orderLine(order)} (CDW returned ${order.status})`);
329 return [
330 summary,
331 `Ordered ${placed.length} from CDW:`,
332 ...placed,
333 ...(failed.length > 0 ? ["Not ordered, try again:", ...failed] : []),
334 ].join("\n");
335}
244 // **List the Macs in Iru**
245 // Iru has no purchase date, so a Mac's age counts from its first enrollment.
246 const devices: unknown[] = [];
247 let done = false;
248 for (let page = 0; page < MAX_PAGES && !done; page++) {
249 const response = await http.get(
250 "https://acme.api.kandji.io/api/v1/devices",
251 {
252 query: {
253 platform: "Mac",
254 limit: String(PAGE_SIZE),
255 offset: String(page * PAGE_SIZE),
256 },
257 auth: { type: "bearer", token: env.IRU_API_TOKEN },
258 },
259 );
260 if (response.status_code !== 200) {
261 fail(
262 `Iru returned ${response.status_code} listing devices. Check the ` +
263 "API URL and that IRU_API_TOKEN can list devices.",
264 );
265 }
266 const batch = Array.isArray(response.body) ? response.body : [];
267 devices.push(...batch);
268 done = batch.length < PAGE_SIZE;
269 }
270 const macs = oldestMacs(devices);
272 // **Look up each person**
273 // Title and department pick the model; the address is where CDW ships.
274 const asked = params.emails.map((email) => email.toLowerCase());
275 const candidates =
276 asked.length > 0 ? asked : dueEmails(macs, params.min_age_years);
277 const checks: Array<Refresh | string> = [];
278 for (const email of candidates.slice(0, MAX_BATCH)) {
279 const profile = await risotto.get_user_profile({ email });
280 const mac = macs.get(email) ?? null;
281 checks.push(checkRefresh(email, profile, mac, params.min_age_years));
282 }
283 const due = checks.filter(isRefresh);
284 const skipped = checks.filter(
285 (check): check is string => typeof check === "string",
286 );
288 // **Summarize the batch**
289 const total = due.reduce((sum, { spec }) => sum + spec.price, 0);
290 const cutOff =
291 candidates.length > MAX_BATCH
292 ? ` Showing the oldest ${MAX_BATCH} of ${candidates.length}.`
293 : "";
294 const summary = [
295 `${due.length} due for a refresh, ${usd(total)} in all.${cutOff}`,
296 ...due.map(refreshLine),
297 ...(skipped.length > 0 ? ["Left out:", ...skipped] : []),
298 ].join("\n");
299 if (due.length === 0 || !params.place_orders) {
300 return summary;
301 }
303 // **Order each replacement from CDW**
304 // One person's order failing doesn't stop the others.
305 const today = new Date().toISOString().slice(0, 10);
306 const orders: Array<{ refresh: Refresh; status: number; ok: boolean }> = [];
307 for (const refresh of due) {
308 const response = await http.post(
309 "https://apiconnect.cdw.com/v1/customers/orders",
310 {
311 auth: {
312 type: "api_key_header",
313 header: "Ocp-Apim-Subscription-Key",
314 value: env.CDW_SUBSCRIPTION_KEY,
315 },
316 json: orderFor(refresh, today),
317 },
318 );
319 orders.push({
320 refresh,
321 status: response.status_code,
322 ok: accepted(response),
323 });
324 }
325 const placed = orders.filter(({ ok }) => ok).map(orderLine);
326 const failed = orders
327 .filter(({ ok }) => !ok)
328 .map((order) => `${orderLine(order)} (CDW returned ${order.status})`);
329 return [
330 summary,
331 `Ordered ${placed.length} from CDW:`,
332 ...placed,
333 ...(failed.length > 0 ? ["Not ordered, try again:", ...failed] : []),
334 ].join("\n");
Config you will fill in
These become encrypted config fields on the new tool:IRU_API_TOKENCDW_SUBSCRIPTION_KEY