@opsrev/acculynx-cli 1.1.0 → 1.3.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.
Files changed (3) hide show
  1. package/README.md +66 -1
  2. package/dist/index.js +315 -1
  3. package/package.json +4 -2
package/README.md CHANGED
@@ -30,7 +30,7 @@ API keys are created by your AccuLynx account administrator under Account Settin
30
30
 
31
31
  ### Unofficial Web API
32
32
 
33
- The `unofficial` commands use cookie-based authentication against AccuLynx's internal web APIs. These provide access to features not available in the official API (job documents, dashboard, etc.).
33
+ The `unofficial` commands use cookie-based authentication against AccuLynx's internal web APIs. These provide access to features not available in the official API (job documents, messages, etc.).
34
34
 
35
35
  | Env Var | Flag | Description |
36
36
  |---------|------|-------------|
@@ -79,8 +79,73 @@ acculynx unofficial logout # Remove cached session
79
79
  acculynx unofficial sessions # List cached sessions
80
80
  acculynx unofficial documents list <jobId> # List all document folders/files for a job
81
81
  acculynx unofficial documents download <jobId> <fileId> [--output ./file.pdf] # Download a document
82
+ acculynx unofficial messages list <jobId> # List all messages/comments for a job
83
+ acculynx unofficial messages list <jobId> --type Email # Filter by type: Comment, Email, or Signatures
84
+ acculynx unofficial messages list <jobId> --count-only # Get message count only
85
+ acculynx unofficial messages post <jobId> <message> # Post a comment to a job
86
+ acculynx unofficial messages post <jobId> <message> --notify <userId,...> # Post and notify users
87
+ acculynx unofficial milestones list <jobId> # List workflow milestones/statuses for a job
88
+ acculynx unofficial milestones set <jobId> <status> # Set a job's milestone/status by name
89
+ acculynx unofficial milestones set <jobId> <status> --message "note" # Set with comment
90
+ acculynx unofficial jobs list # List jobs (unofficial)
91
+ acculynx unofficial jobs list --status <name> # Filter by workflow status name
92
+ acculynx unofficial jobs list --milestone <name> # Filter by milestone name
82
93
  ```
83
94
 
95
+ #### Messages
96
+
97
+ List all messages, comments, and emails on a job. HTML email content is automatically converted to lightweight markdown (headers, links, lists preserved; images and styles stripped) for clean AI agent consumption.
98
+
99
+ ```bash
100
+ acculynx unofficial messages list <jobId> # all messages, newest first
101
+ acculynx unofficial messages list <jobId> --sort "createdDate|asc" # oldest first
102
+ acculynx unofficial messages list <jobId> --type Email # only emails
103
+ acculynx unofficial messages list <jobId> --count-only # just the count
104
+ ```
105
+
106
+ Post a comment to a job, optionally notifying (tagging) users:
107
+
108
+ ```bash
109
+ acculynx unofficial messages post <jobId> "Your message here"
110
+ acculynx unofficial messages post <jobId> "Check this out" --notify "userId1,userId2"
111
+ ```
112
+
113
+ User IDs for `--notify` come from the official users API (`/api/v2/users`).
114
+
115
+ #### Milestones
116
+
117
+ AccuLynx workflows have milestones (Lead, Prospect, Approved, etc.) that contain custom statuses (Estimate Sent, Contract Signed, etc.). The official API only filters by top-level milestones. The unofficial milestones commands let you work with the granular workflow statuses.
118
+
119
+ List all milestones and their statuses for a job:
120
+
121
+ ```bash
122
+ acculynx unofficial milestones list <jobId>
123
+ ```
124
+
125
+ Set a job to a specific workflow status by name (case-insensitive):
126
+
127
+ ```bash
128
+ acculynx unofficial milestones set <jobId> "Estimate Sent"
129
+ acculynx unofficial milestones set <jobId> "OpsRev: Estimate Ready for Review"
130
+ acculynx unofficial milestones set <jobId> "Contract Signed" --message "Moving to contract phase"
131
+ ```
132
+
133
+ If the status name doesn't match, the command returns the list of available statuses.
134
+
135
+ #### Jobs (unofficial)
136
+
137
+ The official `jobs list --milestones` filter only accepts top-level milestone names (Lead, Prospect, Approved, etc.). The unofficial `jobs list` command supports filtering by custom workflow status names.
138
+
139
+ ```bash
140
+ acculynx unofficial jobs list --status "Estimate Sent" # jobs in a specific status
141
+ acculynx unofficial jobs list --status "OpsRev: Estimate Ready for Review" # custom status names work
142
+ acculynx unofficial jobs list --milestone Prospect # filter by milestone
143
+ acculynx unofficial jobs list --status "Estimate Sent" --query "Smith" # combine with search
144
+ acculynx unofficial jobs list --sort "lastTouched|desc" --page 2 # sort and paginate
145
+ ```
146
+
147
+ The `--status` flag resolves the status name (case-insensitive) to a GUID via the company workflow configuration, then queries the internal job list API. If the name doesn't match, the command returns the list of available statuses.
148
+
84
149
  **Getting started:** If you don't know your company ID, run `companies` first -- it logs in and returns all companies available to your account:
85
150
 
86
151
  ```bash
package/dist/index.js CHANGED
@@ -260,6 +260,16 @@ var CookieJar = class _CookieJar {
260
260
  }
261
261
  this.cookies.set(domain, jar);
262
262
  }
263
+ /** Get a specific cookie value by name for a given URL. */
264
+ getCookie(url, name) {
265
+ const domain = new URL(url).hostname;
266
+ for (const [d, jar] of this.cookies) {
267
+ if (domain === d || domain.endsWith("." + d)) {
268
+ if (jar.has(name)) return jar.get(name);
269
+ }
270
+ }
271
+ return void 0;
272
+ }
263
273
  /** Build a Cookie header string for a given URL. */
264
274
  headerFor(url) {
265
275
  const domain = new URL(url).hostname;
@@ -373,6 +383,36 @@ function createUnofficialClient(session) {
373
383
  }
374
384
  return resp.json();
375
385
  }
386
+ async function doPost(path, body) {
387
+ const url = `${base}${path}`;
388
+ const headers = {
389
+ Cookie: session.jar.headerFor(url),
390
+ Accept: "application/json",
391
+ "Content-Type": "application/json"
392
+ };
393
+ const xsrf = session.jar.getCookie(url, "XSRF-TOKEN");
394
+ if (xsrf) {
395
+ headers["X-XSRF-TOKEN"] = xsrf;
396
+ }
397
+ const resp = await fetch(url, {
398
+ method: "POST",
399
+ headers,
400
+ body: JSON.stringify(body)
401
+ });
402
+ if (resp.status === 401 || resp.status === 302) {
403
+ throw new Error(
404
+ "Session expired \u2014 run `acculynx unofficial login` to re-authenticate"
405
+ );
406
+ }
407
+ if (!resp.ok) {
408
+ throw new Error(
409
+ `Unofficial API error (${resp.status}): ${await resp.text()}`
410
+ );
411
+ }
412
+ const text = await resp.text();
413
+ if (!text) return {};
414
+ return JSON.parse(text);
415
+ }
376
416
  async function doGetBuffer(url) {
377
417
  const fullUrl = url.startsWith("http") ? url : `${base}${url}`;
378
418
  const resp = await fetch(fullUrl, {
@@ -383,7 +423,7 @@ function createUnofficialClient(session) {
383
423
  }
384
424
  return Buffer.from(await resp.arrayBuffer());
385
425
  }
386
- return { get: doGet, getBuffer: doGetBuffer };
426
+ return { get: doGet, post: doPost, getBuffer: doGetBuffer };
387
427
  }
388
428
 
389
429
  // src/unofficial/session.ts
@@ -605,6 +645,277 @@ function registerDocumentsCommands(parentCmd, getClient2) {
605
645
  });
606
646
  }
607
647
 
648
+ // src/unofficial/commands/messages.ts
649
+ import TurndownService from "turndown";
650
+ function createTurndown() {
651
+ const td = new TurndownService({
652
+ headingStyle: "atx",
653
+ bulletListMarker: "-"
654
+ });
655
+ td.addRule("removeImages", {
656
+ filter: "img",
657
+ replacement: () => ""
658
+ });
659
+ td.addRule("removeStyle", {
660
+ filter: ["style", "script"],
661
+ replacement: () => ""
662
+ });
663
+ return td;
664
+ }
665
+ var looksLikeHtml = /<[a-z][\s\S]*?>/i;
666
+ function cleanMessage(html) {
667
+ if (!looksLikeHtml.test(html)) return html;
668
+ const td = createTurndown();
669
+ return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim();
670
+ }
671
+ function registerMessagesCommands(parentCmd, getClient2) {
672
+ const messages = parentCmd.command("messages").description("Job message/comment operations");
673
+ messages.command("list").argument("<jobId>", "Job ID (GUID)").option(
674
+ "--sort <sort>",
675
+ "Sort field and direction (field|asc or field|desc)",
676
+ "createdDate|desc"
677
+ ).option("--count-only", "Return only the total count of messages").option(
678
+ "--type <type>",
679
+ "Filter by message type: Comment, Email, or Signatures"
680
+ ).description("List all messages and comments for a job").action(async (jobId, opts) => {
681
+ const params = new URLSearchParams({ sort: opts.sort });
682
+ if (opts.countOnly) {
683
+ params.set("countOnly", "true");
684
+ }
685
+ if (opts.type) {
686
+ params.append("filters", `type=${opts.type}`);
687
+ }
688
+ const data = await getClient2().get(
689
+ `/api/jobs/${jobId}/JobMessageFeed?${params.toString()}`
690
+ );
691
+ if (opts.countOnly) {
692
+ console.log(JSON.stringify({ totalRecords: data.TotalRecords }));
693
+ return;
694
+ }
695
+ const result = {
696
+ totalRecords: data.TotalRecords,
697
+ currentPage: data.CurrentPage,
698
+ totalPages: data.TotalPages,
699
+ messages: data.results.map((msg) => ({
700
+ id: msg.id,
701
+ jobId: msg.JobId,
702
+ type: msg.Type,
703
+ messageType: msg.MessageType,
704
+ message: cleanMessage(msg.Message),
705
+ subject: msg.Subject,
706
+ createdBy: msg.CreatedBy,
707
+ createdById: msg.CreatedByID,
708
+ createdDate: msg.CreatedDate,
709
+ latestMessage: msg.LatestMessage,
710
+ parentMessageId: msg.ParentMessageId,
711
+ attachmentOnly: msg.AttachmentOnly,
712
+ replyEmail: msg.ReplyEmail,
713
+ sentDate: msg.SentDate,
714
+ recipients: msg.Recipients.map((r) => ({
715
+ id: r.id,
716
+ companyUserId: r.companyUserId,
717
+ sent: r.Sent,
718
+ sentDate: r.SentDate,
719
+ delivered: r.Delivered,
720
+ deliveredDate: r.DeliveredDate,
721
+ failed: r.Failed,
722
+ failedDate: r.FailedDate,
723
+ failedDescription: r.FailedDescription
724
+ })),
725
+ attachments: msg.Attachments,
726
+ childMessageCount: msg.ChildMessages.length,
727
+ childMessages: msg.ChildMessages.map((child) => ({
728
+ id: child.id,
729
+ type: child.Type,
730
+ message: cleanMessage(child.Message),
731
+ createdBy: child.CreatedBy,
732
+ createdDate: child.CreatedDate
733
+ }))
734
+ }))
735
+ };
736
+ console.log(JSON.stringify(result));
737
+ });
738
+ messages.command("post").argument("<jobId>", "Job ID (GUID)").argument("<message>", "Message text to post").option(
739
+ "--notify <userIds>",
740
+ "Comma-separated user IDs (GUIDs) to notify"
741
+ ).description("Post a comment/message to a job, optionally notifying users").action(async (jobId, message, opts) => {
742
+ const emailRecipients = opts.notify ? opts.notify.split(",").map((id) => id.trim()) : [];
743
+ const data = await getClient2().post(
744
+ `/api/jobs/${jobId}/Messages`,
745
+ {
746
+ JobId: jobId,
747
+ Message: message,
748
+ RoleId: "1111111",
749
+ MessageType: "General Comment",
750
+ emailRecipients,
751
+ index: -1
752
+ }
753
+ );
754
+ console.log(
755
+ JSON.stringify({
756
+ id: data.JobMessageId,
757
+ jobId: data.JobId,
758
+ message: data.Message,
759
+ messageType: data.MessageType,
760
+ createdDate: data.CreatedDate,
761
+ notified: emailRecipients.length
762
+ })
763
+ );
764
+ });
765
+ }
766
+
767
+ // src/unofficial/commands/milestones.ts
768
+ function registerMilestonesCommands(parentCmd, getClient2) {
769
+ const milestones = parentCmd.command("milestones").description("Job milestone/status operations");
770
+ milestones.command("list").argument("<jobId>", "Job ID (GUID)").description("List all milestones and statuses for a job's workflow").action(async (jobId) => {
771
+ const data = await getClient2().get(
772
+ `/api/v3/job-workflows/${jobId}`
773
+ );
774
+ const result = data.Milestones.map((m) => ({
775
+ milestoneId: m.MilestoneId,
776
+ name: m.Name,
777
+ isCurrent: m.IsCurrent,
778
+ done: m.Done,
779
+ statuses: m.Statuses.map((s) => ({
780
+ statusId: s.StatusId,
781
+ name: s.Name.trim(),
782
+ isCurrent: s.IsCurrent,
783
+ done: s.Done
784
+ }))
785
+ }));
786
+ console.log(JSON.stringify(result));
787
+ });
788
+ milestones.command("set").argument("<jobId>", "Job ID (GUID)").argument("<statusName>", "Destination milestone/status name (case-insensitive)").option("--message <message>", "Optional comment when advancing", "").description("Set a job's milestone/status by name").action(async (jobId, statusName, opts) => {
789
+ const data = await getClient2().get(
790
+ `/api/v3/job-workflows/${jobId}`
791
+ );
792
+ const needle = statusName.toLowerCase().trim();
793
+ let matchedMilestoneId = null;
794
+ let matchedStatus = null;
795
+ for (const m of data.Milestones) {
796
+ if (m.Name.toLowerCase().trim() === needle) {
797
+ matchedMilestoneId = m.MilestoneId;
798
+ matchedStatus = m.Statuses[0] ?? null;
799
+ break;
800
+ }
801
+ for (const s of m.Statuses) {
802
+ if (s.Name.toLowerCase().trim() === needle) {
803
+ matchedMilestoneId = m.MilestoneId;
804
+ matchedStatus = s;
805
+ break;
806
+ }
807
+ }
808
+ if (matchedStatus) break;
809
+ }
810
+ if (!matchedMilestoneId || !matchedStatus) {
811
+ const available = data.Milestones.flatMap(
812
+ (m) => m.Statuses.map((s) => s.Name.trim())
813
+ );
814
+ console.error(
815
+ JSON.stringify({
816
+ error: `Status "${statusName}" not found`,
817
+ available
818
+ })
819
+ );
820
+ process.exitCode = 1;
821
+ return;
822
+ }
823
+ await getClient2().post(
824
+ `/api/v3/job-workflows/${jobId}/set-state`,
825
+ {
826
+ MilestoneId: matchedMilestoneId,
827
+ StatusId: matchedStatus.StatusId,
828
+ Message: opts.message
829
+ }
830
+ );
831
+ console.log(
832
+ JSON.stringify({
833
+ jobId,
834
+ milestoneId: matchedMilestoneId,
835
+ statusId: matchedStatus.StatusId,
836
+ statusName: matchedStatus.Name.trim(),
837
+ message: opts.message || null
838
+ })
839
+ );
840
+ });
841
+ }
842
+
843
+ // src/unofficial/commands/jobs.ts
844
+ async function resolveStatusId(client, statusName) {
845
+ const workflow = await client.get(
846
+ "/api/v3/workflows"
847
+ );
848
+ const needle = statusName.toLowerCase().trim();
849
+ for (const m of workflow.Milestones) {
850
+ for (const s of m.Statuses) {
851
+ if (s.Name.toLowerCase().trim() === needle) {
852
+ return { statusId: s.StatusId, milestoneName: m.Name };
853
+ }
854
+ }
855
+ }
856
+ return null;
857
+ }
858
+ async function getAvailableStatuses(client) {
859
+ const workflow = await client.get(
860
+ "/api/v3/workflows"
861
+ );
862
+ return workflow.Milestones.flatMap(
863
+ (m) => m.Statuses.map((s) => s.Name.trim())
864
+ );
865
+ }
866
+ function registerUnofficialJobsCommands(parentCmd, getClient2) {
867
+ const jobs = parentCmd.command("jobs").description("Unofficial job search with workflow status filtering");
868
+ jobs.command("list").description("List jobs, optionally filtered by workflow status or milestone").option("--status <name>", "Filter by workflow status name (case-insensitive)").option("--milestone <name>", "Filter by milestone name (e.g. Prospect, Approved)").option("--query <text>", "Search term").option("--sort <field>", "Sort: milestoneStart|desc, lastTouched|desc, createdDate|desc", "milestoneStart|desc").option("--page <n>", "Page number", "1").action(async (opts) => {
869
+ const client = getClient2();
870
+ const params = new URLSearchParams();
871
+ if (opts.status) {
872
+ const resolved = await resolveStatusId(client, opts.status);
873
+ if (!resolved) {
874
+ const available = await getAvailableStatuses(client);
875
+ console.error(
876
+ JSON.stringify({
877
+ error: `Status "${opts.status}" not found`,
878
+ available
879
+ })
880
+ );
881
+ process.exitCode = 1;
882
+ return;
883
+ }
884
+ params.append("filters", `currentStatusId=${resolved.statusId}`);
885
+ }
886
+ if (opts.milestone) {
887
+ params.append("filters", `currentMilestoneList=${opts.milestone}`);
888
+ }
889
+ params.set("sort", opts.sort);
890
+ params.set("page", opts.page);
891
+ params.set("type", "2");
892
+ params.set("loadAll", "false");
893
+ if (opts.query) params.set("query", opts.query);
894
+ const data = await client.get(
895
+ `/api/joblist?${params.toString()}`
896
+ );
897
+ const result = {
898
+ totalRecords: data.TotalRecords,
899
+ currentPage: data.CurrentPage,
900
+ totalPages: data.TotalPages,
901
+ jobs: data.results.map((j) => ({
902
+ id: j.Id,
903
+ name: j.Name,
904
+ address: j.FullAddress,
905
+ cityState: j.CityState,
906
+ milestone: j.CurrentMilestone,
907
+ status: j.CurrentStatus,
908
+ salesPerson: j.SalesPerson,
909
+ createdDate: j.CreatedDate,
910
+ lastTouched: j.LastTouched,
911
+ workTypes: j.WorkTypes,
912
+ trades: j.Trades
913
+ }))
914
+ };
915
+ console.log(JSON.stringify(result));
916
+ });
917
+ }
918
+
608
919
  // src/unofficial/commands/index.ts
609
920
  function getSessionFromEnv() {
610
921
  const email = process.env.ACCULYNX_EMAIL;
@@ -635,6 +946,9 @@ function registerUnofficialCommands(parentCmd) {
635
946
  return _client2;
636
947
  }
637
948
  registerDocumentsCommands(unofficial, getClient2);
949
+ registerMessagesCommands(unofficial, getClient2);
950
+ registerMilestonesCommands(unofficial, getClient2);
951
+ registerUnofficialJobsCommands(unofficial, getClient2);
638
952
  }
639
953
 
640
954
  // src/index.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsrev/acculynx-cli",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "CLI for the AccuLynx roofing CRM API",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,10 +28,12 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "commander": "^14.0.3"
31
+ "commander": "^14.0.3",
32
+ "turndown": "^7.2.2"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@types/node": "^25.4.0",
36
+ "@types/turndown": "^5.0.6",
35
37
  "tsup": "^8.5.1",
36
38
  "tsx": "^4.21.0",
37
39
  "typescript": "^5.9.3",