busroot-sdk 0.0.8-dev.2775675320 → 0.0.8-dev.2785859549

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 (2) hide show
  1. package/build/index.js +1210 -91
  2. package/package.json +1 -1
package/build/index.js CHANGED
@@ -8939,6 +8939,1213 @@ var require_note3 = __commonJS({
8939
8939
  }
8940
8940
  });
8941
8941
 
8942
+ // ../../packages/common/build/configVars.js
8943
+ var require_configVars = __commonJS({
8944
+ "../../packages/common/build/configVars.js"(exports2) {
8945
+ "use strict";
8946
+ Object.defineProperty(exports2, "__esModule", { value: true });
8947
+ exports2.REDSHIFT_USERNAME = exports2.REDSHIFT_PORT = exports2.REDSHIFT_HOST_PUBLIC = exports2.REDSHIFT_HOST = exports2.SES_CONFIG = exports2.RATE_LIMIT_COUNT = exports2.RATE_LIMIT_WINDOW = exports2.MS_LOGIN_CALLBACK = exports2.MS_LOGIN_CLIENT_SECRET = exports2.MS_LOGIN_CLIENT_ID = exports2.ENABLE_DEMO_MODE = exports2.MQTT_PORT = exports2.MQTT_HOST = exports2.DEFAULT_ACCOUNT_ID = exports2.AUTH_BYPASS_DOMAIN = exports2.KNEX_SEEDS_DIR = exports2.QUEUE_LENGTH = exports2.LOGIN_COOKIE_SECRET = exports2.ENABLE_MS_TEAM_ALERT = exports2.ALERT_SLACK_TOKEN = exports2.ALERT_SLACK_CHANNEL = exports2.ENABLE_SLACK_ALERT = exports2.JWT_SECRET = exports2.AWS_BACKUP_S3_BUCKET = exports2.AWS_REGION = exports2.AWS_SECRET_ACCESS_KEY = exports2.AWS_ACCESS_KEY_ID = exports2.LOGIN_CALL_BACK_URL = exports2.TO_EMAIL_OVERRIDE = exports2.BCC_EMAIL = exports2.FROM_EMAIL = exports2.INFLUX_WRITE_PROTECTED = exports2.INFLUX_BUCKET = exports2.INFLUX_ORG = exports2.INFLUX_TOKEN = exports2.INFLUX_HOST_URL = exports2.PG_DB = exports2.PG_PASS = exports2.PG_USER = exports2.PG_HOST = exports2.BUSROOT_MQTT_FORWARDER_TOPIC = exports2.BUSROOT_MQTT_FORWARDER_PASS = exports2.BUSROOT_MQTT_FORWARDER_USER = exports2.BUSROOT_MQTT_FORWARDER_HOST = exports2.ADMIN_API_KEY = exports2.ADMIN_PASSWORD = exports2.ADMIN_USERNAME = exports2.DOMAIN_NAME = exports2.APP_ENV = exports2.NODE_ENV = void 0;
8948
+ exports2.NON_PRODUCTION_SIGNAL_TIMEOUT_MS = exports2.CACHE_BUILDER_ERROR_BACKOFF_MS = exports2.CACHE_BUILDER_ACCOUNT_BUDGET_MS = exports2.CACHE_BUILDER_IDLE_SLEEP_MS = exports2.CACHE_WARMING_LOOKBACK_DAYS = exports2.CACHE_WARMING_THROTTLE_MS = exports2.CACHE_WARMING_STAGGER_MAX_MS = exports2.CACHE_WARMING_CRON = exports2.CACHE_WARMING_ENABLED = exports2.STATION_FANOUT_PAUSE_MS = exports2.STATION_FANOUT_BATCH_SIZE = exports2.DAU_BUFFER_MAX_MESSAGE_BYTES = exports2.DAU_BUFFER_MAX_AGE_MS = exports2.DAU_BUFFER_SIZE = exports2.ENABLE_MQTT_EVENTS = exports2.ANTHROPIC_API_KEY = exports2.REDSHIFT_DB = exports2.REDSHIFT_PASSWORD = void 0;
8949
+ function parsePositiveIntEnv(value, fallback) {
8950
+ const parsed = Number(value);
8951
+ return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : fallback;
8952
+ }
8953
+ function parseNonNegativeIntEnv(value, fallback) {
8954
+ const parsed = Number(value);
8955
+ return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : fallback;
8956
+ }
8957
+ exports2.NODE_ENV = process.env.NODE_ENV;
8958
+ exports2.APP_ENV = process.env.APP_ENV || exports2.NODE_ENV;
8959
+ exports2.DOMAIN_NAME = process.env.DOMAIN_NAME || "undefined";
8960
+ exports2.ADMIN_USERNAME = process.env.ADMIN_USERNAME || "admin";
8961
+ exports2.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
8962
+ exports2.ADMIN_API_KEY = process.env.ADMIN_API_KEY;
8963
+ exports2.BUSROOT_MQTT_FORWARDER_HOST = process.env.BUSROOT_MQTT_FORWARDER_HOST;
8964
+ exports2.BUSROOT_MQTT_FORWARDER_USER = process.env.BUSROOT_MQTT_FORWARDER_USER;
8965
+ exports2.BUSROOT_MQTT_FORWARDER_PASS = process.env.BUSROOT_MQTT_FORWARDER_PASS;
8966
+ exports2.BUSROOT_MQTT_FORWARDER_TOPIC = process.env.BUSROOT_MQTT_FORWARDER_TOPIC || "#";
8967
+ exports2.PG_HOST = process.env.PG_HOST || exports2.DOMAIN_NAME;
8968
+ exports2.PG_USER = process.env.PG_USER || "postgres";
8969
+ exports2.PG_PASS = process.env.PG_PASS || "pHrJvh4ICt2Fh7Qu";
8970
+ exports2.PG_DB = process.env.PG_DB || "postgres";
8971
+ exports2.INFLUX_HOST_URL = process.env.INFLUX_HOST_URL || `http://${exports2.DOMAIN_NAME}:8086`;
8972
+ exports2.INFLUX_TOKEN = process.env.INFLUX_TOKEN;
8973
+ exports2.INFLUX_ORG = process.env.INFLUX_ORG || "";
8974
+ exports2.INFLUX_BUCKET = process.env.INFLUX_BUCKET || "default";
8975
+ exports2.INFLUX_WRITE_PROTECTED = process.env.INFLUX_WRITE_PROTECTED === "true";
8976
+ exports2.FROM_EMAIL = process.env.FROM_EMAIL || "busroot@output.industries";
8977
+ exports2.BCC_EMAIL = process.env.BCC_EMAIL;
8978
+ exports2.TO_EMAIL_OVERRIDE = process.env.TO_EMAIL_OVERRIDE;
8979
+ exports2.LOGIN_CALL_BACK_URL = process.env.LOGIN_CALL_BACK_URL || `https://${exports2.DOMAIN_NAME}`;
8980
+ exports2.AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID || "";
8981
+ exports2.AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY || "";
8982
+ exports2.AWS_REGION = process.env.AWS_REGION || "eu-west-2";
8983
+ exports2.AWS_BACKUP_S3_BUCKET = process.env.AWS_BACKUP_S3_BUCKET;
8984
+ exports2.JWT_SECRET = process.env.JWT_SECRET || "greentyre";
8985
+ exports2.ENABLE_SLACK_ALERT = (process.env.ENABLE_SLACK_ALERT || "").toLowerCase() === "true";
8986
+ exports2.ALERT_SLACK_CHANNEL = process.env.ALERT_SLACK_CHANNEL || "C03164SPJSH";
8987
+ exports2.ALERT_SLACK_TOKEN = process.env.ALERT_SLACK_TOKEN;
8988
+ exports2.ENABLE_MS_TEAM_ALERT = (process.env.ENABLE_MS_TEAM_ALERT || "").toLowerCase() === "true";
8989
+ exports2.LOGIN_COOKIE_SECRET = process.env.LOGIN_COOKIE_SECRET || "greentyre";
8990
+ exports2.QUEUE_LENGTH = parseInt(process.env["BUSROOT_QUEUE_LENGTH"] || "") || 200;
8991
+ exports2.KNEX_SEEDS_DIR = process.env.KNEX_SEEDS_DIR;
8992
+ exports2.AUTH_BYPASS_DOMAIN = process.env.AUTH_BYPASS_DOMAIN;
8993
+ exports2.DEFAULT_ACCOUNT_ID = process.env.DEFAULT_ACCOUNT_ID || "account_0000000000000000000";
8994
+ exports2.MQTT_HOST = process.env.MQTT_HOST || exports2.DOMAIN_NAME;
8995
+ exports2.MQTT_PORT = parseInt(process.env.MQTT_PORT || "") || 1883;
8996
+ exports2.ENABLE_DEMO_MODE = process.env.ENABLE_DEMO_MODE === "true";
8997
+ exports2.MS_LOGIN_CLIENT_ID = process.env.MS_LOGIN_CLIENT_ID;
8998
+ exports2.MS_LOGIN_CLIENT_SECRET = process.env.MS_LOGIN_CLIENT_SECRET;
8999
+ exports2.MS_LOGIN_CALLBACK = exports2.APP_ENV === "development" ? "http://localhost:3000" : `https://${exports2.DOMAIN_NAME}`;
9000
+ exports2.RATE_LIMIT_WINDOW = parseInt(process.env.RATE_LIMIT_WINDOW || "60000");
9001
+ exports2.RATE_LIMIT_COUNT = parseInt(process.env.RATE_LIMIT_COUNT || "10");
9002
+ exports2.SES_CONFIG = {
9003
+ accessKeyId: exports2.AWS_ACCESS_KEY_ID || "",
9004
+ secretAccessKey: exports2.AWS_SECRET_ACCESS_KEY || "",
9005
+ region: exports2.AWS_REGION,
9006
+ apiVersion: "2010-12-01"
9007
+ };
9008
+ exports2.REDSHIFT_HOST = process.env.REDSHIFT_HOST;
9009
+ exports2.REDSHIFT_HOST_PUBLIC = process.env.REDSHIFT_HOST_PUBLIC || "Not Set";
9010
+ exports2.REDSHIFT_PORT = Number(process.env.REDSHIFT_PORT || 5439);
9011
+ exports2.REDSHIFT_USERNAME = process.env.REDSHIFT_USERNAME || "admin";
9012
+ exports2.REDSHIFT_PASSWORD = process.env.REDSHIFT_PASSWORD;
9013
+ exports2.REDSHIFT_DB = process.env.REDSHIFT_DB || "dev";
9014
+ exports2.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
9015
+ exports2.ENABLE_MQTT_EVENTS = process.env.ENABLE_MQTT_EVENTS === "true" || false;
9016
+ exports2.DAU_BUFFER_SIZE = parseInt(process.env.DAU_BUFFER_SIZE || "") || 5;
9017
+ exports2.DAU_BUFFER_MAX_AGE_MS = parseInt(process.env.DAU_BUFFER_MAX_AGE_MS || "") || 30 * 24 * 60 * 60 * 1e3;
9018
+ exports2.DAU_BUFFER_MAX_MESSAGE_BYTES = parseInt(process.env.DAU_BUFFER_MAX_MESSAGE_BYTES || "") || 8192;
9019
+ exports2.STATION_FANOUT_BATCH_SIZE = parsePositiveIntEnv(process.env.STATION_WINDOW_BATCH_SIZE, 3);
9020
+ exports2.STATION_FANOUT_PAUSE_MS = parseNonNegativeIntEnv(process.env.STATION_WINDOW_BATCH_PAUSE_MS, 500);
9021
+ exports2.CACHE_WARMING_ENABLED = process.env.CACHE_WARMING_ENABLED === "true";
9022
+ exports2.CACHE_WARMING_CRON = process.env.CACHE_WARMING_CRON || "0 2 * * *";
9023
+ exports2.CACHE_WARMING_STAGGER_MAX_MS = parseNonNegativeIntEnv(process.env.CACHE_WARMING_STAGGER_MAX_MS, 30 * 60 * 1e3);
9024
+ exports2.CACHE_WARMING_THROTTLE_MS = parseNonNegativeIntEnv(process.env.CACHE_WARMING_THROTTLE_MS, 250);
9025
+ exports2.CACHE_WARMING_LOOKBACK_DAYS = parsePositiveIntEnv(process.env.CACHE_WARMING_LOOKBACK_DAYS, 730);
9026
+ exports2.CACHE_BUILDER_IDLE_SLEEP_MS = parseNonNegativeIntEnv(process.env.CACHE_BUILDER_IDLE_SLEEP_MS, 2e3);
9027
+ exports2.CACHE_BUILDER_ACCOUNT_BUDGET_MS = parsePositiveIntEnv(process.env.CACHE_BUILDER_ACCOUNT_BUDGET_MS, 6e4);
9028
+ exports2.CACHE_BUILDER_ERROR_BACKOFF_MS = parseNonNegativeIntEnv(process.env.CACHE_BUILDER_ERROR_BACKOFF_MS, 5e3);
9029
+ exports2.NON_PRODUCTION_SIGNAL_TIMEOUT_MS = parseNonNegativeIntEnv(process.env.NON_PRODUCTION_SIGNAL_TIMEOUT_MS, 0);
9030
+ }
9031
+ });
9032
+
9033
+ // ../../packages/common/build/utils/oee.js
9034
+ var require_oee2 = __commonJS({
9035
+ "../../packages/common/build/utils/oee.js"(exports2) {
9036
+ "use strict";
9037
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
9038
+ if (k2 === void 0) k2 = k;
9039
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9040
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9041
+ desc = { enumerable: true, get: function() {
9042
+ return m[k];
9043
+ } };
9044
+ }
9045
+ Object.defineProperty(o, k2, desc);
9046
+ }) : (function(o, m, k, k2) {
9047
+ if (k2 === void 0) k2 = k;
9048
+ o[k2] = m[k];
9049
+ }));
9050
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
9051
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
9052
+ }) : function(o, v) {
9053
+ o["default"] = v;
9054
+ });
9055
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
9056
+ var ownKeys = function(o) {
9057
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
9058
+ var ar = [];
9059
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
9060
+ return ar;
9061
+ };
9062
+ return ownKeys(o);
9063
+ };
9064
+ return function(mod) {
9065
+ if (mod && mod.__esModule) return mod;
9066
+ var result = {};
9067
+ if (mod != null) {
9068
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
9069
+ }
9070
+ __setModuleDefault(result, mod);
9071
+ return result;
9072
+ };
9073
+ })();
9074
+ Object.defineProperty(exports2, "__esModule", { value: true });
9075
+ exports2.UNKNOWN_DATA = void 0;
9076
+ var utils = __importStar(require_utils());
9077
+ var station_windows_1 = require_station_windows();
9078
+ exports2.UNKNOWN_DATA = {
9079
+ key: "unknown",
9080
+ value: "Unknown"
9081
+ };
9082
+ function calculateOeeForStationWindows(stationWindows, reasonCauseService, nonProductionCauseService) {
9083
+ if (stationWindows.length == 0) {
9084
+ return {
9085
+ availabilityMs: 0,
9086
+ availabilityLossMs: 0,
9087
+ availabilityPerc: 0,
9088
+ goodQualityCount: 0,
9089
+ goodQualityLossCount: 0,
9090
+ goodQualityPerc: 0,
9091
+ oee: 0,
9092
+ performanceMs: 0,
9093
+ performanceLossMs: 0,
9094
+ performancePerc: 0,
9095
+ productionScheduleMs: 0,
9096
+ productionScheduleLossMs: 0,
9097
+ productionSchedulePerc: 0,
9098
+ scheduleMs: 0,
9099
+ scheduleLossMs: 0,
9100
+ schedulePerc: 0,
9101
+ scheduledNonProduction: [],
9102
+ stops: []
9103
+ };
9104
+ }
9105
+ const stationWindow = (0, station_windows_1.combineStationWindows)(stationWindows);
9106
+ const scheduleMs = utils.add(stationWindow.scheduledProductionMs, stationWindow.scheduledNonProductionMs);
9107
+ const scheduleLossMs = utils.subtract(stationWindow.shiftMs, scheduleMs);
9108
+ const scheduleRatio = utils.ratio(scheduleMs, scheduleLossMs);
9109
+ const productionScheduleMs = utils.add(stationWindow.scheduledProductionMs);
9110
+ const productionScheduleLossMs = utils.subtract(scheduleMs, productionScheduleMs);
9111
+ const productionScheduleRatio = utils.ratio(productionScheduleMs, productionScheduleLossMs);
9112
+ const availabilityLossMs = utils.add(stationWindow.downtimeMs);
9113
+ const availabilityMs = utils.subtract(productionScheduleMs - availabilityLossMs);
9114
+ const availabilityRatio = utils.ratio(availabilityMs, availabilityLossMs);
9115
+ const performanceMs = utils.add(stationWindow.productionMs);
9116
+ const performanceLossMs = Math.max(0, utils.subtract(availabilityMs - performanceMs));
9117
+ const performanceRatio = utils.ratio(performanceMs, performanceLossMs);
9118
+ const goodQualityCount = utils.add(stationWindow.productionGoodCount);
9119
+ const goodQualityLossCount = utils.add(stationWindow.productionBadCount);
9120
+ const goodQualityRatio = utils.ratio(goodQualityCount, goodQualityLossCount);
9121
+ const nonProductionReasonCodes = [...stationWindow.nonProductionReasonCodes || [], exports2.UNKNOWN_DATA.key];
9122
+ const scheduledNonProduction = nonProductionReasonCodes.flatMap((s) => {
9123
+ const results = [];
9124
+ for (let i = 0; i < stationWindows.length; i++) {
9125
+ const window2 = stationWindows[i];
9126
+ if (!window2.scheduledNonProductionMs) {
9127
+ continue;
9128
+ }
9129
+ let duration = 0;
9130
+ let j = i;
9131
+ do {
9132
+ const nextWindow = stationWindows[j];
9133
+ if (!nextWindow.scheduledNonProductionMs) {
9134
+ i = j;
9135
+ break;
9136
+ }
9137
+ let nextNonProductionReasonCode = nextWindow.nonProductionReasonCodes?.find((code) => code === s) || Object.keys(nextWindow.nonProductionReasonCodesDetail || {}).find((code) => code === s);
9138
+ if (!nextNonProductionReasonCode && !nextWindow.nonProductionReasonCodes?.length) {
9139
+ nextNonProductionReasonCode = exports2.UNKNOWN_DATA.key;
9140
+ }
9141
+ if (nextNonProductionReasonCode !== s) {
9142
+ i = j;
9143
+ break;
9144
+ }
9145
+ duration += nextWindow.nonProductionReasonCodesDetail ? nextWindow.nonProductionReasonCodesDetail[s]?.scheduledNonProductionMs ?? 0 : nextWindow.scheduledNonProductionMs ?? 0;
9146
+ j++;
9147
+ i = j;
9148
+ } while (j < stationWindows.length);
9149
+ if (duration) {
9150
+ const breadcrumb = nonProductionCauseService != null ? nonProductionCauseService.getCauseBreadcrumb(s) : [];
9151
+ const description = nonProductionCauseService != null ? breadcrumb.map((c) => c.description).join(" | ") || exports2.UNKNOWN_DATA.value : "";
9152
+ results.push({
9153
+ code: s,
9154
+ description,
9155
+ reasonBreadcrumb: breadcrumb.length > 0 ? breadcrumb : [{ code: s, description: description || exports2.UNKNOWN_DATA.value }],
9156
+ duration,
9157
+ cost: 0,
9158
+ percent: 0,
9159
+ energy: 0,
9160
+ energyCost: 0,
9161
+ productionQuantity: 0
9162
+ });
9163
+ }
9164
+ }
9165
+ return results;
9166
+ });
9167
+ const issueReasonCodes = [...stationWindow.downtimeReasonCodes || [], exports2.UNKNOWN_DATA.key];
9168
+ const stops = issueReasonCodes.flatMap((s) => {
9169
+ const results = [];
9170
+ for (let i = 0; i < stationWindows.length; i++) {
9171
+ const window2 = stationWindows[i];
9172
+ if (!window2.downtimeMs) {
9173
+ continue;
9174
+ }
9175
+ let duration = 0;
9176
+ let issueDowntimeCost = 0;
9177
+ let energyDowntimeCost = 0;
9178
+ let energyDowntime = 0;
9179
+ let productionQuantity = 0;
9180
+ let j = i;
9181
+ do {
9182
+ const nextWindow = stationWindows[j];
9183
+ if (!nextWindow.downtimeMs) {
9184
+ i = j;
9185
+ break;
9186
+ }
9187
+ let nextIssueReasonCode = nextWindow.downtimeReasonCodes?.find((code) => code === s) || Object.keys(nextWindow.downtimeReasonCodesDetail || {}).find((code) => code === s);
9188
+ if (!nextIssueReasonCode && !nextWindow.downtimeReasonCodes?.length) {
9189
+ nextIssueReasonCode = exports2.UNKNOWN_DATA.key;
9190
+ }
9191
+ if (nextIssueReasonCode !== s) {
9192
+ i = j;
9193
+ break;
9194
+ }
9195
+ const detail = nextWindow.downtimeReasonCodesDetail;
9196
+ issueDowntimeCost += detail ? detail[s]?.lostProductionCostDowntime ?? 0 : nextWindow.lostProductionCostDowntime ?? 0;
9197
+ energyDowntimeCost += detail ? detail[s]?.electricalCost ?? 0 : nextWindow.electricalCost ?? 0;
9198
+ energyDowntime += detail ? detail[s]?.electricalKwh ?? 0 : nextWindow.electricalKwh ?? 0;
9199
+ duration += detail ? detail[s]?.downtimeMs ?? 0 : nextWindow.downtimeMs ?? 0;
9200
+ productionQuantity += detail ? detail[s]?.productionIdealCount ?? 0 : nextWindow.productionIdealCount ?? 0;
9201
+ j++;
9202
+ i = j;
9203
+ } while (j < stationWindows.length);
9204
+ if (duration) {
9205
+ const breadcrumb = reasonCauseService != null ? reasonCauseService.getCauseBreadcrumb(s) : [];
9206
+ const description = reasonCauseService != null ? breadcrumb.map((c) => c.description).join(" | ") || exports2.UNKNOWN_DATA.value : "";
9207
+ results.push({
9208
+ code: s,
9209
+ description,
9210
+ reasonBreadcrumb: breadcrumb.length > 0 ? breadcrumb : [{ code: s, description: description || exports2.UNKNOWN_DATA.value }],
9211
+ duration,
9212
+ cost: issueDowntimeCost,
9213
+ energy: energyDowntime,
9214
+ energyCost: energyDowntimeCost,
9215
+ percent: 0,
9216
+ productionQuantity
9217
+ });
9218
+ }
9219
+ }
9220
+ return results;
9221
+ }).sort((a, b) => b.duration - a.duration);
9222
+ const oee = utils.roundTo(availabilityRatio * performanceRatio * goodQualityRatio, 3);
9223
+ return {
9224
+ scheduleMs,
9225
+ scheduleLossMs,
9226
+ schedulePerc: scheduleRatio,
9227
+ productionScheduleMs,
9228
+ productionScheduleLossMs,
9229
+ productionSchedulePerc: productionScheduleRatio,
9230
+ availabilityMs,
9231
+ availabilityLossMs,
9232
+ availabilityPerc: availabilityRatio,
9233
+ performanceMs,
9234
+ performanceLossMs,
9235
+ performancePerc: performanceRatio,
9236
+ goodQualityCount,
9237
+ goodQualityLossCount,
9238
+ goodQualityPerc: goodQualityRatio,
9239
+ stops: getOeeStopsPercentages(stops),
9240
+ scheduledNonProduction,
9241
+ oee
9242
+ };
9243
+ }
9244
+ function combineOee(stations) {
9245
+ const combine = {
9246
+ scheduleMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.scheduleMs, 0), 2),
9247
+ scheduleLossMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.scheduleLossMs, 0), 2),
9248
+ productionScheduleMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.productionScheduleMs, 0), 2),
9249
+ productionScheduleLossMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.productionScheduleLossMs, 0), 2),
9250
+ availabilityMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.availabilityMs, 0), 2),
9251
+ availabilityLossMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.availabilityLossMs, 0), 2),
9252
+ performanceMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.performanceMs, 0), 2),
9253
+ performanceLossMs: utils.roundTo(stations.reduce((a, station) => a += station.oee.performanceLossMs, 0), 2),
9254
+ goodQualityCount: utils.roundTo(stations.reduce((a, station) => a += station.oee.goodQualityCount, 0), 2),
9255
+ goodQualityLossCount: utils.roundTo(stations.reduce((a, station) => a += station.oee.goodQualityLossCount, 0), 2),
9256
+ scheduledNonProduction: combineOeeStops(stations.flatMap((station) => station.oee.scheduledNonProduction)),
9257
+ stops: combineOeeStops(stations.flatMap((station) => station.oee.stops))
9258
+ };
9259
+ const withPerc = {
9260
+ ...combine,
9261
+ schedulePerc: combine.scheduleMs / (combine.scheduleMs + combine.scheduleLossMs) || 0,
9262
+ productionSchedulePerc: combine.productionScheduleMs / (combine.productionScheduleMs + combine.productionScheduleLossMs) || 1,
9263
+ availabilityPerc: combine.availabilityMs / (combine.availabilityMs + combine.availabilityLossMs) || 1,
9264
+ performancePerc: combine.performanceMs / (combine.performanceMs + combine.performanceLossMs) || 1,
9265
+ goodQualityPerc: combine.goodQualityCount / (combine.goodQualityCount + combine.goodQualityLossCount) || 1
9266
+ };
9267
+ return { ...withPerc, oee: utils.roundTo(withPerc.availabilityPerc * withPerc.performancePerc * withPerc.goodQualityPerc, 2) };
9268
+ }
9269
+ function combineOeeStops(stops) {
9270
+ const combinedStops = [
9271
+ ...stops.reduce((a, stop) => {
9272
+ if (!stop.code) {
9273
+ return a;
9274
+ }
9275
+ const downtime = a.get(stop.code) || {
9276
+ code: stop.code,
9277
+ description: stop.description,
9278
+ reasonBreadcrumb: stop.reasonBreadcrumb,
9279
+ duration: 0,
9280
+ cost: 0,
9281
+ percent: 0,
9282
+ energy: 0,
9283
+ energyCost: 0,
9284
+ productionQuantity: 0
9285
+ };
9286
+ downtime.duration += stop.duration || 0;
9287
+ downtime.cost += stop.cost || 0;
9288
+ downtime.energy += stop.energy || 0;
9289
+ downtime.energyCost += stop.energyCost || 0;
9290
+ downtime.productionQuantity += stop.productionQuantity || 0;
9291
+ a.set(stop.code, downtime);
9292
+ return a;
9293
+ }, /* @__PURE__ */ new Map()).values()
9294
+ ];
9295
+ const withPercent = getOeeStopsPercentages(combinedStops);
9296
+ return withPercent;
9297
+ }
9298
+ function getOeeStopsPercentages(stops) {
9299
+ const totalDuration = stops.reduce((a, b) => a + b.duration, 0);
9300
+ return stops.map((stop) => {
9301
+ return { ...stop, percent: stop.duration / totalDuration };
9302
+ }).sort((a, b) => b.duration - a.duration);
9303
+ }
9304
+ var OeeHelper = {
9305
+ combineOee,
9306
+ combineOeeStops,
9307
+ calculateOeeForStationWindows
9308
+ };
9309
+ exports2.default = OeeHelper;
9310
+ }
9311
+ });
9312
+
9313
+ // ../../packages/common/build/utils/station-windows.js
9314
+ var require_station_windows = __commonJS({
9315
+ "../../packages/common/build/utils/station-windows.js"(exports2) {
9316
+ "use strict";
9317
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
9318
+ if (k2 === void 0) k2 = k;
9319
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9320
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9321
+ desc = { enumerable: true, get: function() {
9322
+ return m[k];
9323
+ } };
9324
+ }
9325
+ Object.defineProperty(o, k2, desc);
9326
+ }) : (function(o, m, k, k2) {
9327
+ if (k2 === void 0) k2 = k;
9328
+ o[k2] = m[k];
9329
+ }));
9330
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
9331
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
9332
+ }) : function(o, v) {
9333
+ o["default"] = v;
9334
+ });
9335
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
9336
+ var ownKeys = function(o) {
9337
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
9338
+ var ar = [];
9339
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
9340
+ return ar;
9341
+ };
9342
+ return ownKeys(o);
9343
+ };
9344
+ return function(mod) {
9345
+ if (mod && mod.__esModule) return mod;
9346
+ var result = {};
9347
+ if (mod != null) {
9348
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
9349
+ }
9350
+ __setModuleDefault(result, mod);
9351
+ return result;
9352
+ };
9353
+ })();
9354
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
9355
+ return mod && mod.__esModule ? mod : { "default": mod };
9356
+ };
9357
+ Object.defineProperty(exports2, "__esModule", { value: true });
9358
+ exports2.AggregatedProduction = void 0;
9359
+ exports2.generateMockStationWindows = generateMockStationWindows;
9360
+ exports2.combineStationWindows = combineStationWindows;
9361
+ exports2.combineStationWindowsByTime = combineStationWindowsByTime;
9362
+ exports2.aggregateStationWindows = aggregateStationWindows;
9363
+ exports2.aggregateStationWindowsBySkuCode = aggregateStationWindowsBySkuCode;
9364
+ exports2.extractDowntimesFromStationWindows = extractDowntimesFromStationWindows;
9365
+ exports2.getReliabilityData = getReliabilityData;
9366
+ exports2.calculateReliabilityMetrics = calculateReliabilityMetrics;
9367
+ exports2.downtimesToStationWindows = downtimesToStationWindows;
9368
+ exports2.filterStationWindowsBySkuCode = filterStationWindowsBySkuCode;
9369
+ exports2.filterStationWindowsByShiftNames = filterStationWindowsByShiftNames;
9370
+ exports2.getCycleTimeFromSku = getCycleTimeFromSku;
9371
+ exports2.getPerformanceValueFromSkuCycleTime = getPerformanceValueFromSkuCycleTime;
9372
+ exports2.getPerformanceModeFromSku = getPerformanceModeFromSku;
9373
+ exports2.aggregateProductionFromStationWindows = aggregateProductionFromStationWindows;
9374
+ exports2.aggregateProductionBySkuFromStationWindows = aggregateProductionBySkuFromStationWindows;
9375
+ exports2.isSignalNonProductionWindow = isSignalNonProductionWindow;
9376
+ exports2.signalNonProductionReasonCode = signalNonProductionReasonCode;
9377
+ var moment_timezone_1 = __importDefault(require("moment-timezone"));
9378
+ var enums_1 = require_enums();
9379
+ var time_1 = require_time();
9380
+ var shiftUtils = __importStar(require_shifts());
9381
+ var schedules_1 = require_schedules();
9382
+ var station_window_1 = require_station_window2();
9383
+ var times_1 = require_times();
9384
+ var utils = __importStar(require_utils());
9385
+ var _1 = require_utils();
9386
+ var zod_1 = __importDefault(require("zod"));
9387
+ var configVars_1 = require_configVars();
9388
+ var oee_1 = require_oee2();
9389
+ var WINDOW_DURATION = 6e4;
9390
+ var MAX_WINDOWS_PER_DOWNTIME = 1440;
9391
+ function generateMockStationWindows(offset, extraFields) {
9392
+ const startMoment = (0, moment_timezone_1.default)("2020-01-01T00:00:00.000Z");
9393
+ return {
9394
+ accountId: configVars_1.DEFAULT_ACCOUNT_ID,
9395
+ stationCode: "station1",
9396
+ stationName: "Station 1",
9397
+ totalMs: 6e4,
9398
+ shiftMs: 6e4,
9399
+ isAlive: true,
9400
+ windowStartAt: startMoment.clone().add(offset, "minute").toISOString(),
9401
+ windowStartAtTimestamp: startMoment.clone().add(offset, "minute").valueOf(),
9402
+ windowEndAt: startMoment.clone().add(offset + 1, "minute").toISOString(),
9403
+ windowEndAtTimestamp: startMoment.clone().add(offset + 1, "minute").valueOf(),
9404
+ ...extraFields
9405
+ };
9406
+ }
9407
+ function combineStationWindows(windows, inShiftAverages = false, skipConsecutiveCheck = false) {
9408
+ if (windows.length === 0) {
9409
+ throw new Error("Must be at least 1 window.");
9410
+ }
9411
+ const windowDuration = windows[0].totalMs;
9412
+ const window2 = windows.reduce((a, b, i) => {
9413
+ const isFirstWindow = i === 0;
9414
+ const isConsecutive = a.windowEndAt === b.windowStartAt;
9415
+ const isSameDuration = b.totalMs === windowDuration;
9416
+ if (!isFirstWindow && !skipConsecutiveCheck) {
9417
+ if (!isConsecutive) {
9418
+ throw new Error("Windows are not consecutive.");
9419
+ }
9420
+ if (!isSameDuration) {
9421
+ throw new Error("Windows are not the same duration. " + windowDuration + " " + b.totalMs);
9422
+ }
9423
+ }
9424
+ a.stationCode = b.stationCode;
9425
+ a.stationName = b.stationName;
9426
+ a.windowEndAt = b.windowEndAt;
9427
+ a.windowEndAtTimestamp = b.windowEndAtTimestamp;
9428
+ a.downtimeSince = b.downtimeSince;
9429
+ a.totalMs = add(a.totalMs, b.totalMs) || 0;
9430
+ a.shiftMs = add(a.shiftMs, b.shiftMs);
9431
+ a.scheduledProductionMs = add(a.scheduledProductionMs, b.scheduledProductionMs);
9432
+ a.scheduledNonProductionMs = add(a.scheduledNonProductionMs, b.scheduledNonProductionMs);
9433
+ a.productiveMs = add(a.productiveMs, b.productiveMs);
9434
+ a.downtimeMs = add(a.downtimeMs, b.downtimeMs);
9435
+ a.productionGoodCount = add(a.productionGoodCount, b.productionGoodCount);
9436
+ a.productionBadCount = add(a.productionBadCount, b.productionBadCount);
9437
+ a.productionGoodValue = add(a.productionGoodValue, b.productionGoodValue);
9438
+ a.productionBadValue = add(a.productionBadValue, b.productionBadValue);
9439
+ a.productionTotalCount = add(a.productionTotalCount, b.productionTotalCount);
9440
+ a.productionMs = add(a.productionMs, b.productionMs);
9441
+ a.speed = add(a.speed, b.speed);
9442
+ a.electricalKwh = add(a.electricalKwh, b.electricalKwh);
9443
+ a.electricalCost = add(a.electricalCost, b.electricalCost);
9444
+ a.lostProductionCostNonProduction = add(a.lostProductionCostNonProduction, b.lostProductionCostNonProduction);
9445
+ a.lostProductionCostDowntime = add(a.lostProductionCostDowntime, b.lostProductionCostDowntime);
9446
+ a.lostProductionCostSpeed = add(a.lostProductionCostSpeed, b.lostProductionCostSpeed);
9447
+ a.lostProductionCostQuality = add(a.lostProductionCostQuality, b.lostProductionCostQuality);
9448
+ a.lostProductionCostTotal = add(a.lostProductionCostTotal, b.lostProductionCostTotal);
9449
+ a.productionIdealCount = add(a.productionIdealCount, b.productionIdealCount);
9450
+ a.productionTargetCount = add(a.productionTargetCount, b.productionTargetCount);
9451
+ if (b.shiftNames) {
9452
+ a.shiftNames?.push(...b.shiftNames);
9453
+ }
9454
+ if (b.skuCodes) {
9455
+ a.skuCodes?.push(...b.skuCodes);
9456
+ }
9457
+ if (b.skuNames) {
9458
+ a.skuNames?.push(...b.skuNames);
9459
+ }
9460
+ if (b.scheduleIds) {
9461
+ a.scheduleIds?.push(...b.scheduleIds || []);
9462
+ }
9463
+ if (b.workOrderReferences) {
9464
+ a.workOrderReferences?.push(...b.workOrderReferences || []);
9465
+ }
9466
+ if (b.errorCodes) {
9467
+ a.errorCodes?.push(...b.errorCodes);
9468
+ }
9469
+ if (b.downtimeIds) {
9470
+ a.downtimeIds?.push(...b.downtimeIds);
9471
+ }
9472
+ if (b.downtimeReasonCodes) {
9473
+ a.downtimeReasonCodes?.push(...b.downtimeReasonCodes);
9474
+ }
9475
+ if (b.downtimeMs) {
9476
+ const downtimeReasonCodesDetail = a.downtimeReasonCodesDetail || {};
9477
+ const bDetail = b.downtimeReasonCodesDetail || {
9478
+ [b.downtimeReasonCodes?.[0] || oee_1.UNKNOWN_DATA.key]: {
9479
+ productionIdealCount: b.productionIdealCount || 0,
9480
+ downtimeMs: b.downtimeMs || 0,
9481
+ lostProductionCostDowntime: b.lostProductionCostDowntime || 0,
9482
+ electricalCost: b.electricalCost || 0,
9483
+ electricalKwh: b.electricalKwh || 0
9484
+ }
9485
+ };
9486
+ for (const [reasonCode, detail] of Object.entries(bDetail)) {
9487
+ downtimeReasonCodesDetail[reasonCode] = {
9488
+ productionIdealCount: (downtimeReasonCodesDetail[reasonCode]?.productionIdealCount || 0) + (detail.productionIdealCount || 0),
9489
+ downtimeMs: (downtimeReasonCodesDetail[reasonCode]?.downtimeMs || 0) + (detail.downtimeMs || 0),
9490
+ lostProductionCostDowntime: (downtimeReasonCodesDetail[reasonCode]?.lostProductionCostDowntime || 0) + (detail.lostProductionCostDowntime || 0),
9491
+ electricalCost: (downtimeReasonCodesDetail[reasonCode]?.electricalCost || 0) + (detail.electricalCost || 0),
9492
+ electricalKwh: (downtimeReasonCodesDetail[reasonCode]?.electricalKwh || 0) + (detail.electricalKwh || 0)
9493
+ };
9494
+ }
9495
+ a.downtimeReasonCodesDetail = downtimeReasonCodesDetail;
9496
+ }
9497
+ if (b.nonProductionReasonCodes) {
9498
+ a.nonProductionReasonCodes?.push(...b.nonProductionReasonCodes);
9499
+ }
9500
+ if (b.scheduledNonProductionMs) {
9501
+ const nonProductionReasonCodesDetail = a.nonProductionReasonCodesDetail || {};
9502
+ const bNonProductionDetail = b.nonProductionReasonCodesDetail || {
9503
+ [b.nonProductionReasonCodes?.[0] || oee_1.UNKNOWN_DATA.key]: {
9504
+ scheduledNonProductionMs: b.scheduledNonProductionMs || 0
9505
+ }
9506
+ };
9507
+ for (const [reasonCode, detail] of Object.entries(bNonProductionDetail)) {
9508
+ nonProductionReasonCodesDetail[reasonCode] = {
9509
+ scheduledNonProductionMs: (nonProductionReasonCodesDetail[reasonCode]?.scheduledNonProductionMs || 0) + (detail.scheduledNonProductionMs || 0)
9510
+ };
9511
+ }
9512
+ a.nonProductionReasonCodesDetail = nonProductionReasonCodesDetail;
9513
+ }
9514
+ if (b.operatorInitials) {
9515
+ a.operatorInitials = b.operatorInitials;
9516
+ }
9517
+ a.performanceModeFrom = b.performanceModeFrom;
9518
+ a.performanceModeType = b.performanceModeType;
9519
+ a.isAlive = b.isAlive ? true : a.isAlive;
9520
+ a.isFuture = !b.isFuture ? false : a.isFuture;
9521
+ if (!inShiftAverages || b.shiftMs != void 0 && b.shiftMs > 0) {
9522
+ a.rssiAvg = add(a.rssiAvg, b.rssiAvg);
9523
+ a.electricalVoltsAvg = add(a.electricalVoltsAvg, b.electricalVoltsAvg);
9524
+ a.electricalAmpsAvg = add(a.electricalAmpsAvg, b.electricalAmpsAvg);
9525
+ a.electricalHzAvg = add(a.electricalHzAvg, b.electricalHzAvg);
9526
+ a.electricalPfAvg = add(a.electricalPfAvg, b.electricalPfAvg);
9527
+ a.electricalKwAvg = add(a.electricalKwAvg, b.electricalKwAvg);
9528
+ a.inShiftCount++;
9529
+ }
9530
+ if ((a.scheduledProductionMs || 0) > 0) {
9531
+ a.inProductionCount++;
9532
+ }
9533
+ a.count++;
9534
+ return a;
9535
+ }, {
9536
+ ...windows[0],
9537
+ totalMs: 0,
9538
+ shiftMs: void 0,
9539
+ shiftNames: [],
9540
+ scheduledProductionMs: void 0,
9541
+ scheduledNonProductionMs: void 0,
9542
+ productiveMs: void 0,
9543
+ downtimeMs: void 0,
9544
+ downtimeSince: void 0,
9545
+ rssiAvg: void 0,
9546
+ productionGoodCount: void 0,
9547
+ productionBadCount: void 0,
9548
+ productionGoodValue: void 0,
9549
+ productionBadValue: void 0,
9550
+ productionIdealCount: void 0,
9551
+ productionTargetCount: void 0,
9552
+ productionTotalCount: void 0,
9553
+ productionRatePerHour: void 0,
9554
+ productionRatePerHourIdeal: void 0,
9555
+ productionMs: void 0,
9556
+ speed: void 0,
9557
+ electricalVoltsAvg: void 0,
9558
+ electricalAmpsAvg: void 0,
9559
+ electricalHzAvg: void 0,
9560
+ electricalPfAvg: void 0,
9561
+ electricalKwAvg: void 0,
9562
+ electricalKwh: void 0,
9563
+ electricalCost: 0,
9564
+ skuCodes: [],
9565
+ skuNames: [],
9566
+ scheduleIds: [],
9567
+ workOrderReferences: [],
9568
+ errorCodes: [],
9569
+ downtimeIds: [],
9570
+ downtimeReasonCodes: [],
9571
+ nonProductionReasonCodes: [],
9572
+ operatorInitials: void 0,
9573
+ isAlive: false,
9574
+ lostProductionCostNonProduction: 0,
9575
+ lostProductionCostDowntime: 0,
9576
+ lostProductionCostSpeed: 0,
9577
+ lostProductionCostQuality: 0,
9578
+ lostProductionCostTotal: 0,
9579
+ count: 0,
9580
+ inShiftCount: 0,
9581
+ inProductionCount: 0,
9582
+ performanceModeFrom: "none",
9583
+ performanceModeType: "none",
9584
+ downtimeReasonCodesDetail: void 0,
9585
+ nonProductionReasonCodesDetail: void 0
9586
+ });
9587
+ if (window2.isFuture) {
9588
+ const result = {
9589
+ stationCode: window2.stationCode,
9590
+ stationName: window2.stationName,
9591
+ windowStartAt: window2.windowStartAt,
9592
+ windowStartAtTimestamp: window2.windowStartAtTimestamp,
9593
+ windowEndAt: window2.windowEndAt,
9594
+ windowEndAtTimestamp: window2.windowEndAtTimestamp,
9595
+ totalMs: window2.totalMs,
9596
+ shiftMs: window2.shiftMs,
9597
+ isAlive: window2.isAlive,
9598
+ isFuture: window2.isFuture
9599
+ };
9600
+ return result;
9601
+ } else {
9602
+ const result = {
9603
+ stationCode: window2.stationCode,
9604
+ stationName: window2.stationName,
9605
+ windowStartAt: window2.windowStartAt,
9606
+ windowStartAtTimestamp: window2.windowStartAtTimestamp,
9607
+ windowEndAt: window2.windowEndAt,
9608
+ windowEndAtTimestamp: window2.windowEndAtTimestamp,
9609
+ totalMs: window2.totalMs,
9610
+ shiftMs: window2.shiftMs,
9611
+ shiftNames: Array.from(/* @__PURE__ */ new Set([...window2.shiftNames || []])),
9612
+ scheduledProductionMs: window2.scheduledProductionMs,
9613
+ scheduledNonProductionMs: window2.scheduledNonProductionMs,
9614
+ productiveMs: window2.productiveMs,
9615
+ downtimeMs: window2.downtimeMs,
9616
+ downtimeSince: window2.downtimeSince,
9617
+ productionGoodCount: (0, _1.roundTo)(window2.productionGoodCount, 2),
9618
+ productionBadCount: (0, _1.roundTo)(window2.productionBadCount, 2),
9619
+ productionGoodValue: (0, _1.roundTo)(window2.productionGoodValue, 2),
9620
+ productionBadValue: (0, _1.roundTo)(window2.productionBadValue, 2),
9621
+ productionTotalCount: (0, _1.roundTo)(window2.productionTotalCount, 2),
9622
+ productionRatePerHour: (divide(window2.productionTotalCount, window2.inProductionCount, 2) || 0) * 60,
9623
+ productionRatePerHourIdeal: (divide(window2.productionIdealCount, window2.inProductionCount, 2) || 0) * 60,
9624
+ productionMs: (0, _1.roundTo)(window2.productionMs, 2),
9625
+ isAlive: window2.isAlive,
9626
+ isFuture: false,
9627
+ speed: divide(window2.speed, window2.count, 4),
9628
+ electricalKwh: window2.electricalKwh,
9629
+ electricalCost: (0, _1.roundTo)(window2.electricalCost, 2),
9630
+ skuCodes: Array.from(/* @__PURE__ */ new Set([...window2.skuCodes || []])),
9631
+ skuNames: Array.from(/* @__PURE__ */ new Set([...window2.skuNames || []])),
9632
+ scheduleIds: Array.from(/* @__PURE__ */ new Set([...window2.scheduleIds || []])),
9633
+ workOrderReferences: Array.from(/* @__PURE__ */ new Set([...window2.workOrderReferences || []])),
9634
+ errorCodes: Array.from(/* @__PURE__ */ new Set([...window2.errorCodes || []])),
9635
+ downtimeIds: Array.from(/* @__PURE__ */ new Set([...window2.downtimeIds || []])),
9636
+ downtimeReasonCodes: Array.from(/* @__PURE__ */ new Set([...window2.downtimeReasonCodes || []])),
9637
+ downtimeReasonCodesDetail: window2.downtimeReasonCodesDetail,
9638
+ nonProductionReasonCodes: Array.from(/* @__PURE__ */ new Set([...window2.nonProductionReasonCodes || []])),
9639
+ nonProductionReasonCodesDetail: window2.nonProductionReasonCodesDetail,
9640
+ lostProductionCostNonProduction: window2.lostProductionCostNonProduction,
9641
+ lostProductionCostDowntime: window2.lostProductionCostDowntime,
9642
+ lostProductionCostSpeed: window2.lostProductionCostSpeed,
9643
+ lostProductionCostQuality: window2.lostProductionCostQuality,
9644
+ lostProductionCostTotal: window2.lostProductionCostTotal,
9645
+ productionIdealCount: (0, _1.roundTo)(window2.productionIdealCount, 2),
9646
+ productionTargetCount: (0, _1.roundTo)(window2.productionTargetCount, 2),
9647
+ performanceModeFrom: window2.performanceModeFrom,
9648
+ performanceModeType: window2.performanceModeType,
9649
+ operatorInitials: window2.operatorInitials
9650
+ };
9651
+ if (window2.inShiftCount > 0) {
9652
+ result.rssiAvg = divide(window2.rssiAvg, window2.inShiftCount, 4);
9653
+ result.electricalVoltsAvg = divide(window2.electricalVoltsAvg, window2.inShiftCount, 4);
9654
+ result.electricalAmpsAvg = divide(window2.electricalAmpsAvg, window2.inShiftCount, 4);
9655
+ result.electricalHzAvg = divide(window2.electricalHzAvg, window2.inShiftCount, 4);
9656
+ result.electricalPfAvg = divide(window2.electricalPfAvg, window2.inShiftCount, 4);
9657
+ result.electricalKwAvg = divide(window2.electricalKwAvg, window2.inShiftCount, 4);
9658
+ }
9659
+ return result;
9660
+ }
9661
+ }
9662
+ function combineStationWindowsByTime(windows) {
9663
+ const outputWindows = [];
9664
+ const windowsByTime = {};
9665
+ for (const window2 of windows) {
9666
+ if (windowsByTime[window2.windowStartAtTimestamp] == null) {
9667
+ windowsByTime[window2.windowStartAtTimestamp] = [];
9668
+ }
9669
+ delete window2.stationCode;
9670
+ delete window2.stationName;
9671
+ windowsByTime[window2.windowStartAtTimestamp].push(window2);
9672
+ }
9673
+ const times = Object.keys(windowsByTime).map((k) => Number(k));
9674
+ for (const time of times) {
9675
+ const sameTimeWindows = windowsByTime[time];
9676
+ outputWindows.push(combineStationWindows(sameTimeWindows, false, true));
9677
+ }
9678
+ return outputWindows;
9679
+ }
9680
+ function aggregateStationWindows(manifest, windows, station, aggregateWindowInMinutes, includeFutureWindowsUntil, inShiftAverages = false, schedules) {
9681
+ if (!windows.length) {
9682
+ return [];
9683
+ }
9684
+ let aggregatedWindows = [];
9685
+ const aggregateWindowInMs = aggregateWindowInMinutes * 6e4;
9686
+ let alignedWithAggregateWindowIndex = aggregateWindowInMinutes >= time_1.TimeIntervals["1h"].min ? true : false;
9687
+ const batch = [];
9688
+ for (let i = 0; i < windows.length; i++) {
9689
+ const thisWindow = windows[i];
9690
+ const thisWindowDuration = thisWindow.windowEndAtTimestamp - thisWindow.windowStartAtTimestamp;
9691
+ if (thisWindowDuration > aggregateWindowInMs) {
9692
+ throw new Error("Windows being aggregated must be less than or equal to the aggregate window. " + windows[i].totalMs + " " + aggregateWindowInMinutes);
9693
+ }
9694
+ if (alignedWithAggregateWindowIndex === false) {
9695
+ if (windows[i].windowStartAtTimestamp % aggregateWindowInMs === 0) {
9696
+ alignedWithAggregateWindowIndex = true;
9697
+ } else {
9698
+ continue;
9699
+ }
9700
+ }
9701
+ batch.push(windows[i]);
9702
+ const durationOfBatch = batch.reduce((a, b) => a + b.totalMs, 0);
9703
+ if (durationOfBatch >= aggregateWindowInMs) {
9704
+ aggregatedWindows.push(combineStationWindows(batch, inShiftAverages));
9705
+ batch.length = 0;
9706
+ }
9707
+ }
9708
+ if (includeFutureWindowsUntil && station != null) {
9709
+ const windowDurationMs = aggregateWindowInMinutes * WINDOW_DURATION;
9710
+ const lastAggregatedWindowEndAtTimestamp = aggregatedWindows[aggregatedWindows.length - 1]?.windowEndAtTimestamp;
9711
+ const lastWindowEndAtTimestamp = lastAggregatedWindowEndAtTimestamp ?? windows[windows.length - 1].windowEndAtTimestamp;
9712
+ const futureWindowsStartAt = lastAggregatedWindowEndAtTimestamp == null && aggregateWindowInMinutes < time_1.TimeIntervals["1h"].min ? lastWindowEndAtTimestamp - lastWindowEndAtTimestamp % windowDurationMs : lastWindowEndAtTimestamp;
9713
+ const requiredFutureWindowsCount = Math.floor((includeFutureWindowsUntil - futureWindowsStartAt) / windowDurationMs);
9714
+ const { windows: futureTimeWindows, endAtTimestamp } = (0, times_1.generateTimeWindows)(futureWindowsStartAt, windowDurationMs, requiredFutureWindowsCount, void 0, false);
9715
+ const futureWindows = futureTimeWindows.map((x) => {
9716
+ const isInShift = shiftUtils.isTimeInShifts({
9717
+ time: x.windowStartAtTimestamp,
9718
+ shifts: station.shifts,
9719
+ timezone: station.timezone
9720
+ });
9721
+ const totalMs = x.windowEndAtTimestamp - x.windowStartAtTimestamp;
9722
+ return {
9723
+ accountId: station.accountId,
9724
+ stationCode: station.code,
9725
+ windowStartAt: x.windowStartAt,
9726
+ windowStartAtTimestamp: x.windowStartAtTimestamp,
9727
+ windowEndAt: x.windowEndAt,
9728
+ windowEndAtTimestamp: x.windowEndAtTimestamp,
9729
+ totalMs,
9730
+ shiftMs: isInShift ? totalMs : 0,
9731
+ isAlive: false,
9732
+ isFuture: true
9733
+ };
9734
+ });
9735
+ const futureWindowViewModels = (0, station_window_1.toStationWindowViewModel)((0, schedules_1.enrichStationWindowsWithSchedules)(station, futureWindows, schedules || [], endAtTimestamp), manifest).map((sw) => ({ ...sw, isFuture: true }));
9736
+ aggregatedWindows = aggregatedWindows.concat(futureWindowViewModels);
9737
+ }
9738
+ return aggregatedWindows;
9739
+ }
9740
+ async function aggregateStationWindowsBySkuCode(aggregateWindowInMinutes, stationWindows) {
9741
+ const skus = Array.from(new Set(stationWindows.flatMap((x) => x.skuCodes || []).filter((x) => !!x)));
9742
+ const windows = stationWindows.filter((x) => x.skuCodes && x.skuCodes.length > 0).reduce((prev, currentWindow) => {
9743
+ const skuCode = currentWindow.skuCodes?.join("-");
9744
+ const key = skuCode + currentWindow.windowStartAt;
9745
+ if (!prev[key]) {
9746
+ prev[key] = {
9747
+ skuCode,
9748
+ ...currentWindow
9749
+ };
9750
+ } else {
9751
+ const w = combineStationWindows([prev[key], currentWindow], false, true);
9752
+ w.totalMs = w.windowEndAtTimestamp - w.windowStartAtTimestamp;
9753
+ prev[key] = { ...w, skuCode };
9754
+ }
9755
+ return prev;
9756
+ }, {});
9757
+ const windowsBySku = utils.groupBy(Object.values(windows), "skuCode");
9758
+ if (aggregateWindowInMinutes === 1) {
9759
+ return skus.map((code) => {
9760
+ const skuWindows = windowsBySku.get(code) ?? [];
9761
+ const skuNames = skuWindows.find((s) => s.skuNames?.length)?.skuNames;
9762
+ return {
9763
+ skuCode: code,
9764
+ skuName: skuNames?.[0] || "",
9765
+ windows: windowsBySku.get(code) ?? []
9766
+ };
9767
+ });
9768
+ }
9769
+ const results = [];
9770
+ windowsBySku.forEach((values, skuCode) => {
9771
+ const skuNames = values.find((s) => s.skuNames?.length)?.skuNames;
9772
+ const aggregatedWindows = {
9773
+ skuCode,
9774
+ skuName: skuNames?.[0] || "",
9775
+ windows: []
9776
+ };
9777
+ const batch = [];
9778
+ for (let i = 0; i < values.length; i++) {
9779
+ batch.push(values[i]);
9780
+ if ((i + 1) % aggregateWindowInMinutes === 0 || i + 1 === values.length) {
9781
+ aggregatedWindows.windows.push(combineStationWindows(batch, false, true));
9782
+ batch.length = 0;
9783
+ }
9784
+ }
9785
+ results.push(aggregatedWindows);
9786
+ });
9787
+ return results;
9788
+ }
9789
+ function extractDowntimesFromStationWindows(windows, now) {
9790
+ const isOngoingThreshold = (0, moment_timezone_1.default)(now).startOf("minute").add(-1, "minute").valueOf();
9791
+ const downtimes = {};
9792
+ let currentDowntimeStartTime = 0;
9793
+ let currentDowntimeId = void 0;
9794
+ let currentDowntimeFirstWindow = void 0;
9795
+ let accumulatedEnergyKwh = 0;
9796
+ let accumulatedEnergyCost = 0;
9797
+ let accumulatedLostProductionCost = 0;
9798
+ let accumulatedLostProductionQuantity = 0;
9799
+ for (let i = 0; i < windows.length; i++) {
9800
+ const window2 = windows[i];
9801
+ if (window2.totalMs > 6e4) {
9802
+ throw Error("extractDowntimesFromStationWindows only works on non-aggregated station windows.");
9803
+ }
9804
+ const downtimeId = window2.downtimeIds?.join("") || "";
9805
+ const isLastWindow = i === windows.length - 1;
9806
+ const isDowntime = window2.downtimeMs != null && window2.downtimeMs > 0;
9807
+ const isContinousDowntime = currentDowntimeStartTime > 0 && currentDowntimeId === downtimeId;
9808
+ const isOngoing = window2.windowEndAtTimestamp >= isOngoingThreshold;
9809
+ if (isDowntime && isContinousDowntime && !isLastWindow) {
9810
+ accumulatedEnergyKwh += window2.electricalKwh ?? 0;
9811
+ accumulatedEnergyCost += window2.electricalCost ?? 0;
9812
+ accumulatedLostProductionCost += window2.lostProductionCostDowntime ?? 0;
9813
+ accumulatedLostProductionQuantity += window2.productionIdealCount ?? 0;
9814
+ continue;
9815
+ }
9816
+ if (currentDowntimeStartTime > 0) {
9817
+ const from = currentDowntimeStartTime;
9818
+ const to = window2.windowStartAtTimestamp;
9819
+ if (currentDowntimeId != null) {
9820
+ downtimes[currentDowntimeStartTime] = {
9821
+ id: currentDowntimeId,
9822
+ type: enums_1.DowntimeType.Unknown,
9823
+ stationCode: currentDowntimeFirstWindow?.stationCode || "",
9824
+ stationName: currentDowntimeFirstWindow?.stationName,
9825
+ skuCode: currentDowntimeFirstWindow?.skuCodes?.join(","),
9826
+ skuName: currentDowntimeFirstWindow?.skuNames?.join(","),
9827
+ scheduleId: currentDowntimeFirstWindow?.scheduleIds?.at(0),
9828
+ workOrderReference: currentDowntimeFirstWindow?.workOrderReferences?.join(","),
9829
+ range: (0, times_1.timestampsToTimeRange)({ from, to }),
9830
+ reasonCode: currentDowntimeFirstWindow?.downtimeReasonCodes?.at(0),
9831
+ reasonBreadcrumb: [],
9832
+ isOngoing,
9833
+ energyKwh: accumulatedEnergyKwh || void 0,
9834
+ energyCost: accumulatedEnergyCost || void 0,
9835
+ lostProductionCost: accumulatedLostProductionCost || void 0,
9836
+ lostProductionQuantity: accumulatedLostProductionQuantity || void 0
9837
+ };
9838
+ }
9839
+ currentDowntimeStartTime = 0;
9840
+ currentDowntimeId = void 0;
9841
+ currentDowntimeFirstWindow = void 0;
9842
+ accumulatedEnergyKwh = 0;
9843
+ accumulatedEnergyCost = 0;
9844
+ accumulatedLostProductionCost = 0;
9845
+ accumulatedLostProductionQuantity = 0;
9846
+ }
9847
+ if (isDowntime) {
9848
+ currentDowntimeStartTime = window2.windowStartAtTimestamp;
9849
+ currentDowntimeId = downtimeId;
9850
+ currentDowntimeFirstWindow = window2;
9851
+ accumulatedEnergyKwh = window2.electricalKwh ?? 0;
9852
+ accumulatedEnergyCost = window2.electricalCost ?? 0;
9853
+ accumulatedLostProductionCost = window2.lostProductionCostDowntime ?? 0;
9854
+ accumulatedLostProductionQuantity = window2.productionIdealCount ?? 0;
9855
+ }
9856
+ }
9857
+ return Object.values(downtimes);
9858
+ }
9859
+ function getReliabilityData(windows) {
9860
+ const periods = [];
9861
+ let currentPeriod = { totalTime: 0, type: "start" };
9862
+ for (const window2 of windows) {
9863
+ const issueTime = window2.downtimeMs || 0;
9864
+ const runningTime = window2.scheduledProductionMs || 0;
9865
+ if (issueTime > 0) {
9866
+ if (currentPeriod.type === "running") {
9867
+ periods.push(currentPeriod);
9868
+ currentPeriod = { totalTime: 0, type: "stopped" };
9869
+ }
9870
+ currentPeriod.type = "stopped";
9871
+ currentPeriod.totalTime += issueTime;
9872
+ } else if (runningTime > 0) {
9873
+ if (currentPeriod.type === "stopped") {
9874
+ periods.push(currentPeriod);
9875
+ currentPeriod = { totalTime: 0, type: "running" };
9876
+ }
9877
+ currentPeriod.type = "running";
9878
+ currentPeriod.totalTime += runningTime;
9879
+ }
9880
+ }
9881
+ periods.push(currentPeriod);
9882
+ const runningsCount = periods.filter((period) => period.type === "running").length;
9883
+ const stopsCount = periods.filter((period) => period.type === "stopped").length;
9884
+ const totalRunningTime = periods.filter((period) => period.type === "running").reduce((a, b) => a + b.totalTime, 0);
9885
+ const totalStoppedTime = periods.filter((period) => period.type === "stopped").reduce((a, b) => a + b.totalTime, 0);
9886
+ return {
9887
+ runningsCount,
9888
+ stopsCount,
9889
+ totalRunningTime,
9890
+ totalStoppedTime
9891
+ };
9892
+ }
9893
+ function calculateReliabilityMetrics(reliabilityData) {
9894
+ if (reliabilityData.stopsCount === 0 || reliabilityData.runningsCount === 0) {
9895
+ return;
9896
+ }
9897
+ return {
9898
+ mtbf: reliabilityData.totalRunningTime / reliabilityData.runningsCount,
9899
+ mttr: reliabilityData.totalStoppedTime / reliabilityData.stopsCount
9900
+ };
9901
+ }
9902
+ function downtimesToStationWindows(downtimes, stations, nowOverride) {
9903
+ const now = nowOverride == null ? (0, moment_timezone_1.default)().valueOf() : nowOverride;
9904
+ const stationWindowsMap = downtimes.reduce((a, downtime) => {
9905
+ const stationIdleCostPerMinute = stations.find((s) => s.code === downtime.stationCode)?.idleCostPerMinute || 0;
9906
+ const startAt = (0, moment_timezone_1.default)(downtime.startAt).valueOf();
9907
+ const endAt = downtime.endAt == null ? now : (0, moment_timezone_1.default)(downtime.endAt).valueOf();
9908
+ let windowStartAt = startAt - startAt % WINDOW_DURATION;
9909
+ let windowsForThisDowntime = 0;
9910
+ while (windowStartAt + WINDOW_DURATION <= endAt && windowsForThisDowntime < MAX_WINDOWS_PER_DOWNTIME) {
9911
+ windowsForThisDowntime++;
9912
+ const windowEndAt = windowStartAt + WINDOW_DURATION;
9913
+ const timestamp = windowStartAt + "_" + windowEndAt + "_" + downtime.stationCode;
9914
+ const stationWindow = a.get(timestamp) || {
9915
+ accountId: downtime.accountId,
9916
+ stationCode: downtime.stationCode,
9917
+ windowStartAt: (0, moment_timezone_1.default)(windowStartAt).toISOString(),
9918
+ windowEndAt: (0, moment_timezone_1.default)(windowEndAt).toISOString(),
9919
+ windowStartAtTimestamp: windowStartAt,
9920
+ windowEndAtTimestamp: windowEndAt,
9921
+ totalMs: WINDOW_DURATION,
9922
+ downtimeMs: 0
9923
+ };
9924
+ if (downtime.excludedAt != null) {
9925
+ const newStationWindow = {
9926
+ ...stationWindow,
9927
+ downtimeMs: 0,
9928
+ downtimeId: void 0,
9929
+ downtimeReasonCode: void 0,
9930
+ downtimeSince: void 0,
9931
+ lostProductionCostDowntime: 0
9932
+ };
9933
+ a.set(timestamp, newStationWindow);
9934
+ } else {
9935
+ const issueTime = Math.min(windowEndAt, endAt) - Math.max(startAt, windowStartAt);
9936
+ const idleCost = downtime.skuValue ?? stationIdleCostPerMinute;
9937
+ const lostProductionCostDowntime = idleCost * (issueTime / time_1.TimeIntervals["1m"].ms);
9938
+ const newStationWindow = {
9939
+ ...stationWindow,
9940
+ downtimeMs: Math.max(stationWindow.downtimeMs, issueTime),
9941
+ downtimeId: downtime.id,
9942
+ downtimeReasonCode: downtime.reasonCode,
9943
+ downtimeSince: downtime.startAt,
9944
+ lostProductionCostDowntime
9945
+ };
9946
+ if (newStationWindow.downtimeMs > 0) {
9947
+ newStationWindow.productionTargetCount = 0;
9948
+ }
9949
+ a.set(timestamp, newStationWindow);
9950
+ }
9951
+ windowStartAt = windowEndAt;
9952
+ }
9953
+ return a;
9954
+ }, /* @__PURE__ */ new Map());
9955
+ return [...stationWindowsMap.values()];
9956
+ }
9957
+ function filterStationWindowsBySkuCode(windows, skuCodes) {
9958
+ if (!skuCodes?.length) {
9959
+ return [...windows];
9960
+ }
9961
+ return windows.map((s) => {
9962
+ const hasSkuCode = !!(s.skuCodes?.length && skuCodes.some((code) => s.skuCodes?.includes(code)));
9963
+ return {
9964
+ ...s,
9965
+ productionGoodCount: hasSkuCode ? s.productionGoodCount : 0,
9966
+ productionBadCount: hasSkuCode ? s.productionBadCount : 0,
9967
+ productionIdealCount: hasSkuCode ? s.productionIdealCount : 0,
9968
+ productionTargetCount: hasSkuCode ? s.productionTargetCount : 0
9969
+ };
9970
+ });
9971
+ }
9972
+ function filterStationWindowsByShiftNames(windows, shiftNames) {
9973
+ if (!shiftNames?.length) {
9974
+ return [...windows];
9975
+ }
9976
+ return windows.map((s) => {
9977
+ const hasShiftName = !!(s.shiftNames?.length && shiftNames.some((name) => s.shiftNames?.includes(name)));
9978
+ if (hasShiftName) {
9979
+ return s;
9980
+ }
9981
+ return {
9982
+ ...s,
9983
+ shiftMs: 0,
9984
+ shiftNames: void 0,
9985
+ downtimeMs: void 0,
9986
+ downtimeIds: void 0,
9987
+ downtimeReasonCodes: void 0,
9988
+ downtimeSince: void 0,
9989
+ productionGoodCount: 0,
9990
+ productionBadCount: 0,
9991
+ productionIdealCount: 0,
9992
+ productionTargetCount: 0,
9993
+ productionTotalCount: 0,
9994
+ productionGoodValue: 0,
9995
+ productionBadValue: 0,
9996
+ productionMs: 0,
9997
+ productionRatePerHour: 0,
9998
+ lostProductionCostDowntime: 0,
9999
+ lostProductionCostQuality: 0,
10000
+ lostProductionCostNonProduction: 0,
10001
+ lostProductionCostSpeed: 0,
10002
+ lostProductionCostTotal: 0,
10003
+ speed: 0,
10004
+ electricalKwh: 0,
10005
+ electricalKwAvg: 0,
10006
+ electricalAmpsAvg: 0,
10007
+ electricalCo2: 0,
10008
+ electricalCost: 0,
10009
+ electricalHzAvg: 0,
10010
+ electricalPfAvg: 0,
10011
+ electricalVoltsAvg: 0
10012
+ };
10013
+ });
10014
+ }
10015
+ function getCycleTimeFromSku(sku) {
10016
+ if (sku == null) {
10017
+ return void 0;
10018
+ }
10019
+ if (sku.cycleTime != null) {
10020
+ return sku.cycleTime;
10021
+ }
10022
+ const partsPerCycle = sku.partsPerCycle || 1;
10023
+ if (sku.unitsPerMinute != null) {
10024
+ return time_1.TimeIntervals["1m"].ms / sku.unitsPerMinute * partsPerCycle;
10025
+ }
10026
+ if (sku.unitsPerHour != null) {
10027
+ return time_1.TimeIntervals["1h"].ms / sku.unitsPerHour * partsPerCycle;
10028
+ }
10029
+ return void 0;
10030
+ }
10031
+ function getPerformanceValueFromSkuCycleTime(mode, cycleTime) {
10032
+ if (!cycleTime) {
10033
+ return void 0;
10034
+ }
10035
+ if (mode === enums_1.PERFORMANCE_MODE_TYPE.cycleTime) {
10036
+ return cycleTime;
10037
+ }
10038
+ if (mode === enums_1.PERFORMANCE_MODE_TYPE.unitsPerHour) {
10039
+ return time_1.TimeIntervals["1h"].ms / cycleTime;
10040
+ }
10041
+ if (mode === enums_1.PERFORMANCE_MODE_TYPE.unitsPerMinute) {
10042
+ return time_1.TimeIntervals["1m"].ms / cycleTime;
10043
+ }
10044
+ return void 0;
10045
+ }
10046
+ function getPerformanceModeFromSku(sku) {
10047
+ return sku?.cycleTime ? enums_1.PERFORMANCE_MODE_TYPE.cycleTime : sku?.unitsPerHour ? enums_1.PERFORMANCE_MODE_TYPE.unitsPerHour : sku?.unitsPerMinute ? enums_1.PERFORMANCE_MODE_TYPE.unitsPerMinute : sku?.lineSpeedTarget ? enums_1.PERFORMANCE_MODE_TYPE.lineSpeed : enums_1.PERFORMANCE_MODE_TYPE.none;
10048
+ }
10049
+ function add(a, b) {
10050
+ if (a == void 0 && b == void 0) {
10051
+ return void 0;
10052
+ }
10053
+ return (a || 0) + (b || 0);
10054
+ }
10055
+ function divide(a, b, fractionDigits) {
10056
+ if (a == void 0 || !b) {
10057
+ return void 0;
10058
+ }
10059
+ return Number((a / b).toFixed(fractionDigits));
10060
+ }
10061
+ exports2.AggregatedProduction = zod_1.default.object({
10062
+ id: zod_1.default.string(),
10063
+ accountId: zod_1.default.string(),
10064
+ workOrderReference: zod_1.default.string(),
10065
+ skuCode: zod_1.default.string(),
10066
+ skuName: zod_1.default.string(),
10067
+ quantityGood: zod_1.default.number(),
10068
+ quantityBad: zod_1.default.number(),
10069
+ quantityTotal: zod_1.default.number(),
10070
+ electricalKwh: zod_1.default.number(),
10071
+ electricalCost: zod_1.default.number()
10072
+ });
10073
+ function aggregateProductionFromStationWindows(accountId, stationWindows) {
10074
+ return Object.values(stationWindows.reduce((a, b) => {
10075
+ if (b.workOrderReferences == null || b.workOrderReferences.length === 0) {
10076
+ return a;
10077
+ }
10078
+ const id = b.workOrderReferences?.join(",") + "_" + b.skuCodes?.join(",");
10079
+ if (a[id] == null) {
10080
+ a[id] = {
10081
+ id,
10082
+ accountId,
10083
+ workOrderReference: b.workOrderReferences?.join(",") || "",
10084
+ skuCode: b.skuCodes?.join(",") || "",
10085
+ skuName: b.skuNames?.join(",") || "",
10086
+ quantityGood: 0,
10087
+ quantityBad: 0,
10088
+ quantityTotal: 0,
10089
+ electricalKwh: 0,
10090
+ electricalCost: 0
10091
+ };
10092
+ }
10093
+ a[id].quantityGood += b.productionGoodCount || 0;
10094
+ a[id].quantityBad += b.productionBadCount || 0;
10095
+ a[id].electricalKwh += b.electricalKwh || 0;
10096
+ a[id].electricalCost += b.electricalCost || 0;
10097
+ return a;
10098
+ }, {})).map((p) => {
10099
+ const quantityTotal = utils.roundTo(p.quantityGood + p.quantityBad, 2);
10100
+ const quantityGood = utils.roundTo(p.quantityGood, 2);
10101
+ const quantityBad = utils.roundTo(p.quantityBad, 2);
10102
+ return { ...p, quantityTotal, quantityGood, quantityBad };
10103
+ });
10104
+ }
10105
+ function aggregateProductionBySkuFromStationWindows(accountId, stationWindows) {
10106
+ return Object.values(stationWindows.reduce((a, b) => {
10107
+ const skuCode = b.skuCodes?.join(",") || "SKU NOT KNOWN";
10108
+ const id = skuCode;
10109
+ if (a[id] == null) {
10110
+ a[id] = {
10111
+ id,
10112
+ accountId,
10113
+ workOrderReference: "",
10114
+ skuCode,
10115
+ skuName: b.skuNames?.join(",") || "",
10116
+ quantityGood: 0,
10117
+ quantityBad: 0,
10118
+ quantityTotal: 0,
10119
+ electricalKwh: 0,
10120
+ electricalCost: 0
10121
+ };
10122
+ }
10123
+ a[id].quantityGood += b.productionGoodCount || 0;
10124
+ a[id].quantityBad += b.productionBadCount || 0;
10125
+ a[id].electricalKwh += b.electricalKwh || 0;
10126
+ a[id].electricalCost += b.electricalCost || 0;
10127
+ return a;
10128
+ }, {})).map((p) => {
10129
+ const quantityTotal = utils.roundTo(p.quantityGood + p.quantityBad, 2);
10130
+ const quantityGood = utils.roundTo(p.quantityGood, 2);
10131
+ const quantityBad = utils.roundTo(p.quantityBad, 2);
10132
+ return { ...p, quantityTotal, quantityGood, quantityBad };
10133
+ });
10134
+ }
10135
+ function isSignalNonProductionWindow(window2) {
10136
+ return (window2.scheduledNonProductionMs || 0) > 0 && !!window2.nonProductionReasonCode && window2.scheduleId == null;
10137
+ }
10138
+ function signalNonProductionReasonCode(window2) {
10139
+ const nonProductionReasonCode = window2.nonProductionReasonCodes?.[0];
10140
+ return isSignalNonProductionWindow({
10141
+ scheduledNonProductionMs: window2.scheduledNonProductionMs,
10142
+ nonProductionReasonCode,
10143
+ scheduleId: window2.scheduleIds?.[0]
10144
+ }) ? nonProductionReasonCode : void 0;
10145
+ }
10146
+ }
10147
+ });
10148
+
8942
10149
  // ../../packages/common/build/view-models/station.js
8943
10150
  var require_station4 = __commonJS({
8944
10151
  "../../packages/common/build/view-models/station.js"(exports2) {
@@ -8954,6 +10161,7 @@ var require_station4 = __commonJS({
8954
10161
  var schedule_1 = require_schedule3();
8955
10162
  var note_1 = require_note3();
8956
10163
  var task_1 = require_task();
10164
+ var station_windows_1 = require_station_windows();
8957
10165
  exports2.StationState = zod_1.z.object({
8958
10166
  code: zod_1.z.string(),
8959
10167
  label: zod_1.z.string(),
@@ -9032,6 +10240,8 @@ var require_station4 = __commonJS({
9032
10240
  state = exports2.StationStates.stopped;
9033
10241
  } else if (station.activeSchedule?.nonProductionReasonCode != null) {
9034
10242
  state = exports2.StationStates.non_production;
10243
+ } else if ((0, station_windows_1.signalNonProductionReasonCode)(station.lastStationWindow) != null) {
10244
+ state = exports2.StationStates.non_production;
9035
10245
  } else if (station.activeSchedule?.skuCode != null) {
9036
10246
  state = exports2.StationStates.running;
9037
10247
  } else {
@@ -9142,97 +10352,6 @@ var require_plant3 = __commonJS({
9142
10352
  }
9143
10353
  });
9144
10354
 
9145
- // ../../packages/common/build/configVars.js
9146
- var require_configVars = __commonJS({
9147
- "../../packages/common/build/configVars.js"(exports2) {
9148
- "use strict";
9149
- Object.defineProperty(exports2, "__esModule", { value: true });
9150
- exports2.REDSHIFT_USERNAME = exports2.REDSHIFT_PORT = exports2.REDSHIFT_HOST_PUBLIC = exports2.REDSHIFT_HOST = exports2.SES_CONFIG = exports2.RATE_LIMIT_COUNT = exports2.RATE_LIMIT_WINDOW = exports2.MS_LOGIN_CALLBACK = exports2.MS_LOGIN_CLIENT_SECRET = exports2.MS_LOGIN_CLIENT_ID = exports2.ENABLE_DEMO_MODE = exports2.MQTT_PORT = exports2.MQTT_HOST = exports2.DEFAULT_ACCOUNT_ID = exports2.AUTH_BYPASS_DOMAIN = exports2.KNEX_SEEDS_DIR = exports2.QUEUE_LENGTH = exports2.LOGIN_COOKIE_SECRET = exports2.ENABLE_MS_TEAM_ALERT = exports2.ALERT_SLACK_TOKEN = exports2.ALERT_SLACK_CHANNEL = exports2.ENABLE_SLACK_ALERT = exports2.JWT_SECRET = exports2.AWS_BACKUP_S3_BUCKET = exports2.AWS_REGION = exports2.AWS_SECRET_ACCESS_KEY = exports2.AWS_ACCESS_KEY_ID = exports2.LOGIN_CALL_BACK_URL = exports2.TO_EMAIL_OVERRIDE = exports2.BCC_EMAIL = exports2.FROM_EMAIL = exports2.INFLUX_WRITE_PROTECTED = exports2.INFLUX_BUCKET = exports2.INFLUX_ORG = exports2.INFLUX_TOKEN = exports2.INFLUX_HOST_URL = exports2.PG_DB = exports2.PG_PASS = exports2.PG_USER = exports2.PG_HOST = exports2.BUSROOT_MQTT_FORWARDER_TOPIC = exports2.BUSROOT_MQTT_FORWARDER_PASS = exports2.BUSROOT_MQTT_FORWARDER_USER = exports2.BUSROOT_MQTT_FORWARDER_HOST = exports2.ADMIN_API_KEY = exports2.ADMIN_PASSWORD = exports2.ADMIN_USERNAME = exports2.DOMAIN_NAME = exports2.APP_ENV = exports2.NODE_ENV = void 0;
9151
- exports2.NON_PRODUCTION_SIGNAL_TIMEOUT_MS = exports2.CACHE_BUILDER_ERROR_BACKOFF_MS = exports2.CACHE_BUILDER_ACCOUNT_BUDGET_MS = exports2.CACHE_BUILDER_IDLE_SLEEP_MS = exports2.CACHE_WARMING_LOOKBACK_DAYS = exports2.CACHE_WARMING_THROTTLE_MS = exports2.CACHE_WARMING_STAGGER_MAX_MS = exports2.CACHE_WARMING_CRON = exports2.CACHE_WARMING_ENABLED = exports2.STATION_FANOUT_PAUSE_MS = exports2.STATION_FANOUT_BATCH_SIZE = exports2.DAU_BUFFER_MAX_MESSAGE_BYTES = exports2.DAU_BUFFER_MAX_AGE_MS = exports2.DAU_BUFFER_SIZE = exports2.ENABLE_MQTT_EVENTS = exports2.ANTHROPIC_API_KEY = exports2.REDSHIFT_DB = exports2.REDSHIFT_PASSWORD = void 0;
9152
- function parsePositiveIntEnv(value, fallback) {
9153
- const parsed = Number(value);
9154
- return Number.isFinite(parsed) && parsed >= 1 ? Math.floor(parsed) : fallback;
9155
- }
9156
- function parseNonNegativeIntEnv(value, fallback) {
9157
- const parsed = Number(value);
9158
- return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : fallback;
9159
- }
9160
- exports2.NODE_ENV = process.env.NODE_ENV;
9161
- exports2.APP_ENV = process.env.APP_ENV || exports2.NODE_ENV;
9162
- exports2.DOMAIN_NAME = process.env.DOMAIN_NAME || "undefined";
9163
- exports2.ADMIN_USERNAME = process.env.ADMIN_USERNAME || "admin";
9164
- exports2.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
9165
- exports2.ADMIN_API_KEY = process.env.ADMIN_API_KEY;
9166
- exports2.BUSROOT_MQTT_FORWARDER_HOST = process.env.BUSROOT_MQTT_FORWARDER_HOST;
9167
- exports2.BUSROOT_MQTT_FORWARDER_USER = process.env.BUSROOT_MQTT_FORWARDER_USER;
9168
- exports2.BUSROOT_MQTT_FORWARDER_PASS = process.env.BUSROOT_MQTT_FORWARDER_PASS;
9169
- exports2.BUSROOT_MQTT_FORWARDER_TOPIC = process.env.BUSROOT_MQTT_FORWARDER_TOPIC || "#";
9170
- exports2.PG_HOST = process.env.PG_HOST || exports2.DOMAIN_NAME;
9171
- exports2.PG_USER = process.env.PG_USER || "postgres";
9172
- exports2.PG_PASS = process.env.PG_PASS || "pHrJvh4ICt2Fh7Qu";
9173
- exports2.PG_DB = process.env.PG_DB || "postgres";
9174
- exports2.INFLUX_HOST_URL = process.env.INFLUX_HOST_URL || `http://${exports2.DOMAIN_NAME}:8086`;
9175
- exports2.INFLUX_TOKEN = process.env.INFLUX_TOKEN;
9176
- exports2.INFLUX_ORG = process.env.INFLUX_ORG || "";
9177
- exports2.INFLUX_BUCKET = process.env.INFLUX_BUCKET || "default";
9178
- exports2.INFLUX_WRITE_PROTECTED = process.env.INFLUX_WRITE_PROTECTED === "true";
9179
- exports2.FROM_EMAIL = process.env.FROM_EMAIL || "busroot@output.industries";
9180
- exports2.BCC_EMAIL = process.env.BCC_EMAIL;
9181
- exports2.TO_EMAIL_OVERRIDE = process.env.TO_EMAIL_OVERRIDE;
9182
- exports2.LOGIN_CALL_BACK_URL = process.env.LOGIN_CALL_BACK_URL || `https://${exports2.DOMAIN_NAME}`;
9183
- exports2.AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID || "";
9184
- exports2.AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY || "";
9185
- exports2.AWS_REGION = process.env.AWS_REGION || "eu-west-2";
9186
- exports2.AWS_BACKUP_S3_BUCKET = process.env.AWS_BACKUP_S3_BUCKET;
9187
- exports2.JWT_SECRET = process.env.JWT_SECRET || "greentyre";
9188
- exports2.ENABLE_SLACK_ALERT = (process.env.ENABLE_SLACK_ALERT || "").toLowerCase() === "true";
9189
- exports2.ALERT_SLACK_CHANNEL = process.env.ALERT_SLACK_CHANNEL || "C03164SPJSH";
9190
- exports2.ALERT_SLACK_TOKEN = process.env.ALERT_SLACK_TOKEN;
9191
- exports2.ENABLE_MS_TEAM_ALERT = (process.env.ENABLE_MS_TEAM_ALERT || "").toLowerCase() === "true";
9192
- exports2.LOGIN_COOKIE_SECRET = process.env.LOGIN_COOKIE_SECRET || "greentyre";
9193
- exports2.QUEUE_LENGTH = parseInt(process.env["BUSROOT_QUEUE_LENGTH"] || "") || 200;
9194
- exports2.KNEX_SEEDS_DIR = process.env.KNEX_SEEDS_DIR;
9195
- exports2.AUTH_BYPASS_DOMAIN = process.env.AUTH_BYPASS_DOMAIN;
9196
- exports2.DEFAULT_ACCOUNT_ID = process.env.DEFAULT_ACCOUNT_ID || "account_0000000000000000000";
9197
- exports2.MQTT_HOST = process.env.MQTT_HOST || exports2.DOMAIN_NAME;
9198
- exports2.MQTT_PORT = parseInt(process.env.MQTT_PORT || "") || 1883;
9199
- exports2.ENABLE_DEMO_MODE = process.env.ENABLE_DEMO_MODE === "true";
9200
- exports2.MS_LOGIN_CLIENT_ID = process.env.MS_LOGIN_CLIENT_ID;
9201
- exports2.MS_LOGIN_CLIENT_SECRET = process.env.MS_LOGIN_CLIENT_SECRET;
9202
- exports2.MS_LOGIN_CALLBACK = exports2.APP_ENV === "development" ? "http://localhost:3000" : `https://${exports2.DOMAIN_NAME}`;
9203
- exports2.RATE_LIMIT_WINDOW = parseInt(process.env.RATE_LIMIT_WINDOW || "60000");
9204
- exports2.RATE_LIMIT_COUNT = parseInt(process.env.RATE_LIMIT_COUNT || "10");
9205
- exports2.SES_CONFIG = {
9206
- accessKeyId: exports2.AWS_ACCESS_KEY_ID || "",
9207
- secretAccessKey: exports2.AWS_SECRET_ACCESS_KEY || "",
9208
- region: exports2.AWS_REGION,
9209
- apiVersion: "2010-12-01"
9210
- };
9211
- exports2.REDSHIFT_HOST = process.env.REDSHIFT_HOST;
9212
- exports2.REDSHIFT_HOST_PUBLIC = process.env.REDSHIFT_HOST_PUBLIC || "Not Set";
9213
- exports2.REDSHIFT_PORT = Number(process.env.REDSHIFT_PORT || 5439);
9214
- exports2.REDSHIFT_USERNAME = process.env.REDSHIFT_USERNAME || "admin";
9215
- exports2.REDSHIFT_PASSWORD = process.env.REDSHIFT_PASSWORD;
9216
- exports2.REDSHIFT_DB = process.env.REDSHIFT_DB || "dev";
9217
- exports2.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
9218
- exports2.ENABLE_MQTT_EVENTS = process.env.ENABLE_MQTT_EVENTS === "true" || false;
9219
- exports2.DAU_BUFFER_SIZE = parseInt(process.env.DAU_BUFFER_SIZE || "") || 5;
9220
- exports2.DAU_BUFFER_MAX_AGE_MS = parseInt(process.env.DAU_BUFFER_MAX_AGE_MS || "") || 30 * 24 * 60 * 60 * 1e3;
9221
- exports2.DAU_BUFFER_MAX_MESSAGE_BYTES = parseInt(process.env.DAU_BUFFER_MAX_MESSAGE_BYTES || "") || 8192;
9222
- exports2.STATION_FANOUT_BATCH_SIZE = parsePositiveIntEnv(process.env.STATION_WINDOW_BATCH_SIZE, 3);
9223
- exports2.STATION_FANOUT_PAUSE_MS = parseNonNegativeIntEnv(process.env.STATION_WINDOW_BATCH_PAUSE_MS, 500);
9224
- exports2.CACHE_WARMING_ENABLED = process.env.CACHE_WARMING_ENABLED === "true";
9225
- exports2.CACHE_WARMING_CRON = process.env.CACHE_WARMING_CRON || "0 2 * * *";
9226
- exports2.CACHE_WARMING_STAGGER_MAX_MS = parseNonNegativeIntEnv(process.env.CACHE_WARMING_STAGGER_MAX_MS, 30 * 60 * 1e3);
9227
- exports2.CACHE_WARMING_THROTTLE_MS = parseNonNegativeIntEnv(process.env.CACHE_WARMING_THROTTLE_MS, 250);
9228
- exports2.CACHE_WARMING_LOOKBACK_DAYS = parsePositiveIntEnv(process.env.CACHE_WARMING_LOOKBACK_DAYS, 730);
9229
- exports2.CACHE_BUILDER_IDLE_SLEEP_MS = parseNonNegativeIntEnv(process.env.CACHE_BUILDER_IDLE_SLEEP_MS, 2e3);
9230
- exports2.CACHE_BUILDER_ACCOUNT_BUDGET_MS = parsePositiveIntEnv(process.env.CACHE_BUILDER_ACCOUNT_BUDGET_MS, 6e4);
9231
- exports2.CACHE_BUILDER_ERROR_BACKOFF_MS = parseNonNegativeIntEnv(process.env.CACHE_BUILDER_ERROR_BACKOFF_MS, 5e3);
9232
- exports2.NON_PRODUCTION_SIGNAL_TIMEOUT_MS = parseNonNegativeIntEnv(process.env.NON_PRODUCTION_SIGNAL_TIMEOUT_MS, 0);
9233
- }
9234
- });
9235
-
9236
10355
  // ../../packages/common/build/utils/manifest-helpers.js
9237
10356
  var require_manifest_helpers = __commonJS({
9238
10357
  "../../packages/common/build/utils/manifest-helpers.js"(exports2) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "busroot-sdk",
3
- "version": "0.0.8-dev.2775675320",
3
+ "version": "0.0.8-dev.2785859549",
4
4
  "description": "An SDK for accessing Busroot from output.industries",
5
5
  "homepage": "https://www.output.industries",
6
6
  "main": "./build/index.js",