shoc-frontend-new/src/domain/work-orders/use-cases/use-work-order-mutations.ts
Arthur Bassi a0cf7b9ef0
Feat/vite typescript migration (#16)
* chore: add eslint, prettier, husky and commitlint tooling

* ci: add GitHub Actions workflow for lint and build

* build: migrate from CRA to Vite with TypeScript config

* docs: add architecture plan and design system documentation

* fix: scope ESLint to new components and hooks directories

* feat: add HTTP client, query cache and shared utilities

* feat: add theme system and global application styles

* feat: add shared UI, layout and domain badge components

* feat: add auth domain, provider and login page

* feat: add app shell, file-based routing and bootstrap

* feat: add protected layout and dashboard module

* feat: add accounts CRUD module

* feat: add assets CRUD module

* feat: add contacts CRUD module

* feat: add employees CRUD module

* feat: add locations CRUD module

* feat: add calendar events module

* feat: add follow-ups CRUD module

* feat: add PM schedules CRUD module

* feat: add work orders module with dispatch modals

* feat: add vendors CRUD and portal token panel

* feat: add vendor purchase orders module

* feat: add uplifts queue module

* feat: add settings for dropdowns and task templates

* feat: add vendor portal routes and signature capture

* test: add Vitest setup and Playwright login e2e spec

* chore: remove legacy CRA pages, Redux store and JS hooks

* chore: update gitignore and env example for Vite

* docs: translate pt-BR docs and Cursor rules to English

* fix(ci): fix login e2e session mock and prettier formatting

* fix(build): use mjs router script for Node 20 CI compatibility

* chore: remove migration scripts and unused generouted router

* fix(auth): restore JWT and align CRUD with backend routes

* fix(api): add no-content helpers and align paths with backend

* fix(accounts): align detail and mutation payloads with backend

* fix(contacts): resolve detail via GetContacts and map address DTOs

* fix(work-orders): align routes, delete body, and create payload

* fix(vendors): delete vendors via REST route

* fix(pm-schedules): handle empty save and delete responses

* fix(employees): add fallbacks for detail and dropdown calls

* chore(calendar): disable routes until backend exists

* chore(env): switch tracked env vars to Vite prefixes

* fix(api): align frontend contracts with backend review findings

Correct Work Order getById query param, asset site options via Location API,
Employee JobTitleId payload, and remove stale API paths.

* fix(employees,pm-schedules): align forms with backend API contracts

Align PM Schedule form and save payload with PMSchedule_DTO fields.
Bind employee Job Title select to jobTitleId for create/update payloads.
Add regression tests for both flows.

* fix(pm-schedules): gate edit/delete for Dev API contract

Production Dev API exposes only GetList and Save.

Hide unsupported edit/delete UI and block the edit route.

Add regression tests for disabled actions.

* docs(env): document VITE_API_URL must include /api suffix

* refactor(api): extract shared API prefix URL resolution

* feat(build): fail build on misconfigured absolute VITE_API_URL

* test(api): cover API URL contract and prefix resolution

* feat(auth): disable login submit until email and password are valid

* test(auth): align login tests with disabled submit behavior

* Feat/ab/menu-and-header (#17)

* chore(deps): add lucide-react for layout icon migration

* feat(auth): add getPrimaryUserRole helper for header display

* style(theme): add sidebar active tokens and nav group typography

* refactor(menu): migrate nav icons to lucide and trim menu groups

* feat(layout): redesign sidebar, topbar, and admin shell viewport

* chore(menu): hide Reports and Documents from sidebar

---------

Co-authored-by: Arthur Bassi <arthur.winiarski.ranger@outlook.com>

* ci: add frontend PR quality baseline (#18)

* chore(deps): add lucide-react for layout icon migration

* feat(auth): add getPrimaryUserRole helper for header display

* style(theme): add sidebar active tokens and nav group typography

* refactor(menu): migrate nav icons to lucide and trim menu groups

* feat(layout): redesign sidebar, topbar, and admin shell viewport

* chore(menu): hide Reports and Documents from sidebar

* ci: add PR quality baseline checks

* ci: avoid self-matching standards guard

* ci: split frontend quality gates

---------

Co-authored-by: Arthur Bassi <arthur.winiarski.ranger@outlook.com>

---------

Co-authored-by: Arthur Bassi <arthur.winiarski.ranger@outlook.com>
Co-authored-by: Alexandre Brandizzi <alex_brandizzi@hotmail.com>
2026-06-18 14:41:17 -03:00

268 lines
8.6 KiB
TypeScript

import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
import type { WorkOrderFormSchemaValues } from "@/domain/work-orders/schemas/work-order-schema";
import type {
DispatchComment,
DispatchSignoff,
DispatchToVendorPayload,
UpdateDispatchPayload,
WorkOrderComment,
WorkOrderDetail,
WorkOrderFormValues,
} from "@/domain/work-orders/types/work-order";
import { queryKeys } from "@/infra/query-key/query-key";
function invalidateWorkOrders(queryClient: ReturnType<typeof useQueryClient>) {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.all });
}
interface AddWorkOrderCommentInput {
text: string;
commentType: string;
}
interface ChangeWorkOrderAssignmentInput {
userId: string | number;
userName: string;
}
interface AddDispatchCommentInput {
text: string;
sendEmail: boolean;
}
interface UpdateChecklistItemInput {
itemId: string | number;
isCompleted: boolean;
completedBy: string;
}
interface AddDispatchSignoffInput {
signoffType: string;
name: string;
signature: string;
signatureMethod: string;
}
export function useCreateWorkOrder(): UseMutationResult<
WorkOrderDetail,
Error,
WorkOrderFormSchemaValues | WorkOrderFormValues
> {
const queryClient = useQueryClient();
const navigate = useNavigate();
return useMutation({
mutationFn: (values: WorkOrderFormSchemaValues | WorkOrderFormValues) =>
workOrdersApi.create(values),
onSuccess: (data) => {
invalidateWorkOrders(queryClient);
toast.success("Work Order created successfully!");
navigate(`/workorders/${data.id}`);
},
onError: (error: Error) => {
toast.error(error.message || "Failed to create work order");
},
});
}
export function useUpdateWorkOrder(
id: string | number,
): UseMutationResult<WorkOrderDetail, Error, WorkOrderFormSchemaValues | WorkOrderFormValues> {
const queryClient = useQueryClient();
const navigate = useNavigate();
return useMutation({
mutationFn: (values: WorkOrderFormSchemaValues | WorkOrderFormValues) =>
workOrdersApi.update(id, values),
onSuccess: () => {
invalidateWorkOrders(queryClient);
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(id) });
toast.success("Work Order updated successfully!");
navigate(`/workorders/${id}`);
},
onError: (error: Error) => {
toast.error(error.message || "Failed to update work order");
},
});
}
export function useAddWorkOrderComment(
workOrderId: string | number,
): UseMutationResult<WorkOrderComment, Error, AddWorkOrderCommentInput> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ text, commentType }: AddWorkOrderCommentInput) =>
workOrdersApi.addComment(workOrderId, text, commentType),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
},
onError: (error: Error) => {
toast.error(error.message || "Failed to add comment");
},
});
}
export function useChangeWorkOrderStatus(
workOrderId: string | number,
): UseMutationResult<void, Error, string> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (status: string) => workOrdersApi.changeStatus(workOrderId, status),
onSuccess: (_data, status) => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
invalidateWorkOrders(queryClient);
toast.success(`Status changed to ${status}`);
},
onError: (error: Error) => {
toast.error(error.message || "Failed to update status");
},
});
}
export function useChangeWorkOrderAssignment(
workOrderId: string | number,
): UseMutationResult<string, Error, ChangeWorkOrderAssignmentInput> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ userId, userName }: ChangeWorkOrderAssignmentInput) =>
workOrdersApi.changeAssignment(workOrderId, userId).then(() => userName),
onSuccess: (userName) => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
invalidateWorkOrders(queryClient);
toast.success(`Assigned to ${userName || "Unassigned"}`);
},
onError: (error: Error) => {
toast.error(error.message || "Failed to update assignment");
},
});
}
export function useDispatchToVendor(
workOrderId: string | number,
): UseMutationResult<void, Error, DispatchToVendorPayload> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: workOrdersApi.dispatchToVendor,
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
invalidateWorkOrders(queryClient);
toast.success("Dispatched successfully");
},
onError: (error: Error) => {
toast.error(error.message || "Failed to dispatch");
},
});
}
export function useUpdateDispatch(
dispatchId: string | number,
workOrderId: string | number,
): UseMutationResult<void, Error, UpdateDispatchPayload> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: workOrdersApi.updateDispatch,
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
toast.success("Dispatch updated");
},
onError: (error: Error) => {
toast.error(error.message || "Failed to update dispatch");
},
});
}
export function useAddDispatchComment(
dispatchId: string | number,
): UseMutationResult<DispatchComment, Error, AddDispatchCommentInput> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ text, sendEmail }: AddDispatchCommentInput) =>
workOrdersApi.addDispatchComment(dispatchId, text, sendEmail),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
},
onError: (error: Error) => {
toast.error(error.message || "Failed to send message");
},
});
}
export function useUpdateChecklistItem(
dispatchId: string | number,
): UseMutationResult<void, Error, UpdateChecklistItemInput> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ itemId, isCompleted, completedBy }: UpdateChecklistItemInput) =>
workOrdersApi.updateChecklistItem(itemId, isCompleted, completedBy),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
},
onError: (error: Error) => {
toast.error(error.message || "Failed to update checklist item");
},
});
}
export function useAddChecklistItem(
dispatchId: string | number,
): UseMutationResult<void, Error, string> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (itemText: string) => workOrdersApi.addChecklistItem(dispatchId, itemText),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
},
onError: (error: Error) => {
toast.error(error.message || "Failed to add checklist item");
},
});
}
export function useAddDispatchSignoff(
dispatchId: string | number,
): UseMutationResult<DispatchSignoff, Error, AddDispatchSignoffInput> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ signoffType, name, signature, signatureMethod }: AddDispatchSignoffInput) =>
workOrdersApi.addDispatchSignoff(dispatchId, signoffType, name, signature, signatureMethod),
onSuccess: (_data, variables) => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
toast.success(`${variables.signoffType} sign-off collected`);
},
onError: (error: Error) => {
toast.error(error.message || "Failed to save sign-off");
},
});
}
export function useVerifyDispatch(
dispatchId: string | number,
workOrderId: string | number,
): UseMutationResult<void, Error, void> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: () => workOrdersApi.verifyDispatch(dispatchId),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.dispatch(dispatchId) });
void queryClient.invalidateQueries({ queryKey: queryKeys.workOrders.detail(workOrderId) });
toast.success("Dispatch verified");
},
onError: (error: Error) => {
toast.error(error.message || "Failed to verify");
},
});
}