summaryrefslogtreecommitdiff
path: root/components/client-table-v2/preset-actions.ts
blob: 0b8b3adb95f3c10593d76218c88af593a644f9d8 (plain)
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
"use server";

import db from "@/db/db";
import { userCustomData } from "@/db/schema/user-custom-data/userCustomData";
import { eq, and } from "drizzle-orm";
import { Preset, PresetRepository } from "./preset-types";

// Drizzle Implementation of PresetRepository
// This file acts as the concrete repository implementation.
// To swap DBs, you would replace the logic here or create a new implementation file.

export async function getPresets(tableKey: string, userId: number): Promise<{ success: boolean; data?: Preset[]; error?: string }> {
  try {
    const settings = await db
      .select()
      .from(userCustomData)
      .where(
        and(
          eq(userCustomData.tableKey, tableKey),
          eq(userCustomData.userId, userId)
        )
      )
      .orderBy(userCustomData.createdDate);

    // Map DB entity to domain model
    const data: Preset[] = settings.map(s => ({
      id: s.id,
      name: s.customSettingName,
      setting: s.customSetting,
      createdAt: s.createdDate,
      updatedAt: s.updatedDate,
    }));

    return { success: true, data };
  } catch (error) {
    console.error("Failed to fetch presets:", error);
    return { success: false, error: "Failed to fetch presets" };
  }
}

export async function savePreset(
  userId: number,
  tableKey: string,
  name: string,
  setting: any
): Promise<{ success: boolean; error?: string }> {
  try {
    const existing = await db.query.userCustomData.findFirst({
        where: and(
            eq(userCustomData.userId, userId),
            eq(userCustomData.tableKey, tableKey),
            eq(userCustomData.customSettingName, name)
        )
    });

    if (existing) {
        await db.update(userCustomData)
            .set({ 
                customSetting: setting, 
                updatedDate: new Date() 
            })
            .where(eq(userCustomData.id, existing.id));
    } else {
        await db.insert(userCustomData).values({
            userId,
            tableKey,
            customSettingName: name,
            customSetting: setting,
        });
    }

    return { success: true };
  } catch (error) {
    console.error("Failed to save preset:", error);
    return { success: false, error: "Failed to save preset" };
  }
}

export async function deletePreset(id: string): Promise<{ success: boolean; error?: string }> {
  try {
    await db.delete(userCustomData).where(eq(userCustomData.id, id));
    return { success: true };
  } catch (error) {
    console.error("Failed to delete preset:", error);
    return { success: false, error: "Failed to delete preset" };
  }
}