@bluecopa/core 0.1.14 → 0.1.16

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.
package/dist/index.es.js CHANGED
@@ -54,7 +54,7 @@ const createApiClient = () => {
54
54
  config.baseURL = copaConfig.apiBaseUrl;
55
55
  }
56
56
  if (copaConfig.accessToken && config.headers) {
57
- config.headers["X-COPA-TOKEN"] = `Bearer ${copaConfig.accessToken}`;
57
+ config.headers["X-COPA-TOKEN"] = `${copaConfig.accessToken}`;
58
58
  }
59
59
  if (copaConfig.workspaceId && config.headers) {
60
60
  config.headers["X-COPA-WORKSPACE-ID"] = copaConfig.workspaceId;
@@ -99,7 +99,7 @@ async function getLoggedInUserDetails() {
99
99
  throw { message, status };
100
100
  }
101
101
  }
102
- const index$b = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
102
+ const index$c = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
103
103
  __proto__: null,
104
104
  getLoggedInUserDetails
105
105
  }, Symbol.toStringTag, { value: "Module" }));
@@ -158,7 +158,7 @@ const getWorkflowInstanceStatusById = async (request) => {
158
158
  throw { message, status };
159
159
  }
160
160
  };
161
- const index$a = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
161
+ const index$b = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
162
162
  __proto__: null,
163
163
  WorkflowStatus,
164
164
  getWorkflowInstanceStatusById,
@@ -183,7 +183,7 @@ async function getFileUrlByFileId({
183
183
  throw { message, status };
184
184
  }
185
185
  }
186
- const index$9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
186
+ const index$a = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
187
187
  __proto__: null,
188
188
  getFileUrlByFileId
189
189
  }, Symbol.toStringTag, { value: "Module" }));
@@ -220,23 +220,42 @@ const runSampleDefinition = async (props) => {
220
220
  );
221
221
  };
222
222
  const runDefinition = async (props) => {
223
+ var _a, _b, _c, _d;
223
224
  const { definition, variable, inputs, limit, source } = props;
224
225
  if (!definition) {
225
- throw new Error(`Definition is null`);
226
+ throw {
227
+ message: "Definition is required for definition run",
228
+ status: 400
229
+ };
226
230
  }
227
231
  if (!variable) {
228
- throw new Error(`Variable is null`);
232
+ throw {
233
+ message: "Variable name is required for definition run",
234
+ status: 400
235
+ };
229
236
  }
230
237
  if (!inputs) {
231
- throw new Error(`Inputs is null`);
238
+ throw {
239
+ message: "Inputs are required for definition run",
240
+ status: 400
241
+ };
242
+ }
243
+ try {
244
+ const response = await apiClient.post(
245
+ "/definition/run",
246
+ { inputs, definition, variable, limit },
247
+ { cancelToken: source == null ? void 0 : source.token }
248
+ );
249
+ return response.data;
250
+ } catch (error) {
251
+ throw {
252
+ message: ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "Failed to run definition",
253
+ status: ((_c = error.response) == null ? void 0 : _c.status) || 500,
254
+ data: (_d = error.response) == null ? void 0 : _d.data
255
+ };
232
256
  }
233
- return apiClient.post(
234
- "/definition/run",
235
- { inputs, definition, variable, limit },
236
- { cancelToken: source == null ? void 0 : source.token }
237
- );
238
257
  };
239
- const index$8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
258
+ const index$9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
240
259
  __proto__: null,
241
260
  runDefinition,
242
261
  runPublishedDefinition,
@@ -274,7 +293,7 @@ const getWorksheetsByType = async (type) => {
274
293
  throw { message, status };
275
294
  }
276
295
  };
277
- const index$7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
296
+ const index$8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
278
297
  __proto__: null,
279
298
  getWorksheets,
280
299
  getWorksheetsByType
@@ -651,7 +670,7 @@ const getFiltersToBeAppliedOnDrilldown = (props) => {
651
670
  const getMetricFilterRule = (inputs) => {
652
671
  const isInputsArray = Array.isArray(inputs);
653
672
  const input = isInputsArray ? inputs[0] : inputs;
654
- return (input == null ? void 0 : input["rule_pivot"]) ?? defaultFilterRule;
673
+ return (input == null ? void 0 : input["rule_pivot"]) ?? defaultFilterRule$1;
655
674
  };
656
675
  const getColumnSettingsToSelectOptions = (columnSettings) => {
657
676
  return _.chain(columnSettings).filter((c) => !c.field.includes("__bc_") && !c.aggFunc).map((c) => {
@@ -670,7 +689,7 @@ const getColumnSettingsToSelectOptions = (columnSettings) => {
670
689
  };
671
690
  }).value();
672
691
  };
673
- const defaultFilterRule = {
692
+ const defaultFilterRule$1 = {
674
693
  is_not: false,
675
694
  rule_type: "and_cond",
676
695
  rules: []
@@ -933,13 +952,14 @@ const updatePromotedFiltersAndDateRangeToMetadataAndInputs = (props) => {
933
952
  ["filterOnAggregates"]: _.get(
934
953
  inputs,
935
954
  "filterOnAggregates",
936
- defaultFilterRule
955
+ defaultFilterRule$1
937
956
  ),
938
957
  ["rule_pivot"]: updatedFilterRule,
939
958
  date_range: updatedDateRange,
940
959
  to_currency: updateCurrencyFilterValue,
941
960
  showDimensionMappingValues: metadata.showDimensionMappingValues ?? false,
942
- showBinSortOrderValues: ((_a = metadata == null ? void 0 : metadata.inputs) == null ? void 0 : _a.showBinSortOrderValues) ?? false
961
+ showBinSortOrderValues: ((_a = metadata == null ? void 0 : metadata.inputs) == null ? void 0 : _a.showBinSortOrderValues) ?? false,
962
+ groupsSortOrder: (inputs == null ? void 0 : inputs.groupsSortOrder) ?? inputs.groupByInput.map((r) => [r, "asc"])
943
963
  };
944
964
  const updatedMetadata = {
945
965
  ...metadata,
@@ -1053,6 +1073,7 @@ const getInputsArray = (props) => {
1053
1073
  projectAsInput,
1054
1074
  showDimensionMappingValues,
1055
1075
  showBinSortOrderValues,
1076
+ groupsSortOrder: groupByInput.map((r) => [r, "asc"]),
1056
1077
  ...sortPivotInputsKey ? { [sortPivotInputsKey]: sortPivotInputsValue } : {}
1057
1078
  });
1058
1079
  });
@@ -1075,6 +1096,7 @@ const getInputsArray = (props) => {
1075
1096
  projectAsInput,
1076
1097
  showDimensionMappingValues,
1077
1098
  showBinSortOrderValues,
1099
+ groupsSortOrder: _.map(rowsToGroupBy[0], (r) => [r, "asc"]),
1078
1100
  ...sortPivotInputsKey ? { [sortPivotInputsKey]: sortPivotInputsValue } : {}
1079
1101
  };
1080
1102
  });
@@ -1094,6 +1116,7 @@ const getInputsArray = (props) => {
1094
1116
  projectAsInput,
1095
1117
  showDimensionMappingValues,
1096
1118
  showBinSortOrderValues,
1119
+ groupsSortOrder: _.map(rowsToGroupBy[0], (r) => [r, "asc"]),
1097
1120
  ...sortPivotInputsKey ? { [sortPivotInputsKey]: sortPivotInputsValue } : {}
1098
1121
  }
1099
1122
  ];
@@ -4824,11 +4847,17 @@ class CentrifugoWebsocket {
4824
4847
  this.centrifuge = null;
4825
4848
  this.subscriptions = {};
4826
4849
  this.isConnected = false;
4827
- }
4828
- connect() {
4829
4850
  if (!this.accessToken) {
4830
- throw new Error("Unable to connect to websocket, missing info");
4851
+ throw new Error("AccessToken is required");
4852
+ }
4853
+ if (!this.userId) {
4854
+ throw new Error("UserId is required");
4831
4855
  }
4856
+ if (!this.connectionUrl) {
4857
+ throw new Error("ConnectionUrl is required");
4858
+ }
4859
+ }
4860
+ connect() {
4832
4861
  if (!this.centrifuge) {
4833
4862
  this.centrifuge = new Centrifuge(
4834
4863
  [
@@ -4869,12 +4898,11 @@ class CentrifugoWebsocket {
4869
4898
  subscription.on("publication", (data) => {
4870
4899
  callback(_.get(data, "data", data));
4871
4900
  });
4872
- subscription.on("subscribing", (data) => {
4873
- console.log("subscribing", data);
4901
+ subscription.on("subscribing", () => {
4902
+ console.log("subscribing");
4874
4903
  });
4875
- subscription.on("subscribed", (data) => {
4876
- console.log("subscribed to", channelName, subscription);
4877
- console.log("subscribed", data);
4904
+ subscription.on("subscribed", () => {
4905
+ console.log("subscribed to", channelName);
4878
4906
  });
4879
4907
  subscription.subscribe();
4880
4908
  }
@@ -4926,12 +4954,320 @@ const websocketProviderFactory = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ O
4926
4954
  __proto__: null,
4927
4955
  WebsocketContextFactory
4928
4956
  }, Symbol.toStringTag, { value: "Module" }));
4929
- const index$6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4957
+ const getDescription = async (props) => {
4958
+ var _a, _b, _c, _d;
4959
+ const { definition, variable, inputs, source } = props;
4960
+ if (!definition) {
4961
+ throw {
4962
+ message: "Definition is required for description lookup",
4963
+ status: 400
4964
+ };
4965
+ }
4966
+ if (!variable) {
4967
+ throw {
4968
+ message: "Variable name is required for description lookup",
4969
+ status: 400
4970
+ };
4971
+ }
4972
+ if (!inputs) {
4973
+ throw {
4974
+ message: "Inputs are required for description lookup",
4975
+ status: 400
4976
+ };
4977
+ }
4978
+ try {
4979
+ const response = await apiClient.post(
4980
+ "/definition/describe",
4981
+ { definition, variable, inputs },
4982
+ { cancelToken: source == null ? void 0 : source.token }
4983
+ );
4984
+ return response.data;
4985
+ } catch (error) {
4986
+ throw {
4987
+ message: ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "Failed to fetch variable description",
4988
+ status: ((_c = error.response) == null ? void 0 : _c.status) || 500,
4989
+ data: (_d = error.response) == null ? void 0 : _d.data
4990
+ };
4991
+ }
4992
+ };
4993
+ const defaultFilterRule = {
4994
+ is_not: false,
4995
+ rule_type: "and_cond",
4996
+ rules: []
4997
+ };
4998
+ const createFilterRuleFromValues = (column, values) => {
4999
+ return {
5000
+ rule_type: "and_cond",
5001
+ is_not: false,
5002
+ is_case_sensitive: false,
5003
+ rules: [
5004
+ {
5005
+ rule_type: "cond",
5006
+ col: column,
5007
+ operator: "in_op",
5008
+ value: values,
5009
+ is_not: false
5010
+ }
5011
+ ]
5012
+ };
5013
+ };
5014
+ const getSheetById = (sheets, sheetId) => sheets.find((s) => s.id === sheetId);
5015
+ const convertToPromotedFilter = (statementFilter, statement) => {
5016
+ var _a;
5017
+ try {
5018
+ const sheet = getSheetById(statement.sheets || [], statementFilter.sheetId);
5019
+ if (!sheet) {
5020
+ console.warn(
5021
+ `Sheet ${statementFilter.sheetId} not found for promoted filter`
5022
+ );
5023
+ return null;
5024
+ }
5025
+ const metadata = (_a = sheet.customModel) == null ? void 0 : _a.metadata;
5026
+ const definitionModel = sheet.definitionModel;
5027
+ if (!metadata || !definitionModel) {
5028
+ console.warn(`Metadata or definition not found for sheet ${sheet.id}`);
5029
+ return null;
5030
+ }
5031
+ const columnSettings = metadata.columnSettings || [];
5032
+ const sheetDetails = {
5033
+ sheetId: statementFilter.sheetId,
5034
+ definitionModel,
5035
+ parentTableVariable: metadata.parentTableVariable || "",
5036
+ inputs: metadata.inputs || {}
5037
+ };
5038
+ const rule = createFilterRuleFromValues(
5039
+ statementFilter.column,
5040
+ statementFilter.values
5041
+ );
5042
+ const appliedOnBlocks = statementFilter.lineIds.map((lineId) => {
5043
+ const lineSheet = getSheetById(statement.sheets || [], lineId);
5044
+ return {
5045
+ blockId: lineId,
5046
+ blockName: (lineSheet == null ? void 0 : lineSheet.name) || lineId,
5047
+ applied: true
5048
+ };
5049
+ });
5050
+ const columnSetting = columnSettings.find(
5051
+ (c) => c.field === statementFilter.column
5052
+ );
5053
+ const promotedFilter = {
5054
+ name: statementFilter.name,
5055
+ rule,
5056
+ filterColumnsBy: metadata.filterColumnsBy || {},
5057
+ sheetDetails,
5058
+ appliedOnBlocks,
5059
+ datasetId: statementFilter.datasetId,
5060
+ datasetName: statementFilter.datasetName || "",
5061
+ blockColumnSettings: columnSettings,
5062
+ blockId: statementFilter.sheetId,
5063
+ uniqueValueCount: columnSetting == null ? void 0 : columnSetting.unique_count,
5064
+ id: statementFilter.column
5065
+ };
5066
+ return promotedFilter;
5067
+ } catch (error) {
5068
+ console.error("Error converting to promoted filter:", error);
5069
+ return null;
5070
+ }
5071
+ };
5072
+ const convertToCommonFilter = async (statementFilter, statement) => {
5073
+ var _a;
5074
+ try {
5075
+ const sheet = getSheetById(statement.sheets || [], statementFilter.sheetId);
5076
+ if (!sheet) {
5077
+ console.warn(
5078
+ `Sheet ${statementFilter.sheetId} not found for common filter`
5079
+ );
5080
+ return null;
5081
+ }
5082
+ const metadata = (_a = sheet.customModel) == null ? void 0 : _a.metadata;
5083
+ const definitionModel = sheet.definitionModel;
5084
+ if (!metadata || !definitionModel) {
5085
+ console.warn(`Metadata or definition not found for sheet ${sheet.id}`);
5086
+ return null;
5087
+ }
5088
+ const columnSettings = metadata.columnSettings || [];
5089
+ const sheetDetails = {
5090
+ sheetId: statementFilter.sheetId,
5091
+ definitionModel,
5092
+ parentTableVariable: metadata.parentTableVariable || "",
5093
+ inputs: metadata.inputs || {}
5094
+ };
5095
+ const rule = createFilterRuleFromValues(
5096
+ statementFilter.column,
5097
+ statementFilter.values
5098
+ );
5099
+ const appliedOnBlocks = statementFilter.linesToApply.map((lineMapping) => {
5100
+ var _a2, _b;
5101
+ const lineSheet = getSheetById(
5102
+ statement.sheets || [],
5103
+ lineMapping.lineId
5104
+ );
5105
+ const lineColumnSettings = (_b = (_a2 = lineSheet == null ? void 0 : lineSheet.customModel) == null ? void 0 : _a2.metadata) == null ? void 0 : _b.columnSettings;
5106
+ const columnSelectOptions = _.map(lineColumnSettings, (cs) => ({
5107
+ label: cs.headerName,
5108
+ value: cs.field,
5109
+ option: cs
5110
+ }));
5111
+ return {
5112
+ blockId: lineMapping.lineId,
5113
+ blockName: (lineSheet == null ? void 0 : lineSheet.name) || lineMapping.lineId,
5114
+ applied: true,
5115
+ column: lineMapping.column,
5116
+ columnSettings: columnSelectOptions
5117
+ };
5118
+ });
5119
+ const datasetDefinitionModel = {
5120
+ imports: [
5121
+ {
5122
+ loc: statementFilter.datasetId,
5123
+ to: statementFilter.datasetName,
5124
+ import_type: "dataset"
5125
+ }
5126
+ ],
5127
+ loads: [],
5128
+ variables: [],
5129
+ metrics: [],
5130
+ permissions: [],
5131
+ exports: [],
5132
+ inputs: {
5133
+ date_range: {}
5134
+ }
5135
+ };
5136
+ let columnDescResult;
5137
+ try {
5138
+ const response = await getDescription({
5139
+ inputs: {},
5140
+ definition: datasetDefinitionModel,
5141
+ variable: statementFilter.datasetName
5142
+ });
5143
+ const descriptionResults = response.data;
5144
+ columnDescResult = _.find(
5145
+ descriptionResults,
5146
+ (desc) => desc.name === statementFilter.column
5147
+ );
5148
+ } catch (error) {
5149
+ console.warn(
5150
+ `Failed to get description for dataset ${statementFilter.datasetName}:`,
5151
+ error
5152
+ );
5153
+ columnDescResult = {
5154
+ name: statementFilter.column,
5155
+ data_type: "string",
5156
+ is_currency_column: false,
5157
+ datasetId: statementFilter.datasetId,
5158
+ datasetName: statementFilter.datasetName
5159
+ };
5160
+ }
5161
+ const filterColumnsBy = metadata.filterColumnsBy ? metadata.filterColumnsBy : { [statementFilter.column]: "value" };
5162
+ const commonFilter = {
5163
+ name: statementFilter.name,
5164
+ column: columnDescResult,
5165
+ rule,
5166
+ sheetDetails,
5167
+ filterColumnsBy,
5168
+ appliedOnBlocks,
5169
+ datasetName: statementFilter.datasetName || "",
5170
+ datasetId: statementFilter.datasetId,
5171
+ columnSettings,
5172
+ uniqueValueCount: columnDescResult == null ? void 0 : columnDescResult["unique_count"],
5173
+ id: statementFilter.column
5174
+ };
5175
+ return commonFilter;
5176
+ } catch (error) {
5177
+ console.error("Error converting to common filter:", error);
5178
+ return null;
5179
+ }
5180
+ };
5181
+ const convertStatementFiltersToFullTypes = async (promotedFilters, commonFilters, statement) => {
5182
+ const convertedPromoted = promotedFilters.map((f) => convertToPromotedFilter(f, statement)).filter((f) => f !== null);
5183
+ const convertedCommonPromises = commonFilters.map(
5184
+ (f) => convertToCommonFilter(f, statement)
5185
+ );
5186
+ const convertedCommon = (await Promise.all(convertedCommonPromises)).filter(
5187
+ (f) => f !== null
5188
+ );
5189
+ return {
5190
+ promotedFilters: convertedPromoted,
5191
+ commonFilters: convertedCommon
5192
+ };
5193
+ };
5194
+ const filterConverters = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4930
5195
  __proto__: null,
4931
- formatDate,
4932
- getMetricDefinition,
4933
- inputTableUtils: inputTableDefinition,
4934
- websocketUtils: websocketProviderFactory
5196
+ convertStatementFiltersToFullTypes,
5197
+ convertToCommonFilter,
5198
+ convertToPromotedFilter,
5199
+ createFilterRuleFromValues,
5200
+ defaultFilterRule
5201
+ }, Symbol.toStringTag, { value: "Module" }));
5202
+ const addFilterToRunInputs = (runInputs, lineValue, filter) => {
5203
+ if (!runInputs[lineValue]) {
5204
+ runInputs[lineValue] = filter;
5205
+ } else if (Array.isArray(runInputs[lineValue])) {
5206
+ runInputs[lineValue].push(filter);
5207
+ } else {
5208
+ runInputs[lineValue] = [runInputs[lineValue], filter];
5209
+ }
5210
+ };
5211
+ const convertFiltersToRunInputs = (promotedFilters, commonFilters, statementSheet) => {
5212
+ var _a, _b;
5213
+ const runInputs = {};
5214
+ const allLines = ((_b = (_a = statementSheet.customModel) == null ? void 0 : _a.sections) == null ? void 0 : _b.flatMap((section) => section.lines)) ?? [];
5215
+ _.forEach(promotedFilters, (filter) => {
5216
+ _.forEach(filter.lineIds, (lineId) => {
5217
+ var _a2;
5218
+ const lineValue = (_a2 = _.find(allLines, (l) => l.id === lineId)) == null ? void 0 : _a2.value;
5219
+ if (!lineValue) {
5220
+ console.warn(`Line with id ${lineId} not found in statement sheet`);
5221
+ return;
5222
+ }
5223
+ const lineFilter = {
5224
+ dataset_id: filter.datasetId,
5225
+ filter_input_key: "rule_pivot",
5226
+ filter_value: createFilterRuleFromValues(filter.column, filter.values)
5227
+ };
5228
+ addFilterToRunInputs(runInputs, lineValue, lineFilter);
5229
+ });
5230
+ });
5231
+ _.forEach(commonFilters, (filter) => {
5232
+ _.forEach(filter.linesToApply, (lineMapping) => {
5233
+ var _a2;
5234
+ const lineValue = (_a2 = _.find(
5235
+ allLines,
5236
+ (l) => l.id === lineMapping.lineId
5237
+ )) == null ? void 0 : _a2.value;
5238
+ if (!lineValue) {
5239
+ console.warn(
5240
+ `Line with id ${lineMapping.lineId} not found in statement sheet`
5241
+ );
5242
+ return;
5243
+ }
5244
+ const columnName = lineMapping.column;
5245
+ const lineFilter = {
5246
+ dataset_id: filter.datasetId,
5247
+ filter_input_key: "rule_pivot",
5248
+ filter_value: createFilterRuleFromValues(columnName, filter.values)
5249
+ };
5250
+ addFilterToRunInputs(runInputs, lineValue, lineFilter);
5251
+ });
5252
+ });
5253
+ return runInputs;
5254
+ };
5255
+ const separateColumnFilters = (columnFilters) => {
5256
+ const promotedFilters = [];
5257
+ const commonFilters = [];
5258
+ _.forEach(columnFilters, (filter) => {
5259
+ if (filter.filterType === "promoted") {
5260
+ promotedFilters.push(filter);
5261
+ } else if (filter.filterType === "common") {
5262
+ commonFilters.push(filter);
5263
+ }
5264
+ });
5265
+ return { promotedFilters, commonFilters };
5266
+ };
5267
+ const filterUtils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5268
+ __proto__: null,
5269
+ convertFiltersToRunInputs,
5270
+ separateColumnFilters
4935
5271
  }, Symbol.toStringTag, { value: "Module" }));
4936
5272
  async function downloadFile(loc, contentType) {
4937
5273
  if (!loc) return null;
@@ -4960,6 +5296,157 @@ async function downloadFile(loc, contentType) {
4960
5296
  throw error;
4961
5297
  }
4962
5298
  }
5299
+ const hydrateStatement = async (workbook) => {
5300
+ var _a;
5301
+ const workbookModel = {
5302
+ ...workbook,
5303
+ sheets: [...workbook.sheets]
5304
+ };
5305
+ const sheetsGroupedByType = _.groupBy(workbookModel.sheets, "type");
5306
+ const statementSheet = (_a = sheetsGroupedByType.STATEMENT_SHEET) == null ? void 0 : _a[0];
5307
+ if (!statementSheet) {
5308
+ throw new Error("No STATEMENT_SHEET found in workbook");
5309
+ }
5310
+ if (!statementSheet.externalDataId) {
5311
+ throw new Error("STATEMENT_SHEET is missing required externalDataId");
5312
+ }
5313
+ if (!statementSheet.modelId) {
5314
+ throw new Error("STATEMENT_SHEET is missing required modelId");
5315
+ }
5316
+ const statementSheetDefinitionModelId = statementSheet.externalDataId;
5317
+ const statementSheetCustomModelId = statementSheet.modelId;
5318
+ const modelResultsPromises = [
5319
+ downloadFile(statementSheetDefinitionModelId, "application/json"),
5320
+ downloadFile(statementSheetCustomModelId, "application/json")
5321
+ ];
5322
+ if (!_.isEmpty(sheetsGroupedByType.PIVOT)) {
5323
+ const commonDefinitionModelId = sheetsGroupedByType.PIVOT[0].externalDataId;
5324
+ const commonCustomModelId = sheetsGroupedByType.PIVOT[0].modelId;
5325
+ modelResultsPromises.push(
5326
+ downloadFile(commonDefinitionModelId, "application/json")
5327
+ );
5328
+ modelResultsPromises.push(
5329
+ downloadFile(commonCustomModelId, "application/json")
5330
+ );
5331
+ } else {
5332
+ modelResultsPromises.push(Promise.resolve({}), Promise.resolve({}));
5333
+ }
5334
+ if (!_.isEmpty(sheetsGroupedByType.PLAN)) {
5335
+ const commonPlanDefinitionModelId = sheetsGroupedByType.PLAN[0].externalDataId;
5336
+ const commonPlanCustomModelId = sheetsGroupedByType.PLAN[0].modelId;
5337
+ modelResultsPromises.push(
5338
+ downloadFile(commonPlanDefinitionModelId, "application/json")
5339
+ );
5340
+ modelResultsPromises.push(
5341
+ downloadFile(commonPlanCustomModelId, "application/json")
5342
+ );
5343
+ } else {
5344
+ modelResultsPromises.push(Promise.resolve({}), Promise.resolve({}));
5345
+ }
5346
+ const results = await Promise.allSettled(modelResultsPromises);
5347
+ let commonDefinitionModel = {};
5348
+ let commonCustomModel = {};
5349
+ let planCommonDefinitionModel = {};
5350
+ let planCommonCustomModel = {};
5351
+ const [
5352
+ resStatementDef,
5353
+ resStatementCustom,
5354
+ resPivotDef,
5355
+ resPivotCustom,
5356
+ resPlanDef,
5357
+ resPlanCustom
5358
+ ] = results;
5359
+ if (resStatementDef.status !== "fulfilled") {
5360
+ throw new Error(
5361
+ `Failed to download STATEMENT definition model: ${resStatementDef.reason ?? "unknown error"}`
5362
+ );
5363
+ }
5364
+ if (resStatementCustom.status !== "fulfilled") {
5365
+ throw new Error(
5366
+ `Failed to download STATEMENT custom model: ${resStatementCustom.reason ?? "unknown error"}`
5367
+ );
5368
+ }
5369
+ statementSheet.definitionModel = resStatementDef.value;
5370
+ statementSheet.customModel = resStatementCustom.value;
5371
+ if (resPivotDef && resPivotDef.status === "fulfilled") {
5372
+ commonDefinitionModel = resPivotDef.value;
5373
+ }
5374
+ if (resPivotCustom && resPivotCustom.status === "fulfilled") {
5375
+ commonCustomModel = resPivotCustom.value;
5376
+ }
5377
+ if (resPlanDef && resPlanDef.status === "fulfilled") {
5378
+ planCommonDefinitionModel = resPlanDef.value;
5379
+ }
5380
+ if (resPlanCustom && resPlanCustom.status === "fulfilled") {
5381
+ planCommonCustomModel = resPlanCustom.value;
5382
+ }
5383
+ _.forEach(sheetsGroupedByType.PIVOT, (sheet) => {
5384
+ sheet.customModel = commonCustomModel[sheet.id];
5385
+ sheet.definitionModel = commonDefinitionModel[sheet.id];
5386
+ });
5387
+ _.forEach(sheetsGroupedByType.PLAN, (sheet) => {
5388
+ sheet.customModel = planCommonCustomModel[sheet.id];
5389
+ sheet.definitionModel = planCommonDefinitionModel[sheet.id];
5390
+ });
5391
+ return workbookModel;
5392
+ };
5393
+ const generatePushID = function() {
5394
+ const PUSH_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
5395
+ const pushCharLength = PUSH_CHARS.length;
5396
+ let lastPushTime = 0;
5397
+ const lastRandChars = [];
5398
+ return function() {
5399
+ let now = (/* @__PURE__ */ new Date()).getTime();
5400
+ const duplicateTime = now === lastPushTime;
5401
+ lastPushTime = now;
5402
+ const timeStampChars = new Array(8);
5403
+ for (let i2 = 7; i2 >= 0; i2--) {
5404
+ timeStampChars[i2] = PUSH_CHARS.charAt(now % pushCharLength);
5405
+ now = Math.floor(now / pushCharLength);
5406
+ }
5407
+ if (now !== 0)
5408
+ throw new Error("We should have converted the entire timestamp.");
5409
+ let id = timeStampChars.join("");
5410
+ let i;
5411
+ if (!duplicateTime) {
5412
+ for (i = 0; i < 12; i++) {
5413
+ lastRandChars[i] = Math.floor(Math.random() * pushCharLength);
5414
+ }
5415
+ } else {
5416
+ for (i = 11; i >= 0 && lastRandChars[i] === pushCharLength - 1; i--) {
5417
+ lastRandChars[i] = 0;
5418
+ }
5419
+ lastRandChars[i]++;
5420
+ }
5421
+ for (i = 0; i < 12; i++) {
5422
+ id += PUSH_CHARS.charAt(lastRandChars[i]);
5423
+ }
5424
+ if (id.length != 20) throw new Error("Length should be 20.");
5425
+ return id;
5426
+ };
5427
+ }();
5428
+ const getUniqueDuplicateName = (name, collectionToCheckIn, suffix = "Copy", concatChar = "_") => {
5429
+ if (!name) {
5430
+ throw new Error("Invalid name provided to getUniqueDuplicateName");
5431
+ }
5432
+ let newName = `${name}${concatChar}${suffix}`.trim();
5433
+ for (let i = 1; collectionToCheckIn.includes(newName); i++) {
5434
+ newName = `${name}${concatChar}${suffix}${concatChar}${i}`;
5435
+ }
5436
+ return newName.trim();
5437
+ };
5438
+ const index$7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5439
+ __proto__: null,
5440
+ formatDate,
5441
+ generatePushID,
5442
+ getMetricDefinition,
5443
+ getUniqueDuplicateName,
5444
+ hydrateStatement,
5445
+ inputTableUtils: inputTableDefinition,
5446
+ statementFilterConverters: filterConverters,
5447
+ statementFilterUtils: filterUtils,
5448
+ websocketUtils: websocketProviderFactory
5449
+ }, Symbol.toStringTag, { value: "Module" }));
4963
5450
  const hydrateWorksheet = async (sheet) => {
4964
5451
  try {
4965
5452
  if (!sheet) return sheet;
@@ -4987,7 +5474,7 @@ const hydrateWorksheet = async (sheet) => {
4987
5474
  throw error;
4988
5475
  }
4989
5476
  };
4990
- const getData$2 = async (metricSheetId, options) => {
5477
+ const getData$3 = async (metricSheetId, options) => {
4991
5478
  var _a, _b, _c, _d, _e, _f;
4992
5479
  const worksheets = await getWorksheets([metricSheetId]);
4993
5480
  if (_.isEmpty(worksheets)) return {};
@@ -5113,9 +5600,9 @@ const getData$2 = async (metricSheetId, options) => {
5113
5600
  resultData = _.flatten(resultData);
5114
5601
  return { data: resultData };
5115
5602
  };
5116
- const index$5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5603
+ const index$6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5117
5604
  __proto__: null,
5118
- getData: getData$2
5605
+ getData: getData$3
5119
5606
  }, Symbol.toStringTag, { value: "Module" }));
5120
5607
  async function createThread(request) {
5121
5608
  var _a, _b, _c;
@@ -5264,7 +5751,7 @@ async function checkSubscriptionStatus(userId, threadId) {
5264
5751
  throw { message, status };
5265
5752
  }
5266
5753
  }
5267
- const index$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5754
+ const index$5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5268
5755
  __proto__: null,
5269
5756
  checkSubscriptionStatus,
5270
5757
  createThread,
@@ -5404,7 +5891,7 @@ class DefinitionBuilder {
5404
5891
  });
5405
5892
  }
5406
5893
  }
5407
- const getData$1 = async (datasetId, options) => {
5894
+ const getData$2 = async (datasetId, options) => {
5408
5895
  var _a, _b, _c;
5409
5896
  try {
5410
5897
  if (!datasetId) {
@@ -5468,10 +5955,10 @@ const getAllDatasets = async () => {
5468
5955
  throw { message, status };
5469
5956
  }
5470
5957
  };
5471
- const index$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5958
+ const index$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5472
5959
  __proto__: null,
5473
5960
  getAllDatasets,
5474
- getData: getData$1,
5961
+ getData: getData$2,
5475
5962
  getSampleData
5476
5963
  }, Symbol.toStringTag, { value: "Module" }));
5477
5964
  const getPublishedWorkbookById = async ({
@@ -5524,7 +6011,7 @@ const getTableById = async (tableId) => {
5524
6011
  throw { message, status };
5525
6012
  }
5526
6013
  };
5527
- const getData = async ({
6014
+ const getData$1 = async ({
5528
6015
  inputTableId: inputTableWorkbookId,
5529
6016
  inputTableViewId,
5530
6017
  pageParams = {},
@@ -5655,9 +6142,9 @@ const getInputTables = async () => {
5655
6142
  throw { message, status };
5656
6143
  }
5657
6144
  };
5658
- const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
6145
+ const index$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5659
6146
  __proto__: null,
5660
- getData,
6147
+ getData: getData$1,
5661
6148
  getInputTables,
5662
6149
  getTableById
5663
6150
  }, Symbol.toStringTag, { value: "Module" }));
@@ -5677,24 +6164,294 @@ const getWorkbooksByType = async (type) => {
5677
6164
  throw { message, status };
5678
6165
  }
5679
6166
  };
5680
- const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
6167
+ const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5681
6168
  __proto__: null,
5682
6169
  getPublishedWorkbookById,
5683
6170
  getWorkbooksByType
5684
6171
  }, Symbol.toStringTag, { value: "Module" }));
6172
+ const getViewsBySheetId = async (sheetId) => {
6173
+ var _a, _b, _c;
6174
+ if (!sheetId) {
6175
+ throw { message: "Sheet ID is required", status: 400 };
6176
+ }
6177
+ try {
6178
+ const response = await apiClient.get(
6179
+ `/statement/get-views-by-sheet-id/${sheetId}`
6180
+ );
6181
+ if (!response.data) {
6182
+ throw { message: "Failed to fetch statement views", status: 500 };
6183
+ }
6184
+ return response.data;
6185
+ } catch (error) {
6186
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while fetching statement views";
6187
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6188
+ throw { message, status };
6189
+ }
6190
+ };
6191
+ const getRunsByViewId = async (viewId) => {
6192
+ var _a, _b, _c;
6193
+ if (!viewId) {
6194
+ throw { message: "View ID is required", status: 400 };
6195
+ }
6196
+ try {
6197
+ const response = await apiClient.get(
6198
+ `/statement/get-runs-by-view-id/${viewId}`
6199
+ );
6200
+ if (!response.data) {
6201
+ throw { message: "Failed to fetch view runs", status: 500 };
6202
+ }
6203
+ return response.data;
6204
+ } catch (error) {
6205
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while fetching view runs";
6206
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6207
+ throw { message, status };
6208
+ }
6209
+ };
6210
+ const getData = async ({
6211
+ statementId,
6212
+ viewId,
6213
+ runId
6214
+ }) => {
6215
+ var _a, _b, _c;
6216
+ try {
6217
+ if (!statementId) {
6218
+ throw { message: "Statement ID is required", status: 400 };
6219
+ }
6220
+ const statement = await getPublishedWorkbookById({
6221
+ type: "STATEMENT",
6222
+ id: statementId
6223
+ });
6224
+ if (!statement || !statement.sheets) {
6225
+ throw { message: "Statement not found or has no sheets", status: 404 };
6226
+ }
6227
+ const statementSheet = statement.sheets.find(
6228
+ (sheet) => sheet.type === "STATEMENT_SHEET"
6229
+ );
6230
+ if (!statementSheet || !statementSheet.id) {
6231
+ throw {
6232
+ message: "Statement sheet not found in the workbook",
6233
+ status: 404
6234
+ };
6235
+ }
6236
+ const statementViews = await getViewsBySheetId(statementSheet.id);
6237
+ if (_.isEmpty(statementViews)) {
6238
+ throw { message: "No views found for this statement", status: 404 };
6239
+ }
6240
+ let targetView;
6241
+ if (viewId) {
6242
+ targetView = statementViews.find((v) => v.id === viewId);
6243
+ if (!targetView) {
6244
+ throw { message: `View with ID ${viewId} not found`, status: 404 };
6245
+ }
6246
+ } else {
6247
+ const defaultView = _.find(
6248
+ statementViews,
6249
+ (v) => {
6250
+ var _a2;
6251
+ return Boolean((_a2 = v.customFields) == null ? void 0 : _a2.isDefault);
6252
+ }
6253
+ );
6254
+ if (defaultView) {
6255
+ targetView = defaultView;
6256
+ } else {
6257
+ targetView = statementViews[0];
6258
+ }
6259
+ }
6260
+ if (!targetView) {
6261
+ throw { message: "No valid view found for this statement", status: 404 };
6262
+ }
6263
+ const results = await getRunsByViewId(targetView.id);
6264
+ if (_.isEmpty(results)) {
6265
+ throw { message: "No runs found for this view", status: 404 };
6266
+ }
6267
+ const latestResult = _.orderBy(
6268
+ results,
6269
+ [(r) => r.lastModifiedDate || r.createdDate],
6270
+ ["desc"]
6271
+ )[0];
6272
+ let runToFetchResult = latestResult;
6273
+ if (runId) {
6274
+ runToFetchResult = _.find(results, (r) => r.id === runId);
6275
+ if (!runToFetchResult) {
6276
+ throw { message: `Run with ID ${runId} not found.`, status: 404 };
6277
+ }
6278
+ }
6279
+ if (runToFetchResult.status === "FAILED") {
6280
+ throw { message: "Latest run has failed", status: 500 };
6281
+ }
6282
+ if (runToFetchResult.status === "SCHEDULED" || runToFetchResult.status === "RUNNING") {
6283
+ throw { message: "Run in progress", status: 202 };
6284
+ }
6285
+ if (!runToFetchResult.artifactLocation) {
6286
+ throw { message: "Latest result does not have a data path", status: 500 };
6287
+ }
6288
+ const dataResponse = await downloadFile(
6289
+ runToFetchResult.artifactLocation,
6290
+ "application/json"
6291
+ );
6292
+ return dataResponse;
6293
+ } catch (error) {
6294
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while fetching statement data";
6295
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6296
+ throw { message, status };
6297
+ }
6298
+ };
6299
+ const getViewById = async (viewId) => {
6300
+ var _a, _b, _c;
6301
+ if (!viewId) {
6302
+ throw { message: "View ID is required", status: 400 };
6303
+ }
6304
+ try {
6305
+ const response = await apiClient.get(`/statement/get-view-by-id/${viewId}`);
6306
+ if (!response.data) {
6307
+ throw { message: "Failed to fetch statement view", status: 500 };
6308
+ }
6309
+ return response.data;
6310
+ } catch (error) {
6311
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while fetching statement view";
6312
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6313
+ throw { message, status };
6314
+ }
6315
+ };
6316
+ const createNewRun = async ({
6317
+ statementId,
6318
+ viewId,
6319
+ runId,
6320
+ options
6321
+ }) => {
6322
+ var _a, _b, _c;
6323
+ if (!statementId) {
6324
+ throw { message: "Statement ID is required", status: 400 };
6325
+ }
6326
+ try {
6327
+ const workbook = await getPublishedWorkbookById({
6328
+ type: "STATEMENT",
6329
+ id: statementId
6330
+ });
6331
+ const statement = await hydrateStatement(workbook);
6332
+ if (!statement || !statement.sheets) {
6333
+ throw { message: "Statement not found or has no sheets", status: 404 };
6334
+ }
6335
+ const statementSheet = statement.sheets.find(
6336
+ (sheet) => sheet.type === "STATEMENT_SHEET"
6337
+ );
6338
+ if (!statementSheet || !statementSheet.id) {
6339
+ throw {
6340
+ message: "Statement sheet not found in the statement",
6341
+ status: 404
6342
+ };
6343
+ }
6344
+ const statementViews = await getViewsBySheetId(statementSheet.id);
6345
+ if (_.isEmpty(statementViews)) {
6346
+ throw { message: "No views found for this statement", status: 404 };
6347
+ }
6348
+ let targetView;
6349
+ if (viewId) {
6350
+ targetView = statementViews.find((v) => v.id === viewId);
6351
+ if (!targetView) {
6352
+ throw { message: `View with ID ${viewId} not found`, status: 404 };
6353
+ }
6354
+ } else {
6355
+ const defaultView = _.find(
6356
+ statementViews,
6357
+ (v) => {
6358
+ var _a2;
6359
+ return Boolean((_a2 = v.customFields) == null ? void 0 : _a2.isDefault);
6360
+ }
6361
+ );
6362
+ if (defaultView) {
6363
+ targetView = defaultView;
6364
+ } else {
6365
+ targetView = statementViews[0];
6366
+ }
6367
+ }
6368
+ if (!targetView) {
6369
+ throw { message: "No valid view found for this statement", status: 404 };
6370
+ }
6371
+ const results = await getRunsByViewId(targetView.id);
6372
+ const sortedResults = _.orderBy(
6373
+ results,
6374
+ [(r) => r.lastModifiedDate || r.createdDate],
6375
+ ["desc"]
6376
+ );
6377
+ const runName = (options == null ? void 0 : options.name) ? options.name : getUniqueDuplicateName("Run", _.map(sortedResults, "name"), "", " ");
6378
+ let runInputs = void 0;
6379
+ let customFields = {};
6380
+ if ((options == null ? void 0 : options.columnFilters) && options.columnFilters.length > 0) {
6381
+ const { promotedFilters, commonFilters } = separateColumnFilters(
6382
+ options.columnFilters
6383
+ );
6384
+ runInputs = convertFiltersToRunInputs(
6385
+ promotedFilters,
6386
+ commonFilters,
6387
+ statementSheet
6388
+ );
6389
+ const fullFilters = await convertStatementFiltersToFullTypes(
6390
+ promotedFilters,
6391
+ commonFilters,
6392
+ statement
6393
+ );
6394
+ customFields = {
6395
+ promotedFilters: fullFilters.promotedFilters,
6396
+ commonFilters: fullFilters.commonFilters
6397
+ };
6398
+ }
6399
+ const finalRunId = runId ?? generatePushID();
6400
+ await apiClient.post(`/statement/run/create/${targetView.id}`, {
6401
+ runId: finalRunId,
6402
+ name: runName,
6403
+ runInputs,
6404
+ customFields
6405
+ });
6406
+ return { runId: finalRunId };
6407
+ } catch (error) {
6408
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while creating a new run";
6409
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6410
+ throw { message, status };
6411
+ }
6412
+ };
6413
+ const getRunResultById = async (runId) => {
6414
+ var _a, _b, _c;
6415
+ if (!runId) {
6416
+ throw { message: "Run ID is required", status: 400 };
6417
+ }
6418
+ try {
6419
+ const response = await apiClient.get(
6420
+ `/statement/run/get-result-by-run-id/${runId}`
6421
+ );
6422
+ if (!response.data) {
6423
+ throw { message: "Failed to fetch run result", status: 404 };
6424
+ }
6425
+ return response.data;
6426
+ } catch (error) {
6427
+ const message = error.message || ((_b = (_a = error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || "An unexpected error occurred while fetching run result";
6428
+ const status = error.status || ((_c = error.response) == null ? void 0 : _c.status) || 500;
6429
+ throw { message, status };
6430
+ }
6431
+ };
6432
+ const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
6433
+ __proto__: null,
6434
+ createNewRun,
6435
+ getData,
6436
+ getRunResultById,
6437
+ getRunsByViewId,
6438
+ getViewById,
6439
+ getViewsBySheetId
6440
+ }, Symbol.toStringTag, { value: "Module" }));
5685
6441
  const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5686
6442
  __proto__: null,
5687
6443
  apiClient,
5688
- chat: index$4,
5689
- dataset: index$3,
5690
- definition: index$8,
5691
- files: index$9,
5692
- inputTable: index$2,
5693
- metric: index$5,
5694
- user: index$b,
5695
- workbook: index$1,
5696
- workflow: index$a,
5697
- worksheet: index$7
6444
+ chat: index$5,
6445
+ dataset: index$4,
6446
+ definition: index$9,
6447
+ files: index$a,
6448
+ inputTable: index$3,
6449
+ metric: index$6,
6450
+ statement: index$1,
6451
+ user: index$c,
6452
+ workbook: index$2,
6453
+ workflow: index$b,
6454
+ worksheet: index$8
5698
6455
  }, Symbol.toStringTag, { value: "Module" }));
5699
6456
  const bluecopaTailwindConfig = {
5700
6457
  darkMode: "class",
@@ -5858,6 +6615,6 @@ export {
5858
6615
  getConfig as copaGetConfig,
5859
6616
  setConfig as copaSetConfig,
5860
6617
  bluecopaTailwindConfig as copaTailwindConfig,
5861
- index$6 as copaUtils
6618
+ index$7 as copaUtils
5862
6619
  };
5863
6620
  //# sourceMappingURL=index.es.js.map