Skip to content

Commit

Permalink
database scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
lucia-gomez committed Oct 24, 2024
1 parent 16e54f8 commit 33fdd7e
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 45 deletions.
28 changes: 28 additions & 0 deletions booking-app/app/api/db/addFields/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from "next/server";
import {
serverFetchAllDataFromCollection,
serverUpdateInFirestore,
} from "@/lib/firebase/server/adminDb";

export async function POST(request: NextRequest) {
const { collection } = await request.json();

try {
const rows = await serverFetchAllDataFromCollection(collection);

// await serverUpdateInFirestore(collection, rows[0].id, { level: 1 });
await Promise.all(
rows.map(row =>
serverUpdateInFirestore(collection, row.id, { level: 1 }),
),
);

return NextResponse.json({ modifiedRows: rows.length }, { status: 200 });
} catch (err) {
console.error(err);
return NextResponse.json(
{ error: "Failed to add fields to documents" },
{ status: 500 },
);
}
}
65 changes: 65 additions & 0 deletions booking-app/app/api/db/duplicate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from "next/server";
import {
serverDeleteData,
serverFetchAllDataFromCollection,
serverSaveDataToFirestore,
} from "@/lib/firebase/server/adminDb";

import { TableNames } from "@/components/src/policy";

export async function POST(request: NextRequest) {
const { newCollection } = await request.json();

try {
const rows = await serverFetchAllDataFromCollection(
TableNames.SAFETY_TRAINING,
);
const rowsWithoutIds = rows.map(row => {
const { id, ...other } = row;
return other;
});
await Promise.all(
rowsWithoutIds.map(row => serverSaveDataToFirestore(newCollection, row)),
);
return NextResponse.json(
{ duplicatedRows: rowsWithoutIds.length },
{ status: 200 },
);
} catch (err) {
console.error(err);
return NextResponse.json(
{ error: "Failed to duplicate events to new collection" },
{ status: 500 },
);
}
}

export async function DELETE(request: NextRequest) {
const rows = await serverFetchAllDataFromCollection(TableNames.BOOKING);

const ids = {};

for (let row of rows) {
if (!ids[row.calendarEventId]) {
ids[row.calendarEventId] = [];
}
ids[row.calendarEventId].push(row);
}

const deleteDocIds = [];

for (let key in ids) {
const dups = ids[key];
if (dups[0].requestedAt) {
deleteDocIds.push(dups[1].id);
} else {
deleteDocIds.push(dups[0].id);
}
}

await Promise.all(
deleteDocIds.map(id => serverDeleteData(TableNames.BOOKING, id)),
);

return NextResponse.json({ status: 200 });
}
54 changes: 54 additions & 0 deletions booking-app/app/api/db/merge/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import {
serverFetchAllDataFromCollection,
serverSaveDataToFirestore,
} from "@/lib/firebase/server/adminDb";

import { TableNames } from "@/components/src/policy";

export async function POST(request: NextRequest) {
const { source, destination } = await request.json();
const sourceTable = source as TableNames;
const destinationTable = destination as TableNames;

try {
const sourceRows = await serverFetchAllDataFromCollection(sourceTable);
const destinationRows =
await serverFetchAllDataFromCollection(destinationTable);

// filter out ids
const sourceRowsFiltered = sourceRows.map(row => {
const { id, email, ...other } = row;
return other;
});
const destinationRowsFiltered = destinationRows.map(row => {
const { id, ...other } = row;
return other;
});

const calIdToBookingStatus = {};
for (let row of sourceRowsFiltered) {
calIdToBookingStatus[row.calendarEventId] = row;
}

const merged = destinationRowsFiltered.map(booking => {
const matchingStatus = calIdToBookingStatus[booking.calendarEventId];
return { ...booking, ...matchingStatus };
});

await Promise.all(
merged.map(row => serverSaveDataToFirestore(destinationTable, row)),
);

return NextResponse.json(
{ duplicatedRows: merged.length },
{ status: 200 },
);
} catch (err) {
console.error(err);
return NextResponse.json(
{ error: "Failed to merge collections" },
{ status: 500 },
);
}
}
26 changes: 0 additions & 26 deletions booking-app/app/api/db/route.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Box, Button, Typography } from "@mui/material";
import React, { useState } from "react";

import AlertToast from "../../components/AlertToast";
import { TableNames } from "@/components/src/policy";

const SyncCalendars = () => {
const [loading, setLoading] = useState(false);
Expand Down Expand Up @@ -33,17 +34,18 @@ const SyncCalendars = () => {
}
};

const duplicate = async () => {
await fetch("/api/db", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
newCollection: "usersApprovers",
}),
});
};
// const duplicate = async () => {
// await fetch("/api/db/duplicate", {
// method: "DELETE",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({
// source: TableNames.BOOKING_STATUS,
// destination: TableNames.BOOKING,
// }),
// });
// };

return (
<Box>
Expand All @@ -60,7 +62,7 @@ const SyncCalendars = () => {
Sync Calendar Events
</Button>
</Box>
<Button onClick={duplicate}>Duplicate</Button>
{/* <Button onClick={duplicate}>Duplicate</Button> */}
<AlertToast
message={message}
severity={alertSeverity}
Expand Down
15 changes: 9 additions & 6 deletions booking-app/components/src/client/routes/components/Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -321,12 +321,15 @@ export const DatabaseProvider = ({
const fetchLiaisonUsers = async () => {
clientFetchAllDataFromCollection(TableNames.APPROVERS)
.then((fetchedData) => {
const filtered = fetchedData.map((item: any) => ({
id: item.id,
email: item.email,
department: item.department,
createdAt: item.createdAt,
}));
const filtered = fetchedData
.map((item: any) => ({
id: item.id,
email: item.email,
department: item.department,
createdAt: item.createdAt,
level: Number(item.level),
}))
.filter((x) => x.level === 1);
setLiaisonUsers(filtered);
})
.catch((error) => console.error("Error fetching data:", error));
Expand Down
2 changes: 1 addition & 1 deletion booking-app/components/src/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export enum TableNames {
PAS = "usersPa",
POLICY = "policy",
RESOURCES = "resources",
SAFETY_TRAINING = "usersSafetyWhitelist",
SAFETY_TRAINING = "usersWhitelist",
SETTINGS = "settings",
}

Expand Down
1 change: 1 addition & 0 deletions booking-app/components/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export type LiaisonType = {
email: string;
department: string;
createdAt: string;
level: number;
};

export type DepartmentType = {
Expand Down

0 comments on commit 33fdd7e

Please sign in to comment.