File size: 5,935 Bytes
c09f67c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { RedisCache } from "./redis-client";

export const WIDGET_TYPES = [
  // Critical financial health (default primary widgets)
  "runway",
  "cash-flow",
  "account-balances",
  "profit-analysis",
  "revenue-forecast",
  "revenue-summary",
  "growth-rate",

  // Financial position
  "net-position",

  // Customer insights
  "customer-lifetime-value",
  "top-customer",

  // Receivables & invoices
  "outstanding-invoices",
  "overdue-invoices-alert",
  "invoice-payment-score",

  // Expenses & spending
  "monthly-spending",
  "recurring-expenses",
  "category-expenses",

  // Profitability metrics
  "profit-margin",

  // Operations
  "time-tracker",
  "billable-hours",

  // Admin & documents
  "inbox",
  "vault",
  "tax-summary",
] as const;

export type WidgetType = (typeof WIDGET_TYPES)[number];

export interface WidgetPreferences {
  primaryWidgets: WidgetType[];
  availableWidgets: WidgetType[];
}

export const DEFAULT_WIDGET_ORDER: WidgetType[] = [...WIDGET_TYPES];

export const DEFAULT_WIDGET_PREFERENCES: WidgetPreferences = {
  primaryWidgets: DEFAULT_WIDGET_ORDER.slice(0, 7), // First 7 widgets (insights is separate)
  availableWidgets: DEFAULT_WIDGET_ORDER.slice(7), // Remaining widgets
};

class WidgetPreferencesCache extends RedisCache {
  constructor() {
    super("widget-preferences");
  }

  private getWidgetPreferencesKey(teamId: string, userId: string): string {
    return `${teamId}:${userId}`;
  }

  async getWidgetPreferences(
    teamId: string,
    userId: string,
  ): Promise<WidgetPreferences> {
    const key = this.getWidgetPreferencesKey(teamId, userId);
    const preferences = await this.get<WidgetPreferences>(key);

    if (!preferences) {
      // Return default preferences if none exist
      return DEFAULT_WIDGET_PREFERENCES;
    }

    // Validate the preferences and ensure all widgets are accounted for
    const allWidgets = [
      ...preferences.primaryWidgets,
      ...preferences.availableWidgets,
    ];
    const missingWidgets = DEFAULT_WIDGET_ORDER.filter(
      (widget) => !allWidgets.includes(widget),
    );
    const extraWidgets = allWidgets.filter(
      (widget) => !DEFAULT_WIDGET_ORDER.includes(widget),
    );

    // Handle migrations when widgets are added or removed
    if (missingWidgets.length > 0 || extraWidgets.length > 0) {
      console.info(
        `Migrating widget preferences for team ${teamId}, user ${userId}. Missing: ${missingWidgets.join(", ") || "none"}, Extra: ${extraWidgets.join(", ") || "none"}`,
      );

      // Remove deprecated widgets from both lists
      const migratedPrimaryWidgets = preferences.primaryWidgets.filter(
        (widget) => !extraWidgets.includes(widget),
      );

      const migratedAvailableWidgets = preferences.availableWidgets.filter(
        (widget) => !extraWidgets.includes(widget),
      );

      // Add new widgets to available widgets (they can be moved to primary by the user)
      const updatedAvailableWidgets = [
        ...migratedAvailableWidgets,
        ...missingWidgets,
      ];

      const migratedPreferences: WidgetPreferences = {
        primaryWidgets: migratedPrimaryWidgets,
        availableWidgets: updatedAvailableWidgets,
      };

      // Save the migrated preferences
      await this.setWidgetPreferences(teamId, userId, migratedPreferences);

      return migratedPreferences;
    }

    return preferences;
  }

  async setWidgetPreferences(
    teamId: string,
    userId: string,
    preferences: WidgetPreferences,
  ): Promise<void> {
    // Validate preferences before saving
    const allWidgets = [
      ...preferences.primaryWidgets,
      ...preferences.availableWidgets,
    ];

    // Check that we have exactly the right widgets
    if (allWidgets.length !== DEFAULT_WIDGET_ORDER.length) {
      throw new Error(
        "Invalid widget preferences: incorrect number of widgets",
      );
    }

    // Check that all default widgets are present and no extras
    const missingWidgets = DEFAULT_WIDGET_ORDER.filter(
      (widget) => !allWidgets.includes(widget),
    );
    const extraWidgets = allWidgets.filter(
      (widget) => !DEFAULT_WIDGET_ORDER.includes(widget),
    );

    if (missingWidgets.length > 0) {
      throw new Error(
        `Invalid widget preferences: missing widgets ${missingWidgets.join(", ")}`,
      );
    }

    if (extraWidgets.length > 0) {
      throw new Error(
        `Invalid widget preferences: unknown widgets ${extraWidgets.join(", ")}`,
      );
    }

    // Check that primary widgets doesn't exceed 7 (insights is separate)
    if (preferences.primaryWidgets.length > 7) {
      throw new Error(
        "Invalid widget preferences: primary widgets cannot exceed 7",
      );
    }

    // Check for duplicates
    const duplicates = allWidgets.filter(
      (widget, index) => allWidgets.indexOf(widget) !== index,
    );
    if (duplicates.length > 0) {
      throw new Error(
        `Invalid widget preferences: duplicate widgets ${duplicates.join(", ")}`,
      );
    }

    const key = this.getWidgetPreferencesKey(teamId, userId);
    await this.set(key, preferences);
  }

  async updatePrimaryWidgets(
    teamId: string,
    userId: string,
    newPrimaryWidgets: WidgetType[],
  ): Promise<WidgetPreferences> {
    if (newPrimaryWidgets.length > 7) {
      throw new Error("Primary widgets cannot exceed 7");
    }

    const _currentPreferences = await this.getWidgetPreferences(teamId, userId);

    // Calculate available widgets (all widgets not in primary)
    const availableWidgets = DEFAULT_WIDGET_ORDER.filter(
      (widget) => !newPrimaryWidgets.includes(widget),
    );

    const newPreferences: WidgetPreferences = {
      primaryWidgets: newPrimaryWidgets,
      availableWidgets,
    };

    await this.setWidgetPreferences(teamId, userId, newPreferences);
    return newPreferences;
  }
}

export const widgetPreferencesCache = new WidgetPreferencesCache();