@brunosouzas/stackledger 0.0.0-stage → 0.4.1

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.
Files changed (307) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +260 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +97 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/control.d.ts +2 -0
  7. package/dist/control.js +22 -0
  8. package/dist/control.js.map +1 -0
  9. package/dist/discover-command.d.ts +7 -0
  10. package/dist/discover-command.js +60 -0
  11. package/dist/discover-command.js.map +1 -0
  12. package/dist/discovery/annotations.d.ts +24 -0
  13. package/dist/discovery/annotations.js +37 -0
  14. package/dist/discovery/annotations.js.map +1 -0
  15. package/dist/discovery/host.d.ts +47 -0
  16. package/dist/discovery/host.js +56 -0
  17. package/dist/discovery/host.js.map +1 -0
  18. package/dist/discovery/index.d.ts +15 -0
  19. package/dist/discovery/index.js +30 -0
  20. package/dist/discovery/index.js.map +1 -0
  21. package/dist/discovery/machine.d.ts +14 -0
  22. package/dist/discovery/machine.js +17 -0
  23. package/dist/discovery/machine.js.map +1 -0
  24. package/dist/discovery/run.d.ts +39 -0
  25. package/dist/discovery/run.js +130 -0
  26. package/dist/discovery/run.js.map +1 -0
  27. package/dist/discovery/snapshot.d.ts +60 -0
  28. package/dist/discovery/snapshot.js +161 -0
  29. package/dist/discovery/snapshot.js.map +1 -0
  30. package/dist/discovery/sources/apps.d.ts +3 -0
  31. package/dist/discovery/sources/apps.js +136 -0
  32. package/dist/discovery/sources/apps.js.map +1 -0
  33. package/dist/discovery/sources/brew.d.ts +15 -0
  34. package/dist/discovery/sources/brew.js +69 -0
  35. package/dist/discovery/sources/brew.js.map +1 -0
  36. package/dist/discovery/sources/common.d.ts +39 -0
  37. package/dist/discovery/sources/common.js +70 -0
  38. package/dist/discovery/sources/common.js.map +1 -0
  39. package/dist/discovery/sources/index.d.ts +8 -0
  40. package/dist/discovery/sources/index.js +12 -0
  41. package/dist/discovery/sources/index.js.map +1 -0
  42. package/dist/discovery/sources/launchd.d.ts +3 -0
  43. package/dist/discovery/sources/launchd.js +65 -0
  44. package/dist/discovery/sources/launchd.js.map +1 -0
  45. package/dist/discovery/sources/mas.d.ts +9 -0
  46. package/dist/discovery/sources/mas.js +25 -0
  47. package/dist/discovery/sources/mas.js.map +1 -0
  48. package/dist/discovery/sources/mise.d.ts +5 -0
  49. package/dist/discovery/sources/mise.js +64 -0
  50. package/dist/discovery/sources/mise.js.map +1 -0
  51. package/dist/discovery/sources/npm.d.ts +12 -0
  52. package/dist/discovery/sources/npm.js +34 -0
  53. package/dist/discovery/sources/npm.js.map +1 -0
  54. package/dist/discovery/sources/pipx.d.ts +4 -0
  55. package/dist/discovery/sources/pipx.js +82 -0
  56. package/dist/discovery/sources/pipx.js.map +1 -0
  57. package/dist/discovery/types.d.ts +73 -0
  58. package/dist/discovery/types.js +10 -0
  59. package/dist/discovery/types.js.map +1 -0
  60. package/dist/discovery/write.d.ts +50 -0
  61. package/dist/discovery/write.js +196 -0
  62. package/dist/discovery/write.js.map +1 -0
  63. package/dist/drift-command.d.ts +62 -0
  64. package/dist/drift-command.js +375 -0
  65. package/dist/drift-command.js.map +1 -0
  66. package/dist/drift-formats.d.ts +3 -0
  67. package/dist/drift-formats.js +54 -0
  68. package/dist/drift-formats.js.map +1 -0
  69. package/dist/drift.d.ts +95 -0
  70. package/dist/drift.js +206 -0
  71. package/dist/drift.js.map +1 -0
  72. package/dist/errors.d.ts +15 -0
  73. package/dist/errors.js +26 -0
  74. package/dist/errors.js.map +1 -0
  75. package/dist/graph.d.ts +103 -0
  76. package/dist/graph.js +181 -0
  77. package/dist/graph.js.map +1 -0
  78. package/dist/ics.d.ts +18 -0
  79. package/dist/ics.js +103 -0
  80. package/dist/ics.js.map +1 -0
  81. package/dist/identity.d.ts +18 -0
  82. package/dist/identity.js +36 -0
  83. package/dist/identity.js.map +1 -0
  84. package/dist/index.d.ts +14 -0
  85. package/dist/index.js +9 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/map/badges.d.ts +20 -0
  88. package/dist/map/badges.js +95 -0
  89. package/dist/map/badges.js.map +1 -0
  90. package/dist/map/command.d.ts +8 -0
  91. package/dist/map/command.js +86 -0
  92. package/dist/map/command.js.map +1 -0
  93. package/dist/map/heap.d.ts +15 -0
  94. package/dist/map/heap.js +57 -0
  95. package/dist/map/heap.js.map +1 -0
  96. package/dist/map/ink.d.ts +11 -0
  97. package/dist/map/ink.js +10 -0
  98. package/dist/map/ink.js.map +1 -0
  99. package/dist/map/labels.d.ts +43 -0
  100. package/dist/map/labels.js +172 -0
  101. package/dist/map/labels.js.map +1 -0
  102. package/dist/map/layout.d.ts +59 -0
  103. package/dist/map/layout.js +197 -0
  104. package/dist/map/layout.js.map +1 -0
  105. package/dist/map/model.d.ts +46 -0
  106. package/dist/map/model.js +84 -0
  107. package/dist/map/model.js.map +1 -0
  108. package/dist/map/neighbourhood.d.ts +18 -0
  109. package/dist/map/neighbourhood.js +138 -0
  110. package/dist/map/neighbourhood.js.map +1 -0
  111. package/dist/map/parallel.d.ts +21 -0
  112. package/dist/map/parallel.js +174 -0
  113. package/dist/map/parallel.js.map +1 -0
  114. package/dist/map/relations.d.ts +39 -0
  115. package/dist/map/relations.js +127 -0
  116. package/dist/map/relations.js.map +1 -0
  117. package/dist/map/route.d.ts +25 -0
  118. package/dist/map/route.js +165 -0
  119. package/dist/map/route.js.map +1 -0
  120. package/dist/map/strip.d.ts +29 -0
  121. package/dist/map/strip.js +122 -0
  122. package/dist/map/strip.js.map +1 -0
  123. package/dist/map/suggest.d.ts +21 -0
  124. package/dist/map/suggest.js +97 -0
  125. package/dist/map/suggest.js.map +1 -0
  126. package/dist/map/svg.d.ts +22 -0
  127. package/dist/map/svg.js +232 -0
  128. package/dist/map/svg.js.map +1 -0
  129. package/dist/map/themes.d.ts +61 -0
  130. package/dist/map/themes.js +78 -0
  131. package/dist/map/themes.js.map +1 -0
  132. package/dist/map/xml.d.ts +8 -0
  133. package/dist/map/xml.js +68 -0
  134. package/dist/map/xml.js.map +1 -0
  135. package/dist/map/zones.d.ts +19 -0
  136. package/dist/map/zones.js +46 -0
  137. package/dist/map/zones.js.map +1 -0
  138. package/dist/mcp.d.ts +2 -0
  139. package/dist/mcp.js +145 -0
  140. package/dist/mcp.js.map +1 -0
  141. package/dist/money.d.ts +32 -0
  142. package/dist/money.js +91 -0
  143. package/dist/money.js.map +1 -0
  144. package/dist/report-command.d.ts +3 -0
  145. package/dist/report-command.js +85 -0
  146. package/dist/report-command.js.map +1 -0
  147. package/dist/report-formats.d.ts +11 -0
  148. package/dist/report-formats.js +157 -0
  149. package/dist/report-formats.js.map +1 -0
  150. package/dist/reports.d.ts +105 -0
  151. package/dist/reports.js +247 -0
  152. package/dist/reports.js.map +1 -0
  153. package/dist/scaffold.d.ts +30 -0
  154. package/dist/scaffold.js +140 -0
  155. package/dist/scaffold.js.map +1 -0
  156. package/dist/schema.d.ts +330 -0
  157. package/dist/schema.js +116 -0
  158. package/dist/schema.js.map +1 -0
  159. package/dist/secrets.d.ts +7 -0
  160. package/dist/secrets.js +68 -0
  161. package/dist/secrets.js.map +1 -0
  162. package/dist/site/build.d.ts +22 -0
  163. package/dist/site/build.js +196 -0
  164. package/dist/site/build.js.map +1 -0
  165. package/dist/site/command.d.ts +2 -0
  166. package/dist/site/command.js +221 -0
  167. package/dist/site/command.js.map +1 -0
  168. package/dist/site/data.d.ts +205 -0
  169. package/dist/site/data.js +241 -0
  170. package/dist/site/data.js.map +1 -0
  171. package/dist/site/fs-ops.d.ts +35 -0
  172. package/dist/site/fs-ops.js +26 -0
  173. package/dist/site/fs-ops.js.map +1 -0
  174. package/dist/site/owners.d.ts +5 -0
  175. package/dist/site/owners.js +50 -0
  176. package/dist/site/owners.js.map +1 -0
  177. package/dist/site/paths.d.ts +34 -0
  178. package/dist/site/paths.js +48 -0
  179. package/dist/site/paths.js.map +1 -0
  180. package/dist/site/policy.d.ts +17 -0
  181. package/dist/site/policy.js +26 -0
  182. package/dist/site/policy.js.map +1 -0
  183. package/dist/site/publish.d.ts +14 -0
  184. package/dist/site/publish.js +90 -0
  185. package/dist/site/publish.js.map +1 -0
  186. package/dist/site/relative.d.ts +14 -0
  187. package/dist/site/relative.js +265 -0
  188. package/dist/site/relative.js.map +1 -0
  189. package/dist/site/skills-build.d.ts +22 -0
  190. package/dist/site/skills-build.js +126 -0
  191. package/dist/site/skills-build.js.map +1 -0
  192. package/dist/site/skills-data.d.ts +89 -0
  193. package/dist/site/skills-data.js +94 -0
  194. package/dist/site/skills-data.js.map +1 -0
  195. package/dist/site/staging.d.ts +19 -0
  196. package/dist/site/staging.js +76 -0
  197. package/dist/site/staging.js.map +1 -0
  198. package/dist/skills/command.d.ts +8 -0
  199. package/dist/skills/command.js +64 -0
  200. package/dist/skills/command.js.map +1 -0
  201. package/dist/skills/frontmatter.d.ts +37 -0
  202. package/dist/skills/frontmatter.js +219 -0
  203. package/dist/skills/frontmatter.js.map +1 -0
  204. package/dist/skills/graph.d.ts +39 -0
  205. package/dist/skills/graph.js +100 -0
  206. package/dist/skills/graph.js.map +1 -0
  207. package/dist/skills/ignore.d.ts +34 -0
  208. package/dist/skills/ignore.js +138 -0
  209. package/dist/skills/ignore.js.map +1 -0
  210. package/dist/skills/lines.d.ts +53 -0
  211. package/dist/skills/lines.js +221 -0
  212. package/dist/skills/lines.js.map +1 -0
  213. package/dist/skills/map-command.d.ts +28 -0
  214. package/dist/skills/map-command.js +533 -0
  215. package/dist/skills/map-command.js.map +1 -0
  216. package/dist/skills/mermaid.d.ts +29 -0
  217. package/dist/skills/mermaid.js +261 -0
  218. package/dist/skills/mermaid.js.map +1 -0
  219. package/dist/skills/metro.d.ts +8 -0
  220. package/dist/skills/metro.js +93 -0
  221. package/dist/skills/metro.js.map +1 -0
  222. package/dist/skills/read.d.ts +17 -0
  223. package/dist/skills/read.js +54 -0
  224. package/dist/skills/read.js.map +1 -0
  225. package/dist/skills/rules.d.ts +28 -0
  226. package/dist/skills/rules.js +57 -0
  227. package/dist/skills/rules.js.map +1 -0
  228. package/dist/skills/source.d.ts +66 -0
  229. package/dist/skills/source.js +281 -0
  230. package/dist/skills/source.js.map +1 -0
  231. package/dist/skills/walk.d.ts +64 -0
  232. package/dist/skills/walk.js +281 -0
  233. package/dist/skills/walk.js.map +1 -0
  234. package/dist/source.d.ts +40 -0
  235. package/dist/source.js +199 -0
  236. package/dist/source.js.map +1 -0
  237. package/dist/stdout.d.ts +2 -0
  238. package/dist/stdout.js +24 -0
  239. package/dist/stdout.js.map +1 -0
  240. package/dist/validate.d.ts +45 -0
  241. package/dist/validate.js +321 -0
  242. package/dist/validate.js.map +1 -0
  243. package/dist/views.d.ts +25 -0
  244. package/dist/views.js +58 -0
  245. package/dist/views.js.map +1 -0
  246. package/examples/catalogue-repository/.github/workflows/stackledger.yml +122 -0
  247. package/examples/catalogue-repository/README.md +96 -0
  248. package/examples/catalogue-repository/catalog/catalog-info.yaml +12 -0
  249. package/examples/hosting/Caddyfile +69 -0
  250. package/examples/northwind/catalog-info.yaml +680 -0
  251. package/examples/northwind/stackledger.yaml +16 -0
  252. package/examples/northwind-machine/snapshot.json +309 -0
  253. package/examples/northwind-skills/agents/builder.md +10 -0
  254. package/examples/northwind-skills/agents/reviewer.md +10 -0
  255. package/examples/northwind-skills/designer/SKILL.md +8 -0
  256. package/examples/northwind-skills/editor/SKILL.md +8 -0
  257. package/examples/northwind-skills/engineering/SKILL.md +12 -0
  258. package/examples/northwind-skills/linter/SKILL.md +8 -0
  259. package/examples/northwind-skills/linter/rules.md +5 -0
  260. package/examples/northwind-skills/publishing/SKILL.md +12 -0
  261. package/examples/northwind-skills/publishing/rules.md +5 -0
  262. package/examples/northwind-skills/spec-writer/SKILL.md +8 -0
  263. package/examples/northwind-skills/stackledger-skills.yaml +51 -0
  264. package/examples/northwind-skills/tester/SKILL.md +10 -0
  265. package/examples/northwind-skills/writer/SKILL.md +8 -0
  266. package/examples/northwind-skills/writer/rules.md +6 -0
  267. package/npm-shrinkwrap.json +4995 -0
  268. package/package.json +51 -4
  269. package/site/LICENSE-astroplate +21 -0
  270. package/site/README.md +18 -0
  271. package/site/package.json +6 -0
  272. package/site/public/favicon.svg +1 -0
  273. package/site/src/components/Footer.astro +25 -0
  274. package/site/src/components/Header.astro +35 -0
  275. package/site/src/components/Impact.astro +55 -0
  276. package/site/src/components/LinkOrText.astro +12 -0
  277. package/site/src/components/SkillItem.astro +141 -0
  278. package/site/src/components/SubNav.astro +40 -0
  279. package/site/src/components/ThemeSwitch.astro +16 -0
  280. package/site/src/components/Themed.astro +14 -0
  281. package/site/src/layouts/Base.astro +52 -0
  282. package/site/src/lib/site.ts +25 -0
  283. package/site/src/pages/[reports].astro +222 -0
  284. package/site/src/pages/agents/[file].astro +14 -0
  285. package/site/src/pages/index.astro +71 -0
  286. package/site/src/pages/journeys/[name].astro +50 -0
  287. package/site/src/pages/journeys/index.astro +37 -0
  288. package/site/src/pages/licences/[name].astro +56 -0
  289. package/site/src/pages/map/index.astro +78 -0
  290. package/site/src/pages/playbooks/[file].astro +14 -0
  291. package/site/src/pages/rules/[...rules].astro +61 -0
  292. package/site/src/pages/skill-map/[...map].astro +101 -0
  293. package/site/src/pages/skills/[...list].astro +75 -0
  294. package/site/src/pages/skills/[file].astro +14 -0
  295. package/site/src/pages/software/[name].astro +155 -0
  296. package/site/src/pages/software/index.astro +71 -0
  297. package/site/src/scripts/diagram.ts +8 -0
  298. package/site/src/scripts/links.ts +31 -0
  299. package/site/src/scripts/map.ts +133 -0
  300. package/site/src/scripts/software.ts +32 -0
  301. package/site/src/scripts/theme.ts +52 -0
  302. package/site/src/styles/base.css +470 -0
  303. package/site/src/styles/fonts.css +60 -0
  304. package/site/src/styles/override.css +1 -0
  305. package/site/src/styles/pages.css +299 -0
  306. package/site/src/styles/tokens.css +71 -0
  307. package/skills/stackledger/SKILL.md +155 -0
@@ -0,0 +1,85 @@
1
+ /** `stackledger report <folder> [--date YYYY-MM-DD] [--days N] [--format text|json|csv|ics]`
2
+ * (report-command spec). Called by src/cli.ts; run node dist/cli.js report examples/northwind.
3
+ *
4
+ * Like `stackledger map`: usage and folder errors throw a plain Error before anything is written
5
+ * (exit 2 with usage, from src/cli.ts); a catalogue with errors is still reported from what the
6
+ * `full` view serves, with the counts line of src/map/command.ts on stderr. The whole report is
7
+ * built in memory first, so a failure while computing or serialising it (such as an amount no JSON
8
+ * number holds) leaves stdout empty and exits 1 with one line. A failure while writing stdout (the
9
+ * reader closed the pipe) also exits 1 with one line; bytes already written may remain.
10
+ *
11
+ * Only reads the catalogue folder; no network, no other file.
12
+ */
13
+ import { resolve } from 'node:path';
14
+ import { parseArgs } from 'node:util';
15
+ import { InternalError, internal } from './errors.js';
16
+ import { writeStdout } from './stdout.js';
17
+ import { buildGraph, isDate, localDate } from './graph.js';
18
+ import { calendarNamespace, renderCalendar } from './ics.js';
19
+ import { problemCounts } from './map/command.js';
20
+ import { AmountTooLarge, formatCsv, formatJson, formatText } from './report-formats.js';
21
+ import { buildReport, LAST_WINDOW_DATE, MAX_DAYS, windowFits } from './reports.js';
22
+ import { siteTitle } from './site/data.js';
23
+ import { loadFolder } from './source.js';
24
+ import { validateLoaded } from './validate.js';
25
+ import { applyView, resolveHidden } from './views.js';
26
+ export const REPORT_FORMATS = ['text', 'json', 'csv', 'ics'];
27
+ export const DEFAULT_DAYS = 90;
28
+ const WHOLE_NUMBER = /^\d+$/;
29
+ /** Parse the command's arguments; throws a usage error for anything the spec refuses. */
30
+ function parseReportArgs(args) {
31
+ const { values, positionals } = parseArgs({
32
+ args,
33
+ strict: true,
34
+ allowPositionals: true,
35
+ options: { date: { type: 'string' }, days: { type: 'string' }, format: { type: 'string' } },
36
+ });
37
+ const [, folder, ...extra] = positionals;
38
+ if (!folder)
39
+ throw new Error('A catalogue folder is required');
40
+ if (extra.length)
41
+ throw new Error('Only one folder is accepted');
42
+ const date = values.date ?? localDate();
43
+ if (!isDate(date))
44
+ throw new Error('Report date must be a real YYYY-MM-DD date');
45
+ const daysText = values.days ?? String(DEFAULT_DAYS);
46
+ const days = WHOLE_NUMBER.test(daysText) ? Number(daysText) : Number.NaN;
47
+ if (!(days >= 0 && days <= MAX_DAYS))
48
+ throw new Error(`--days must be a whole number from 0 to ${MAX_DAYS}`);
49
+ if (!windowFits(date, days))
50
+ throw new Error(`--date plus --days must be no later than ${LAST_WINDOW_DATE}`);
51
+ const format = values.format ?? 'text';
52
+ if (!REPORT_FORMATS.includes(format))
53
+ throw new Error(`Unknown format; allowed formats: ${REPORT_FORMATS.join(', ')}`);
54
+ return { folder, date, days, format: format };
55
+ }
56
+ function render(report, format, catalogue) {
57
+ if (format === 'json')
58
+ return formatJson(report);
59
+ if (format === 'csv')
60
+ return formatCsv(report);
61
+ if (format === 'ics')
62
+ return renderCalendar(report, { title: siteTitle(catalogue), namespace: calendarNamespace(catalogue) });
63
+ return formatText(report);
64
+ }
65
+ export async function reportCommand(args) {
66
+ const options = parseReportArgs(args);
67
+ const loaded = await loadFolder(resolve(options.folder));
68
+ const catalogue = validateLoaded(loaded);
69
+ const counts = problemCounts('report', catalogue);
70
+ if (counts.length)
71
+ process.stderr.write(counts.join('\n') + '\n');
72
+ // Arguments and the folder are checked above: a failure from here on is exit 1, never usage.
73
+ let output;
74
+ try {
75
+ const graph = buildGraph(applyView(catalogue.served, 'full', resolveHidden(catalogue)));
76
+ output = render(buildReport(graph, options.date, options.days), options.format, catalogue);
77
+ }
78
+ catch (error) {
79
+ if (error instanceof AmountTooLarge)
80
+ throw new InternalError(`stackledger report: ${error.message}`);
81
+ throw internal('report', error);
82
+ }
83
+ await writeStdout(output, 'stackledger report: cannot write the report to stdout');
84
+ }
85
+ //# sourceMappingURL=report-command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report-command.js","sourceRoot":"","sources":["../src/report-command.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAA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AE,CAAC;QACf,IAAI,KAAK,YAAY,cAAc;YAAE,MAAM,IAAI,aAAa,CAAC,uBAAuB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACrG,MAAM,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IACD,MAAM,WAAW,CAAC,MAAM,EAAE,uDAAuD,CAAC,CAAC;AACrF,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { Report } from './reports.js';
2
+ /** An amount of the report that cannot be written faithfully as a JSON number. */
3
+ export declare class AmountTooLarge extends Error {
4
+ name: string;
5
+ }
6
+ export declare function formatText(report: Report): string;
7
+ export declare function formatJson(report: Report): string;
8
+ export declare const CSV_HEADER: string[];
9
+ /** One CSV field: quoted, quotes doubled, formula starts neutralised with a leading `'`. */
10
+ export declare function csvField(value: string): string;
11
+ export declare function formatCsv(report: Report): string;
@@ -0,0 +1,157 @@
1
+ /** Text, JSON and CSV forms of a licence report (report-command spec, Formats, CSV rows, Safe CSV).
2
+ * Used by src/report-command.ts; the calendar form is src/ics.ts.
3
+ *
4
+ * - formatText(report): plain tables for a terminal. Catalogue text has its control characters
5
+ * replaced by spaces, so a title cannot move the cursor or inject terminal escapes.
6
+ * - formatJson(report): the shape documented in docs/reports.md. Amounts are numbers rounded to two
7
+ * decimals, null where no amount exists. An amount that no JSON number holds exactly throws
8
+ * AmountTooLarge, naming the licence (or the total) it belongs to. U+007F–U+009F are written as `\u`
9
+ * escapes (src/control.ts), so no raw control character reaches a terminal.
10
+ * - formatCsv(report): one quoted row per active, to-confirm or to-buy licence, in reference order.
11
+ * A field that a spreadsheet would read as a formula gets a leading `'`. This protects the file
12
+ * as written; a spreadsheet that saves it again may undo it.
13
+ */
14
+ import { escapeJsonControls } from './control.js';
15
+ import { formatAmount, jsonNumber } from './money.js';
16
+ /** An amount of the report that cannot be written faithfully as a JSON number. */
17
+ export class AmountTooLarge extends Error {
18
+ name = 'AmountTooLarge';
19
+ }
20
+ // Text
21
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
22
+ const NONE = '-';
23
+ /** Catalogue text safe for a terminal: one line, no control characters. */
24
+ function plain(value) {
25
+ return value.replace(CONTROL, ' ');
26
+ }
27
+ const shown = (amount) => (amount === null ? NONE : formatAmount(amount));
28
+ const currencyLabel = (currency) => currency ?? 'unknown';
29
+ /** Columns padded to their widest cell; columns listed in `right` are aligned right (amounts). */
30
+ function table(header, rows, right = new Set()) {
31
+ const widths = header.map((title, column) => Math.max(title.length, ...rows.map(row => row[column].length)));
32
+ const line = (cells) => cells
33
+ .map((cell, column) => (right.has(column) ? cell.padStart(widths[column]) : cell.padEnd(widths[column])))
34
+ .join(' ')
35
+ .trimEnd();
36
+ return [header, ...rows].map(line);
37
+ }
38
+ const AMOUNTS_FROM = (first, count) => new Set(Array.from({ length: count }, (_, i) => first + i));
39
+ function section(title, rows, header, right) {
40
+ return ['', title, ...(rows.length ? table(header, rows, right) : ['None.'])];
41
+ }
42
+ function renewalRows(entries) {
43
+ return entries.map(entry => [
44
+ entry.renewsOn, entry.ref, plain(entry.title), plain(entry.vendor), entry.cycle,
45
+ entry.cost === null ? 'unknown' : formatAmount(entry.cost), currencyLabel(entry.currency),
46
+ ]);
47
+ }
48
+ function totalRows(rows) {
49
+ return rows.map(row => [currencyLabel(row.currency), shown(row.monthly), shown(row.yearly), String(row.incomplete)]);
50
+ }
51
+ function oneOffRows(rows) {
52
+ return rows.map(row => [currencyLabel(row.currency), shown(row.total), String(row.incomplete)]);
53
+ }
54
+ function groupRows(groups) {
55
+ return groups.flatMap(group => group.totals.map(row => [plain(group.label), ...totalRows([row])[0]]));
56
+ }
57
+ const RENEWAL_HEADER = ['Date', 'Licence', 'Title', 'Vendor', 'Cycle', 'Cost', 'Currency'];
58
+ const TOTAL_HEADER = ['Currency', 'Per month', 'Per year', 'Incomplete'];
59
+ const ONE_OFF_HEADER = ['Currency', 'Total', 'Incomplete'];
60
+ export function formatText(report) {
61
+ const lines = [`Licence report for ${report.date}: renewals up to ${report.to} (${report.days} days)`];
62
+ if (report.licences === 0)
63
+ return [...lines, '', 'There are no licences.'].join('\n') + '\n';
64
+ const link = (entry) => [entry.ref, plain(entry.title)];
65
+ lines.push(...section('Renewals', renewalRows(report.renewals), RENEWAL_HEADER, new Set([5])), ...section('Overdue', renewalRows(report.overdue), RENEWAL_HEADER, new Set([5])), ...section('Unknown renewal dates', report.unknownDates.map(link), ['Licence', 'Title']), ...section('Recurring cost', totalRows(report.recurring), TOTAL_HEADER, AMOUNTS_FROM(1, 3)), ...section('By owner', groupRows(report.groups.owner), ['Owner', ...TOTAL_HEADER], AMOUNTS_FROM(2, 3)), ...section('By payer', groupRows(report.groups.payer), ['Payer', ...TOTAL_HEADER], AMOUNTS_FROM(2, 3)), ...section('By zone', groupRows(report.groups.zone), ['Zone', ...TOTAL_HEADER], AMOUNTS_FROM(2, 3)), ...section('One-off', report.oneOff.items.map(item => [...link(item), formatAmount(item.cost), item.currency, item.renewsOn ?? NONE]), ['Licence', 'Title', 'Cost', 'Currency', 'Renews on'], new Set([2])), ...section('One-off totals', oneOffRows(report.oneOff.totals), ONE_OFF_HEADER, AMOUNTS_FROM(1, 2)), ...section('Planned purchases', report.planned.items.map(item => [
66
+ ...link(item), item.cycle, shown(item.cost), currencyLabel(item.currency), shown(item.monthly), shown(item.yearly),
67
+ ]), ['Licence', 'Title', 'Cycle', 'Cost', 'Currency', 'Per month', 'Per year'], new Set([3, 5, 6])), ...section('Planned recurring totals', totalRows(report.planned.recurring), TOTAL_HEADER, AMOUNTS_FROM(1, 3)), ...section('Planned one-off totals', oneOffRows(report.planned.oneOff), ONE_OFF_HEADER, AMOUNTS_FROM(1, 2)), ...section('Incomplete licences', report.incomplete.map(item => [...link(item), item.status, item.unknown.join(', ')]), ['Licence', 'Title', 'Status', 'Unknown']));
68
+ return lines.join('\n') + '\n';
69
+ }
70
+ // JSON
71
+ /** Converts amounts to JSON numbers, naming the owner of an amount that does not fit. */
72
+ function numbers(owner) {
73
+ return (amount) => {
74
+ if (amount === null)
75
+ return null;
76
+ const value = jsonNumber(amount);
77
+ if (value === undefined)
78
+ throw new AmountTooLarge(plain(`An amount of ${owner} cannot be written exactly as a JSON number`));
79
+ return value;
80
+ };
81
+ }
82
+ function totalJson(rows, owner) {
83
+ return rows.map(row => {
84
+ const number = numbers(`the ${currencyLabel(row.currency)} total of ${owner}`);
85
+ return { currency: row.currency, monthly: number(row.monthly), yearly: number(row.yearly), incomplete: row.incomplete };
86
+ });
87
+ }
88
+ function oneOffJson(rows, owner) {
89
+ return rows.map(row => ({ currency: row.currency, total: numbers(`the ${currencyLabel(row.currency)} total of ${owner}`)(row.total), incomplete: row.incomplete }));
90
+ }
91
+ function renewalJson(entry) {
92
+ return {
93
+ ref: entry.ref, title: entry.title, vendor: entry.vendor, status: entry.status, cycle: entry.cycle,
94
+ renewsOn: entry.renewsOn, cost: numbers(entry.ref)(entry.cost), currency: entry.currency,
95
+ };
96
+ }
97
+ function groupJson(groups, grouping) {
98
+ return groups.map(group => ({ key: group.key, label: group.label, synthetic: group.synthetic, totals: totalJson(group.totals, `${grouping} group ${group.label}`) }));
99
+ }
100
+ /** Every licence's own amounts first, so a licence with an absurd cost is the one named. */
101
+ function checkLicences(report) {
102
+ for (const row of report.rows) {
103
+ const number = numbers(row.ref);
104
+ number(row.cost === 'unknown' ? null : row.cost);
105
+ number(row.monthly);
106
+ number(row.yearly);
107
+ }
108
+ }
109
+ export function formatJson(report) {
110
+ checkLicences(report);
111
+ const value = {
112
+ date: report.date, days: report.days, to: report.to,
113
+ renewals: report.renewals.map(renewalJson),
114
+ overdue: report.overdue.map(renewalJson),
115
+ unknownDates: report.unknownDates.map(entry => entry.ref),
116
+ recurring: totalJson(report.recurring, 'the recurring cost'),
117
+ groups: {
118
+ owner: groupJson(report.groups.owner, 'owner'),
119
+ payer: groupJson(report.groups.payer, 'payer'),
120
+ zone: groupJson(report.groups.zone, 'zone'),
121
+ },
122
+ oneOff: {
123
+ items: report.oneOff.items.map(item => ({ ref: item.ref, title: item.title, cost: numbers(item.ref)(item.cost), currency: item.currency, renewsOn: item.renewsOn })),
124
+ totals: oneOffJson(report.oneOff.totals, 'the one-off costs'),
125
+ },
126
+ planned: {
127
+ items: report.planned.items.map(item => {
128
+ const number = numbers(item.ref);
129
+ return { ref: item.ref, title: item.title, cycle: item.cycle, cost: number(item.cost), currency: item.currency, monthly: number(item.monthly), yearly: number(item.yearly) };
130
+ }),
131
+ recurring: totalJson(report.planned.recurring, 'the planned recurring cost'),
132
+ oneOff: oneOffJson(report.planned.oneOff, 'the planned one-off costs'),
133
+ },
134
+ incomplete: report.incomplete.map(item => ({ ref: item.ref, title: item.title, status: item.status, unknown: item.unknown })),
135
+ };
136
+ return escapeJsonControls(JSON.stringify(value, null, 2)) + '\n';
137
+ }
138
+ // CSV
139
+ export const CSV_HEADER = ['ref', 'title', 'vendor', 'status', 'cycle', 'cost', 'currency', 'monthly', 'yearly', 'renewsOn', 'owner', 'paidBy', 'zone', 'counted'];
140
+ /** First characters that make a spreadsheet read a cell as a formula, including full-width forms. */
141
+ const FORMULA_START = /^[=+\-@\t\r\n=+-@]/;
142
+ /** One CSV field: quoted, quotes doubled, formula starts neutralised with a leading `'`. */
143
+ export function csvField(value) {
144
+ const safe = FORMULA_START.test(value) ? `'${value}` : value;
145
+ return `"${safe.replaceAll('"', '""')}"`;
146
+ }
147
+ export function formatCsv(report) {
148
+ const rows = report.rows.map(row => [
149
+ row.ref, row.title, row.vendor, row.status, row.cycle,
150
+ row.cost === 'unknown' ? 'unknown' : formatAmount(row.cost), row.currency,
151
+ row.monthly === null ? '' : formatAmount(row.monthly), row.yearly === null ? '' : formatAmount(row.yearly),
152
+ row.renewsOn, row.owner, row.paidBy ?? '', row.zones.join(';'), String(row.counted),
153
+ ]);
154
+ // RFC 4180 line ends.
155
+ return [CSV_HEADER, ...rows].map(cells => cells.map(csvField).join(',')).join('\r\n') + '\r\n';
156
+ }
157
+ //# sourceMappingURL=report-formats.js.map
@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AG,CAAC,KAAK;QACrD,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,QAAQ;QACzE,GAAG,CAAC,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC;QAC1G,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC;KACpF,CAAC,CAAC;IACH,sBAAsB;IACtB,OAAO,CAAC,UAAU,EAAE,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AACjG,CAAC"}
@@ -0,0 +1,105 @@
1
+ import { type Graph } from './graph.js';
2
+ import { type Amount } from './money.js';
3
+ /** Fields whose `unknown` value makes a licence incomplete, in catalogue order. */
4
+ export type UnknownField = 'cycle' | 'cost' | 'currency';
5
+ export interface LicenceLink {
6
+ ref: string;
7
+ title: string;
8
+ }
9
+ export interface RenewalEntry extends LicenceLink {
10
+ vendor: string;
11
+ status: string;
12
+ cycle: string;
13
+ renewsOn: string;
14
+ cost: Amount | null;
15
+ currency: string | null;
16
+ }
17
+ /** One currency's totals; currency null is the unknown-currency row. An amount is null when no
18
+ * complete licence adds to it. */
19
+ export interface TotalRow {
20
+ currency: string | null;
21
+ monthly: Amount | null;
22
+ yearly: Amount | null;
23
+ incomplete: number;
24
+ }
25
+ export interface OneOffRow {
26
+ currency: string | null;
27
+ total: Amount | null;
28
+ incomplete: number;
29
+ }
30
+ export interface Group {
31
+ key: string;
32
+ label: string;
33
+ synthetic: boolean;
34
+ totals: TotalRow[];
35
+ }
36
+ export interface OneOffItem extends LicenceLink {
37
+ cost: Amount;
38
+ currency: string;
39
+ renewsOn: string | null;
40
+ }
41
+ export interface PlannedItem extends LicenceLink {
42
+ cycle: string;
43
+ cost: Amount | null;
44
+ currency: string | null;
45
+ monthly: Amount | null;
46
+ yearly: Amount | null;
47
+ }
48
+ export interface IncompleteItem extends LicenceLink {
49
+ status: string;
50
+ unknown: UnknownField[];
51
+ }
52
+ /** One CSV row: a licence with status active, to-confirm or to-buy. */
53
+ export interface LicenceRow extends LicenceLink {
54
+ vendor: string;
55
+ status: string;
56
+ cycle: string;
57
+ cost: Amount | 'unknown';
58
+ currency: string;
59
+ renewsOn: string;
60
+ monthly: Amount | null;
61
+ yearly: Amount | null;
62
+ owner: string;
63
+ paidBy: string | undefined;
64
+ zones: string[];
65
+ counted: boolean;
66
+ }
67
+ export interface Report {
68
+ date: string;
69
+ days: number;
70
+ to: string;
71
+ /** Served licences of any status; zero means the catalogue has no licence at all. */
72
+ licences: number;
73
+ renewals: RenewalEntry[];
74
+ overdue: RenewalEntry[];
75
+ unknownDates: LicenceLink[];
76
+ recurring: TotalRow[];
77
+ groups: {
78
+ owner: Group[];
79
+ payer: Group[];
80
+ zone: Group[];
81
+ };
82
+ oneOff: {
83
+ items: OneOffItem[];
84
+ totals: OneOffRow[];
85
+ };
86
+ planned: {
87
+ items: PlannedItem[];
88
+ recurring: TotalRow[];
89
+ oneOff: OneOffRow[];
90
+ };
91
+ incomplete: IncompleteItem[];
92
+ rows: LicenceRow[];
93
+ }
94
+ export interface ReportOptions {
95
+ /** The text an owner group shows and sorts by; the reference itself by default. */
96
+ ownerLabel?: (owner: string) => string;
97
+ }
98
+ export declare const MAX_DAYS = 366;
99
+ /** The last day a window may reach: a calendar event ends the day after its date, and
100
+ * 9999-12-31 has no next day in YYYY-MM-DD. */
101
+ export declare const LAST_WINDOW_DATE = "9999-12-30";
102
+ /** Whether a window of `days` from `date` ends by LAST_WINDOW_DATE (dates compare as text). */
103
+ export declare function windowFits(date: string, days: number): boolean;
104
+ /** The report of a `full`-view graph for a report date and a window of `days` days (0 to 366). */
105
+ export declare function buildReport(graph: Graph, date: string, days: number, options?: ReportOptions): Report;
@@ -0,0 +1,247 @@
1
+ /** The licence report (licence-reports spec, design D1 and D3): renewals, recurring cost per
2
+ * currency and per group, one-off and planned costs, and incomplete licences.
3
+ *
4
+ * Why one pure model: the Reports page, `stackledger report` (text, JSON, CSV) and the calendar
5
+ * file all show the same numbers, so they all read buildReport(graph, date, days). The graph must
6
+ * be built from the `full` view (src/views.ts); the staff site never calls this module.
7
+ *
8
+ * Rules, in short (docs/reports.md has the long form):
9
+ * - `active` and `to-confirm` licences count; `to-buy` ones are planned; `cancelled` and `expired`
10
+ * ones are in no list and no total.
11
+ * - `cost` is the price of one cycle for the whole licence; seats never multiply it. Monthly costs
12
+ * ×12 per year, yearly ÷12 per month, `none` costs zero. Amounts are exact (src/money.ts).
13
+ * - A licence whose cycle, cost or currency is `unknown` adds to no amount; it is listed as
14
+ * incomplete and counted on its currency's total row (or the unknown-currency row).
15
+ * - Groups (owner, payer, zone) hold the recurring totals of counted licences. Synthetic groups
16
+ * (`Not set`, `Several zones`, `No zone`) have keys that can never equal a real value, and come last.
17
+ *
18
+ * Every list is sorted, so the output does not depend on the order of the catalogue's documents.
19
+ */
20
+ import { compareRefs, compareText, isDate } from './identity.js';
21
+ import { renewals as findRenewals } from './graph.js';
22
+ import { add, amountOf, divide, multiply, ZERO } from './money.js';
23
+ export const MAX_DAYS = 366;
24
+ /** The last day a window may reach: a calendar event ends the day after its date, and
25
+ * 9999-12-31 has no next day in YYYY-MM-DD. */
26
+ export const LAST_WINDOW_DATE = '9999-12-30';
27
+ /** Whether a window of `days` from `date` ends by LAST_WINDOW_DATE (dates compare as text). */
28
+ export function windowFits(date, days) {
29
+ if (date > LAST_WINDOW_DATE)
30
+ return false;
31
+ const end = new Date(Date.parse(`${date}T00:00:00.000Z`) + days * 86_400_000).toISOString().slice(0, 10);
32
+ return isDate(end) && end <= LAST_WINDOW_DATE;
33
+ }
34
+ const COUNTED = new Set(['active', 'to-confirm']);
35
+ const PLANNED = 'to-buy';
36
+ const MONTHS = 12n;
37
+ /** Synthetic groups. Their keys may look like real values; Grouping keeps them apart by the flag. */
38
+ const NOT_SET = { key: 'not-set', label: 'Not set', synthetic: true };
39
+ const SEVERAL_ZONES = { key: 'several-zones', label: 'Several zones', synthetic: true };
40
+ const NO_ZONE = { key: 'no-zone', label: 'No zone', synthetic: true };
41
+ function titleOf(item) {
42
+ return item.entity.metadata.title ?? item.name;
43
+ }
44
+ function unknownFields(details) {
45
+ const fields = [];
46
+ if (details.cycle === 'unknown')
47
+ fields.push('cycle');
48
+ if (details.cost === 'unknown')
49
+ fields.push('cost');
50
+ if (details.currency === 'unknown')
51
+ fields.push('currency');
52
+ return fields;
53
+ }
54
+ /** Monthly and yearly amounts of one cycle's cost. */
55
+ function recurringAmounts(cycle, cost) {
56
+ if (cycle === 'monthly')
57
+ return { monthly: cost, yearly: multiply(cost, MONTHS) };
58
+ if (cycle === 'yearly')
59
+ return { monthly: divide(cost, MONTHS), yearly: cost };
60
+ if (cycle === 'none')
61
+ return { monthly: ZERO, yearly: ZERO };
62
+ return undefined;
63
+ }
64
+ function costed(item) {
65
+ const details = item.entity.spec.licence;
66
+ const unknown = unknownFields(details);
67
+ const cost = details.cost === 'unknown' ? null : amountOf(details.cost);
68
+ const complete = unknown.length === 0;
69
+ const amounts = complete ? recurringAmounts(details.cycle, cost) : undefined;
70
+ return {
71
+ item, details, link: { ref: item.ref, title: titleOf(item) }, unknown,
72
+ currency: details.currency === 'unknown' ? null : details.currency, cost,
73
+ monthly: amounts?.monthly ?? null, yearly: amounts?.yearly ?? null,
74
+ oneOff: details.cycle === 'one-off', complete,
75
+ };
76
+ }
77
+ const compareCurrency = (left, right) => left === right ? 0 : left === null ? 1 : right === null ? -1 : compareText(left, right);
78
+ const plus = (total, amount) => (total === null ? amount : add(total, amount));
79
+ /** Recurring total rows, one per currency, built licence by licence. */
80
+ class RecurringTotals {
81
+ rows = new Map();
82
+ add(licence) {
83
+ const row = this.row(licence.currency);
84
+ if (!licence.complete) {
85
+ row.incomplete++;
86
+ return;
87
+ }
88
+ row.monthly = plus(row.monthly, licence.monthly);
89
+ row.yearly = plus(row.yearly, licence.yearly);
90
+ }
91
+ list() {
92
+ return [...this.rows.values()].sort((one, two) => compareCurrency(one.currency, two.currency));
93
+ }
94
+ row(currency) {
95
+ let row = this.rows.get(currency);
96
+ if (!row)
97
+ this.rows.set(currency, (row = { currency, monthly: null, yearly: null, incomplete: 0 }));
98
+ return row;
99
+ }
100
+ }
101
+ /** One-off total rows, one per currency. */
102
+ class OneOffTotals {
103
+ rows = new Map();
104
+ add(licence) {
105
+ let row = this.rows.get(licence.currency);
106
+ if (!row)
107
+ this.rows.set(licence.currency, (row = { currency: licence.currency, total: null, incomplete: 0 }));
108
+ if (licence.complete)
109
+ row.total = plus(row.total, licence.cost);
110
+ else
111
+ row.incomplete++;
112
+ }
113
+ list() {
114
+ return [...this.rows.values()].sort((one, two) => compareCurrency(one.currency, two.currency));
115
+ }
116
+ }
117
+ /** Recurring totals per group of one grouping (owner, payer or zone). */
118
+ class Grouping {
119
+ groups = new Map();
120
+ add(id, licence) {
121
+ // `real:` and `synthetic:` prefixes keep a payer named "Not set" apart from the missing payer.
122
+ const mapKey = `${id.synthetic ? 'synthetic' : 'real'}:${id.key}`;
123
+ let group = this.groups.get(mapKey);
124
+ if (!group)
125
+ this.groups.set(mapKey, (group = { id, totals: new RecurringTotals() }));
126
+ group.totals.add(licence);
127
+ }
128
+ list() {
129
+ return [...this.groups.values()]
130
+ .map(({ id, totals }) => ({ key: id.key, label: id.label, synthetic: id.synthetic, totals: totals.list() }))
131
+ .sort((one, two) => Number(one.synthetic) - Number(two.synthetic) || compareText(one.label, two.label) || compareText(one.key, two.key));
132
+ }
133
+ }
134
+ /** Declared zones of the served layout by lower-cased name; the first declaration wins. */
135
+ function declaredZones(graph) {
136
+ const zones = new Map();
137
+ for (const zone of graph.view.layout?.spec.zones ?? []) {
138
+ const key = zone.name.toLowerCase();
139
+ if (!zones.has(key))
140
+ zones.set(key, { name: key, title: zone.title });
141
+ }
142
+ return zones;
143
+ }
144
+ /** Lower-cased names of the declared zones of the served components that use a licence, sorted. */
145
+ function zonesOf(graph, item, declared) {
146
+ const zones = new Set();
147
+ for (const key of graph.dependants.get(item.key) ?? []) {
148
+ const user = graph.items.get(key);
149
+ if (user?.kind !== 'component')
150
+ continue;
151
+ const label = user.entity.metadata.labels?.['stackledger/zone'];
152
+ // A label that names no declared zone counts as no zone.
153
+ if (typeof label === 'string' && declared.has(label.toLowerCase()))
154
+ zones.add(label.toLowerCase());
155
+ }
156
+ return [...zones].sort(compareText);
157
+ }
158
+ function zoneGroup(zones, declared) {
159
+ if (zones.length === 0)
160
+ return NO_ZONE;
161
+ if (zones.length > 1)
162
+ return SEVERAL_ZONES;
163
+ const zone = declared.get(zones[0]);
164
+ return { key: zone.name, label: zone.title, synthetic: false };
165
+ }
166
+ function renewalEntry(renewal, graph) {
167
+ const item = graph.items.get(renewal.ref.toLowerCase());
168
+ return {
169
+ ref: renewal.ref, title: titleOf(item), vendor: renewal.vendor, status: renewal.status, cycle: renewal.cycle,
170
+ renewsOn: renewal.renewsOn, cost: renewal.cost === 'unknown' ? null : amountOf(renewal.cost),
171
+ currency: renewal.currency === 'unknown' ? null : renewal.currency,
172
+ };
173
+ }
174
+ function plannedItem(licence) {
175
+ return {
176
+ ...licence.link, cycle: licence.details.cycle, cost: licence.cost, currency: licence.currency,
177
+ monthly: licence.monthly, yearly: licence.yearly,
178
+ };
179
+ }
180
+ function licenceRow(licence, zones) {
181
+ const { details } = licence;
182
+ return {
183
+ ...licence.link, vendor: details.vendor, status: details.status, cycle: details.cycle,
184
+ cost: licence.cost ?? 'unknown', currency: details.currency, renewsOn: details.renewsOn,
185
+ monthly: licence.monthly, yearly: licence.yearly, owner: licence.item.entity.spec.owner, paidBy: details.paidBy, zones,
186
+ counted: COUNTED.has(details.status) && licence.complete && !licence.oneOff,
187
+ };
188
+ }
189
+ /** The report of a `full`-view graph for a report date and a window of `days` days (0 to 366). */
190
+ export function buildReport(graph, date, days, options = {}) {
191
+ if (!isDate(date))
192
+ throw new Error('The report date must be a real YYYY-MM-DD date');
193
+ if (!Number.isInteger(days) || days < 0 || days > MAX_DAYS)
194
+ throw new Error(`The window must be from 0 to ${MAX_DAYS} days`);
195
+ if (!windowFits(date, days))
196
+ throw new Error(`The window must end no later than ${LAST_WINDOW_DATE}`);
197
+ const ownerLabel = options.ownerLabel ?? ((owner) => owner);
198
+ const declared = declaredZones(graph);
199
+ const licences = [...graph.items.values()]
200
+ .filter((item) => item.kind === 'licence')
201
+ .sort((one, two) => compareRefs(one.ref, two.ref));
202
+ const recurring = new RecurringTotals(), oneOffTotals = new OneOffTotals();
203
+ const plannedRecurring = new RecurringTotals(), plannedOneOff = new OneOffTotals();
204
+ const byOwner = new Grouping(), byPayer = new Grouping(), byZone = new Grouping();
205
+ const oneOffItems = [], plannedItems = [], incomplete = [], rows = [];
206
+ for (const item of licences) {
207
+ const counted = COUNTED.has(item.entity.spec.licence.status);
208
+ if (!counted && item.entity.spec.licence.status !== PLANNED)
209
+ continue;
210
+ const licence = costed(item);
211
+ const zones = zonesOf(graph, item, declared);
212
+ rows.push(licenceRow(licence, zones));
213
+ if (!licence.complete)
214
+ incomplete.push({ ...licence.link, status: licence.details.status, unknown: licence.unknown });
215
+ if (!counted) {
216
+ plannedItems.push(plannedItem(licence));
217
+ (licence.oneOff ? plannedOneOff : plannedRecurring).add(licence);
218
+ continue;
219
+ }
220
+ if (licence.oneOff) {
221
+ oneOffTotals.add(licence);
222
+ if (licence.complete)
223
+ oneOffItems.push({ ...licence.link, cost: licence.cost, currency: licence.currency, renewsOn: isDate(licence.details.renewsOn) ? licence.details.renewsOn : null });
224
+ continue;
225
+ }
226
+ recurring.add(licence);
227
+ const owner = item.entity.spec.owner;
228
+ byOwner.add({ key: owner, label: ownerLabel(owner), synthetic: false }, licence);
229
+ const payer = licence.details.paidBy;
230
+ byPayer.add(payer === undefined ? NOT_SET : { key: payer, label: payer, synthetic: false }, licence);
231
+ byZone.add(zoneGroup(zones, declared), licence);
232
+ }
233
+ const window = findRenewals(graph, date, days);
234
+ const linkOf = (ref) => ({ ref, title: titleOf(graph.items.get(ref.toLowerCase())) });
235
+ return {
236
+ date, days, to: window.to, licences: licences.length,
237
+ renewals: window.licences.map(renewal => renewalEntry(renewal, graph)),
238
+ overdue: window.overdue.map(renewal => renewalEntry(renewal, graph)),
239
+ unknownDates: window.unknown.map(linkOf),
240
+ recurring: recurring.list(),
241
+ groups: { owner: byOwner.list(), payer: byPayer.list(), zone: byZone.list() },
242
+ oneOff: { items: oneOffItems, totals: oneOffTotals.list() },
243
+ planned: { items: plannedItems, recurring: plannedRecurring.list(), oneOff: plannedOneOff.list() },
244
+ incomplete, rows,
245
+ };
246
+ }
247
+ //# sourceMappingURL=reports.js.map