Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support workorder migrate #4782

Merged
merged 2 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions frontend/providers/workorder/src/pages/api/v1/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { migrateWorkOrders } from '@/services/db/workorder';
import { verify } from 'jsonwebtoken';
import { jsonRes } from '@/services/backend/response';
import { getUserById, updateUser } from '@/services/db/user';
import { desktopJwtSecret } from '@/services/backend/auth';

const verifyToken = (token: string) => {
try {
return verify(token, desktopJwtSecret) as { userUid: string; mergeUserUid: string };
} catch (error) {
throw new Error('Token verification failed');
}
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const token = req.body.token;
if (!token) {
return jsonRes(res, { code: 400, data: 'Invalid parameters' });
}

const { userUid, mergeUserUid } = verifyToken(token);

if (!mergeUserUid || !userUid) {
return jsonRes(res, { code: 400, data: 'Invalid user identifiers' });
}

const mergeUser = await getUserById(mergeUserUid);
const targetUser = await getUserById(userUid);

if (!mergeUser) {
return jsonRes(res, { code: 200, data: 'Merge user not found, nothing to do' });
}

const migrationResult = await migrateWorkOrders({ mergeUserUid, userUid });
if (!migrationResult.success) {
return jsonRes(res, { code: 500, data: migrationResult.message });
}

if (!targetUser) {
const updateResult = await updateUser(mergeUserUid, { userId: userUid });
if (updateResult.matchedCount === 0) {
return jsonRes(res, { code: 500, data: 'Failed to update user' });
}
}

return jsonRes(res, { code: 200, data: 'Success' });
} catch (error) {
console.log('Error in migrate handler:', error);
return jsonRes(res, { code: 500, data: error });
}
}
2 changes: 1 addition & 1 deletion frontend/providers/workorder/src/services/backend/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { verify, sign } from 'jsonwebtoken';
import type { NextApiRequest } from 'next';
import { ERROR_ENUM } from '../error';

const desktopJwtSecret = (process.env.JWT_SECRET_DESKTOP_TO_APP as string) || '123456789';
export const desktopJwtSecret = (process.env.JWT_SECRET_DESKTOP_TO_APP as string) || '123456789';
const appJwtSecret = (process.env.JWT_SECRET_SELF as string) || '123456789';

export const verifyAccessToken = async (req: NextApiRequest) => {
Expand Down
32 changes: 32 additions & 0 deletions frontend/providers/workorder/src/services/db/workorder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { WorkOrderDB, WorkOrderDialog, WorkOrderStatus, WorkOrderType } from '@/types/workorder';
import { connectToDatabase } from './mongodb';
import { getUserById } from './user';
import { ClientSession } from 'mongodb';

async function connectOrderCollection() {
const client = await connectToDatabase();
Expand Down Expand Up @@ -154,3 +155,34 @@ export async function deleteOrder({ orderId, userId }: { orderId: string; userId
const result = await collection.updateOne(filter, update);
return result;
}

export async function migrateWorkOrders({
mergeUserUid,
userUid
}: {
mergeUserUid: string;
userUid: string;
}): Promise<{ success: boolean; message: string }> {
try {
const collection = await connectOrderCollection();

const mergeUserOrders = await collection.find({ userId: mergeUserUid }).toArray();
if (mergeUserOrders.length === 0) {
return { success: true, message: 'No work orders found for mergeUserUid' };
}

const updateResult = await collection.updateMany(
{ userId: mergeUserUid },
{ $set: { userId: userUid } }
);

if (updateResult.modifiedCount === 0) {
return { success: false, message: 'Failed to migrate work orders' };
}

return { success: true, message: 'Work orders migrated successfully' };
} catch (error) {
console.log(error);
return { success: false, message: 'Error migrating work orders' };
}
}
Loading