@okrlinkhub/okrhub 0.1.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 (148) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +579 -0
  3. package/dist/client/_generated/_ignore.d.ts +1 -0
  4. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  5. package/dist/client/_generated/_ignore.js +3 -0
  6. package/dist/client/_generated/_ignore.js.map +1 -0
  7. package/dist/client/index.d.ts +593 -0
  8. package/dist/client/index.d.ts.map +1 -0
  9. package/dist/client/index.js +704 -0
  10. package/dist/client/index.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +72 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +1986 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +3 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/entities/batch.d.ts +121 -0
  32. package/dist/component/entities/batch.d.ts.map +1 -0
  33. package/dist/component/entities/batch.js +81 -0
  34. package/dist/component/entities/batch.js.map +1 -0
  35. package/dist/component/entities/index.d.ts +13 -0
  36. package/dist/component/entities/index.d.ts.map +1 -0
  37. package/dist/component/entities/index.js +22 -0
  38. package/dist/component/entities/index.js.map +1 -0
  39. package/dist/component/entities/indicatorForecasts.d.ts +61 -0
  40. package/dist/component/entities/indicatorForecasts.d.ts.map +1 -0
  41. package/dist/component/entities/indicatorForecasts.js +180 -0
  42. package/dist/component/entities/indicatorForecasts.js.map +1 -0
  43. package/dist/component/entities/indicatorValues.d.ts +77 -0
  44. package/dist/component/entities/indicatorValues.d.ts.map +1 -0
  45. package/dist/component/entities/indicatorValues.js +218 -0
  46. package/dist/component/entities/indicatorValues.js.map +1 -0
  47. package/dist/component/entities/indicators.d.ts +90 -0
  48. package/dist/component/entities/indicators.d.ts.map +1 -0
  49. package/dist/component/entities/indicators.js +239 -0
  50. package/dist/component/entities/indicators.js.map +1 -0
  51. package/dist/component/entities/initiatives.d.ts +103 -0
  52. package/dist/component/entities/initiatives.d.ts.map +1 -0
  53. package/dist/component/entities/initiatives.js +275 -0
  54. package/dist/component/entities/initiatives.js.map +1 -0
  55. package/dist/component/entities/keyResults.d.ts +111 -0
  56. package/dist/component/entities/keyResults.d.ts.map +1 -0
  57. package/dist/component/entities/keyResults.js +284 -0
  58. package/dist/component/entities/keyResults.js.map +1 -0
  59. package/dist/component/entities/milestones.d.ts +93 -0
  60. package/dist/component/entities/milestones.d.ts.map +1 -0
  61. package/dist/component/entities/milestones.js +249 -0
  62. package/dist/component/entities/milestones.js.map +1 -0
  63. package/dist/component/entities/objectives.d.ts +99 -0
  64. package/dist/component/entities/objectives.d.ts.map +1 -0
  65. package/dist/component/entities/objectives.js +261 -0
  66. package/dist/component/entities/objectives.js.map +1 -0
  67. package/dist/component/entities/risks.d.ts +126 -0
  68. package/dist/component/entities/risks.d.ts.map +1 -0
  69. package/dist/component/entities/risks.js +315 -0
  70. package/dist/component/entities/risks.js.map +1 -0
  71. package/dist/component/externalId.d.ts +79 -0
  72. package/dist/component/externalId.d.ts.map +1 -0
  73. package/dist/component/externalId.js +124 -0
  74. package/dist/component/externalId.js.map +1 -0
  75. package/dist/component/lib/hmac.d.ts +18 -0
  76. package/dist/component/lib/hmac.d.ts.map +1 -0
  77. package/dist/component/lib/hmac.js +35 -0
  78. package/dist/component/lib/hmac.js.map +1 -0
  79. package/dist/component/lib/index.d.ts +7 -0
  80. package/dist/component/lib/index.d.ts.map +1 -0
  81. package/dist/component/lib/index.js +6 -0
  82. package/dist/component/lib/index.js.map +1 -0
  83. package/dist/component/lib/types.d.ts +30 -0
  84. package/dist/component/lib/types.d.ts.map +1 -0
  85. package/dist/component/lib/types.js +7 -0
  86. package/dist/component/lib/types.js.map +1 -0
  87. package/dist/component/lib/validation.d.ts +15 -0
  88. package/dist/component/lib/validation.d.ts.map +1 -0
  89. package/dist/component/lib/validation.js +29 -0
  90. package/dist/component/lib/validation.js.map +1 -0
  91. package/dist/component/okrhub.d.ts +31 -0
  92. package/dist/component/okrhub.d.ts.map +1 -0
  93. package/dist/component/okrhub.js +45 -0
  94. package/dist/component/okrhub.js.map +1 -0
  95. package/dist/component/schema.d.ts +943 -0
  96. package/dist/component/schema.d.ts.map +1 -0
  97. package/dist/component/schema.js +437 -0
  98. package/dist/component/schema.js.map +1 -0
  99. package/dist/component/sync/http.d.ts +30 -0
  100. package/dist/component/sync/http.d.ts.map +1 -0
  101. package/dist/component/sync/http.js +114 -0
  102. package/dist/component/sync/http.js.map +1 -0
  103. package/dist/component/sync/index.d.ts +7 -0
  104. package/dist/component/sync/index.d.ts.map +1 -0
  105. package/dist/component/sync/index.js +7 -0
  106. package/dist/component/sync/index.js.map +1 -0
  107. package/dist/component/sync/processor.d.ts +20 -0
  108. package/dist/component/sync/processor.d.ts.map +1 -0
  109. package/dist/component/sync/processor.js +67 -0
  110. package/dist/component/sync/processor.js.map +1 -0
  111. package/dist/component/sync/queue.d.ts +40 -0
  112. package/dist/component/sync/queue.d.ts.map +1 -0
  113. package/dist/component/sync/queue.js +176 -0
  114. package/dist/component/sync/queue.js.map +1 -0
  115. package/dist/react/index.d.ts +2 -0
  116. package/dist/react/index.d.ts.map +1 -0
  117. package/dist/react/index.js +6 -0
  118. package/dist/react/index.js.map +1 -0
  119. package/package.json +117 -0
  120. package/src/client/_generated/_ignore.ts +1 -0
  121. package/src/client/index.ts +1004 -0
  122. package/src/component/_generated/api.ts +88 -0
  123. package/src/component/_generated/component.ts +2685 -0
  124. package/src/component/_generated/dataModel.ts +60 -0
  125. package/src/component/_generated/server.ts +156 -0
  126. package/src/component/convex.config.ts +3 -0
  127. package/src/component/entities/batch.ts +90 -0
  128. package/src/component/entities/index.ts +64 -0
  129. package/src/component/entities/indicatorForecasts.ts +205 -0
  130. package/src/component/entities/indicatorValues.ts +254 -0
  131. package/src/component/entities/indicators.ts +290 -0
  132. package/src/component/entities/initiatives.ts +342 -0
  133. package/src/component/entities/keyResults.ts +334 -0
  134. package/src/component/entities/milestones.ts +296 -0
  135. package/src/component/entities/objectives.ts +294 -0
  136. package/src/component/entities/risks.ts +383 -0
  137. package/src/component/externalId.ts +172 -0
  138. package/src/component/lib/hmac.ts +53 -0
  139. package/src/component/lib/index.ts +7 -0
  140. package/src/component/lib/types.ts +31 -0
  141. package/src/component/lib/validation.ts +41 -0
  142. package/src/component/okrhub.ts +110 -0
  143. package/src/component/schema.ts +574 -0
  144. package/src/component/sync/http.ts +138 -0
  145. package/src/component/sync/index.ts +11 -0
  146. package/src/component/sync/processor.ts +77 -0
  147. package/src/component/sync/queue.ts +201 -0
  148. package/src/react/index.ts +7 -0
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,156 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ /**
111
+ * A set of services for use within Convex query functions.
112
+ *
113
+ * The query context is passed as the first argument to any Convex query
114
+ * function run on the server.
115
+ *
116
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
117
+ */
118
+ export type QueryCtx = GenericQueryCtx<DataModel>;
119
+
120
+ /**
121
+ * A set of services for use within Convex mutation functions.
122
+ *
123
+ * The mutation context is passed as the first argument to any Convex mutation
124
+ * function run on the server.
125
+ *
126
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
127
+ */
128
+ export type MutationCtx = GenericMutationCtx<DataModel>;
129
+
130
+ /**
131
+ * A set of services for use within Convex action functions.
132
+ *
133
+ * The action context is passed as the first argument to any Convex action
134
+ * function run on the server.
135
+ */
136
+ export type ActionCtx = GenericActionCtx<DataModel>;
137
+
138
+ /**
139
+ * An interface to read from the database within Convex query functions.
140
+ *
141
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
142
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
143
+ * building a query.
144
+ */
145
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
146
+
147
+ /**
148
+ * An interface to read from and write to the database within Convex mutation
149
+ * functions.
150
+ *
151
+ * Convex guarantees that all writes within a single mutation are
152
+ * executed atomically, so you never have to worry about partial writes leaving
153
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
154
+ * for the guarantees Convex provides your functions.
155
+ */
156
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("okrhub");
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Batch Operations for OKRHub Component
3
+ *
4
+ * Batch insert mutation for multiple entities.
5
+ */
6
+
7
+ import { v } from "convex/values";
8
+ import { mutation } from "../_generated/server.js";
9
+ import type { Id } from "../_generated/dataModel.js";
10
+ import type { EntityType } from "../externalId.js";
11
+ import { assertValidExternalId } from "../lib/validation.js";
12
+ import { batchPayloadValidator, type BatchPayload } from "../schema.js";
13
+
14
+ // ============================================================================
15
+ // BATCH MUTATIONS
16
+ // ============================================================================
17
+
18
+ /**
19
+ * Insert a batch of entities into LinkHub
20
+ */
21
+ export const insertBatch = mutation({
22
+ args: {
23
+ batch: batchPayloadValidator,
24
+ },
25
+ returns: v.object({
26
+ success: v.boolean(),
27
+ queueIds: v.array(v.id("syncQueue")),
28
+ errors: v.array(v.string()),
29
+ }),
30
+ handler: async (ctx, args) => {
31
+ const { batch } = args;
32
+ const queueIds: Id<"syncQueue">[] = [];
33
+ const errors: string[] = [];
34
+
35
+ // Process each entity type
36
+ const entityTypes: { key: keyof BatchPayload; type: EntityType }[] = [
37
+ { key: "companies", type: "objective" }, // Using objective as placeholder
38
+ { key: "teams", type: "objective" },
39
+ { key: "users", type: "objective" },
40
+ { key: "indicators", type: "indicator" },
41
+ { key: "objectives", type: "objective" },
42
+ { key: "keyResults", type: "keyResult" },
43
+ { key: "risks", type: "risk" },
44
+ { key: "initiatives", type: "initiative" },
45
+ { key: "milestones", type: "milestone" },
46
+ { key: "indicatorValues", type: "indicator" },
47
+ { key: "indicatorForecasts", type: "indicator" },
48
+ ];
49
+
50
+ for (const { key, type: _type } of entityTypes) {
51
+ const items = batch[key];
52
+ if (!items || items.length === 0) continue;
53
+
54
+ for (const item of items) {
55
+ try {
56
+ // Validate external ID
57
+ if ("externalId" in item && typeof item.externalId === "string") {
58
+ assertValidExternalId(item.externalId);
59
+ }
60
+
61
+ const payload = JSON.stringify(item);
62
+ const queueId = await ctx.db.insert("syncQueue", {
63
+ entityType: key,
64
+ externalId:
65
+ "externalId" in item && typeof item.externalId === "string"
66
+ ? item.externalId
67
+ : `batch-${Date.now()}`,
68
+ payload,
69
+ status: "pending",
70
+ attempts: 0,
71
+ createdAt: Date.now(),
72
+ });
73
+ queueIds.push(queueId);
74
+ } catch (error) {
75
+ const errorMessage =
76
+ error && typeof error === "object" && "message" in error
77
+ ? (error.message as string)
78
+ : "Unknown error";
79
+ errors.push(`${key}: ${errorMessage}`);
80
+ }
81
+ }
82
+ }
83
+
84
+ return {
85
+ success: errors.length === 0,
86
+ queueIds,
87
+ errors,
88
+ };
89
+ },
90
+ });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Entities barrel export
3
+ */
4
+
5
+ // Objectives
6
+ export {
7
+ createObjective,
8
+ getObjectivesByTeam,
9
+ getAllObjectives,
10
+ insertObjective,
11
+ } from "./objectives.js";
12
+
13
+ // Key Results
14
+ export {
15
+ createKeyResult,
16
+ getKeyResultsByObjective,
17
+ getAllKeyResults,
18
+ insertKeyResult,
19
+ } from "./keyResults.js";
20
+
21
+ // Risks
22
+ export {
23
+ createRisk,
24
+ getRisksByKeyResult,
25
+ getAllRisks,
26
+ insertRisk,
27
+ } from "./risks.js";
28
+
29
+ // Initiatives
30
+ export {
31
+ createInitiative,
32
+ getAllInitiatives,
33
+ insertInitiative,
34
+ } from "./initiatives.js";
35
+
36
+ // Indicators
37
+ export {
38
+ createIndicator,
39
+ getAllIndicators,
40
+ insertIndicator,
41
+ } from "./indicators.js";
42
+
43
+ // Indicator Values
44
+ export {
45
+ createIndicatorValue,
46
+ getAllIndicatorValues,
47
+ insertIndicatorValue,
48
+ } from "./indicatorValues.js";
49
+
50
+ // Indicator Forecasts
51
+ export {
52
+ createIndicatorForecast,
53
+ getAllIndicatorForecasts,
54
+ } from "./indicatorForecasts.js";
55
+
56
+ // Milestones
57
+ export {
58
+ createMilestone,
59
+ getAllMilestones,
60
+ insertMilestone,
61
+ } from "./milestones.js";
62
+
63
+ // Batch
64
+ export { insertBatch } from "./batch.js";
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Indicator Forecasts Entity for OKRHub Component
3
+ *
4
+ * CRUD operations and queries for Indicator Forecasts.
5
+ */
6
+
7
+ import { v } from "convex/values";
8
+ import { mutation, query } from "../_generated/server.js";
9
+ import type { Id } from "../_generated/dataModel.js";
10
+ import { assertValidExternalId } from "../lib/validation.js";
11
+ import { SyncStatusSchema } from "../schema.js";
12
+
13
+ // ============================================================================
14
+ // LOCAL CRUD MUTATIONS
15
+ // ============================================================================
16
+
17
+ /**
18
+ * Creates an indicator forecast locally and queues for sync
19
+ */
20
+ export const createIndicatorForecast = mutation({
21
+ args: {
22
+ sourceApp: v.string(),
23
+ sourceUrl: v.optional(v.string()),
24
+ indicatorExternalId: v.string(),
25
+ value: v.number(),
26
+ date: v.number(),
27
+ },
28
+ returns: v.object({
29
+ success: v.boolean(),
30
+ externalId: v.string(),
31
+ localId: v.id("indicatorForecasts"),
32
+ queueId: v.optional(v.id("syncQueue")),
33
+ error: v.optional(v.string()),
34
+ }),
35
+ handler: async (ctx, args) => {
36
+ const { sourceApp, sourceUrl, indicatorExternalId, value, date } = args;
37
+
38
+ try {
39
+ assertValidExternalId(indicatorExternalId, "indicatorExternalId");
40
+
41
+ const uuid = crypto.randomUUID();
42
+ const externalId = `${sourceApp}:indicatorForecast:${uuid}`;
43
+ const now = Date.now();
44
+
45
+ const localId = await ctx.db.insert("indicatorForecasts", {
46
+ externalId,
47
+ indicatorExternalId,
48
+ value,
49
+ date,
50
+ syncStatus: "pending",
51
+ createdAt: now,
52
+ });
53
+
54
+ const payload = JSON.stringify({
55
+ externalId,
56
+ indicatorExternalId,
57
+ value,
58
+ date,
59
+ sourceUrl,
60
+ createdAt: now,
61
+ });
62
+
63
+ const queueId = await ctx.db.insert("syncQueue", {
64
+ entityType: "indicatorForecast",
65
+ externalId,
66
+ payload,
67
+ status: "pending",
68
+ attempts: 0,
69
+ createdAt: now,
70
+ });
71
+
72
+ return {
73
+ success: true,
74
+ externalId,
75
+ localId,
76
+ queueId,
77
+ };
78
+ } catch (error) {
79
+ const errorMessage =
80
+ error && typeof error === "object" && "message" in error
81
+ ? (error.message as string)
82
+ : "Unknown error";
83
+
84
+ return {
85
+ success: false,
86
+ externalId: "",
87
+ localId: "" as Id<"indicatorForecasts">,
88
+ error: errorMessage,
89
+ };
90
+ }
91
+ },
92
+ });
93
+
94
+ // ============================================================================
95
+ // LOCAL QUERY FUNCTIONS
96
+ // ============================================================================
97
+
98
+ // ============================================================================
99
+ // UPDATE MUTATIONS
100
+ // ============================================================================
101
+
102
+ /**
103
+ * Updates an indicator forecast locally and queues for sync
104
+ * Resets syncStatus to "pending"
105
+ */
106
+ export const updateIndicatorForecast = mutation({
107
+ args: {
108
+ externalId: v.string(),
109
+ value: v.optional(v.number()),
110
+ date: v.optional(v.number()),
111
+ },
112
+ returns: v.object({
113
+ success: v.boolean(),
114
+ externalId: v.string(),
115
+ queueId: v.optional(v.id("syncQueue")),
116
+ error: v.optional(v.string()),
117
+ }),
118
+ handler: async (ctx, args) => {
119
+ const { externalId, value, date } = args;
120
+
121
+ try {
122
+ // Find the indicator forecast by externalId
123
+ const indicatorForecast = await ctx.db
124
+ .query("indicatorForecasts")
125
+ .withIndex("by_external_id", (q) => q.eq("externalId", externalId))
126
+ .first();
127
+
128
+ if (!indicatorForecast) {
129
+ return {
130
+ success: false,
131
+ externalId,
132
+ error: `Indicator forecast not found: ${externalId}`,
133
+ };
134
+ }
135
+
136
+ const now = Date.now();
137
+
138
+ // Update the indicator forecast
139
+ await ctx.db.patch(indicatorForecast._id, {
140
+ ...(value !== undefined && { value }),
141
+ ...(date !== undefined && { date }),
142
+ syncStatus: "pending",
143
+ });
144
+
145
+ // Create payload for sync with updated values
146
+ const updatedIndicatorForecast = {
147
+ externalId,
148
+ indicatorExternalId: indicatorForecast.indicatorExternalId,
149
+ value: value ?? indicatorForecast.value,
150
+ date: date ?? indicatorForecast.date,
151
+ };
152
+
153
+ const payload = JSON.stringify(updatedIndicatorForecast);
154
+
155
+ // Add to sync queue
156
+ const queueId = await ctx.db.insert("syncQueue", {
157
+ entityType: "indicatorForecast",
158
+ externalId,
159
+ payload,
160
+ status: "pending",
161
+ attempts: 0,
162
+ createdAt: now,
163
+ });
164
+
165
+ return {
166
+ success: true,
167
+ externalId,
168
+ queueId,
169
+ };
170
+ } catch (error) {
171
+ const errorMessage =
172
+ error && typeof error === "object" && "message" in error
173
+ ? (error.message as string)
174
+ : "Unknown error";
175
+
176
+ return {
177
+ success: false,
178
+ externalId,
179
+ error: errorMessage,
180
+ };
181
+ }
182
+ },
183
+ });
184
+
185
+ /**
186
+ * Gets all local indicator forecasts
187
+ */
188
+ export const getAllIndicatorForecasts = query({
189
+ args: {},
190
+ returns: v.array(
191
+ v.object({
192
+ _id: v.id("indicatorForecasts"),
193
+ _creationTime: v.number(),
194
+ externalId: v.string(),
195
+ indicatorExternalId: v.string(),
196
+ value: v.number(),
197
+ date: v.number(),
198
+ syncStatus: SyncStatusSchema,
199
+ createdAt: v.number(),
200
+ })
201
+ ),
202
+ handler: async (ctx) => {
203
+ return await ctx.db.query("indicatorForecasts").collect();
204
+ },
205
+ });