Manage errors

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2025-10-29 14:03:50 +01:00
parent 55743cbb5c
commit 9a33f7b771
84 changed files with 1483 additions and 331 deletions

View File

@@ -68,6 +68,20 @@ export function PageError({ resetErrorBoundary, error: propsError }: Props) {
);
}
if (error && error.toString().includes("UNAUTHORIZED")) {
return (
<div className={classNames.wrapper}>
<h1 className={classNames.title}>
<IconPageCross size={26} />
{__("Access denied")}
</h1>
<p className={classNames.description}>
{__("You don't have permission to access this organization")}
</p>
</div>
);
}
return (
<div className={classNames.wrapper}>
<h1 className={classNames.title}>{__("Unexpected error :(")}</h1>

View File

@@ -69,13 +69,28 @@ export const taskUpdateMutation = graphql`
}
`;
const schema = z.object({
name: z.string(),
const createTaskSchema = z.object({
name: z.string().min(1),
description: z.string(),
timeEstimate: z.string().nullable(),
assignedToId: z.string(),
measureId: z.string(),
deadline: z.string().optional(),
timeEstimate: z.string().optional().nullable(),
assignedToId: z.preprocess(
(val) => (val === "" || val == null ? undefined : val),
z.string({ required_error: "Assigned to is required" }).min(1, "Assigned to is required")
),
measureId: z.preprocess(
(val) => (val === "" || val == null ? undefined : val),
z.string({ required_error: "Measure is required" }).min(1, "Measure is required")
),
deadline: z.string().optional().nullable(),
});
const updateTaskSchema = z.object({
name: z.string().min(1),
description: z.string(),
timeEstimate: z.string().optional().nullable(),
assignedToId: z.string().optional(),
measureId: z.string().optional(),
deadline: z.string().optional().nullable(),
});
type Props = {
@@ -95,15 +110,17 @@ export default function TaskFormDialog(props: Props) {
const [mutate] = task
? useMutationWithToasts(taskUpdateMutation, {
successMessage: __("Task updated successfully."),
errorMessage: __("Failed to update task. Please try again."),
errorMessage: __("Failed to update task"),
})
: useMutationWithToasts(taskCreateMutation, {
successMessage: __("Task created successfully."),
errorMessage: __("Failed to create task. Please try again."),
errorMessage: __("Failed to create task"),
});
const isUpdating = !!task;
const { control, handleSubmit, register, formState, reset } =
useFormWithSchema(schema, {
useFormWithSchema(isUpdating ? updateTaskSchema : createTaskSchema, {
defaultValues: {
name: task?.name ?? "",
description: task?.description ?? "",
@@ -142,7 +159,7 @@ export default function TaskFormDialog(props: Props) {
connections: [props.connection!],
},
onCompleted: (_response, errors) => {
if (!errors) {
if (!errors && data.measureId) {
updateStoreCounter(relayEnv, data.measureId, "tasks(first:0)", 1);
}
},
@@ -151,7 +168,6 @@ export default function TaskFormDialog(props: Props) {
}
dialogRef.current?.close();
});
const isUpdating = !!task;
const showMeasure = !props.measureId && !isUpdating;
const isCreating = !isUpdating;
@@ -217,9 +233,10 @@ export default function TaskFormDialog(props: Props) {
<Controller
name="timeEstimate"
control={control}
render={({ field: { onChange, ...field } }) => (
render={({ field: { onChange, value, ...field } }) => (
<DurationPicker
{...field}
value={value ?? null}
onValueChange={(value) => onChange(value)}
/>
)}

View File

@@ -2,9 +2,9 @@ import { z } from "zod";
import { useFormWithSchema } from "../useFormWithSchema";
export const documentSchema = z.object({
title: z.string(),
content: z.string(),
ownerId: z.string(),
title: z.string().min(1, "Title is required"),
content: z.string().min(1, "Content is required"),
ownerId: z.string().min(1, "Owner is required"),
documentType: z.enum(["OTHER", "ISMS", "POLICY", "PROCEDURE"]),
classification: z.enum(["PUBLIC", "INTERNAL", "CONFIDENTIAL", "SECRET"]),
});

View File

@@ -32,10 +32,10 @@ export type RiskKey = useRiskFormFragment$key & { id: string };
// Export the schema so it can be used elsewhere
export const riskSchema = z.object({
category: z.string(),
name: z.string(),
description: z.string(),
ownerId: z.string(),
category: z.string().min(1, "Category is required"),
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
ownerId: z.string().min(1, "Owner is required"),
treatment: z.enum(["AVOIDED", "MITIGATED", "TRANSFERRED", "ACCEPTED"]),
inherentLikelihood: z.number({ coerce: true }).min(1).max(5),
inherentImpact: z.number({ coerce: true }).min(1).max(5),

View File

@@ -8,21 +8,21 @@ import { useTranslate } from "@probo/i18n";
import { useEffect, useMemo } from "react";
const schema = z.object({
name: z.string(),
description: z.string(),
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
category: z.string().nullish(),
statusPageUrl: z.string(),
termsOfServiceUrl: z.string(),
privacyPolicyUrl: z.string(),
serviceLevelAgreementUrl: z.string(),
dataProcessingAgreementUrl: z.string(),
websiteUrl: z.string(),
legalName: z.string(),
headquarterAddress: z.string(),
statusPageUrl: z.string().optional(),
termsOfServiceUrl: z.string().optional(),
privacyPolicyUrl: z.string().optional(),
serviceLevelAgreementUrl: z.string().optional(),
dataProcessingAgreementUrl: z.string().optional(),
websiteUrl: z.string().optional(),
legalName: z.string().optional(),
headquarterAddress: z.string().optional(),
certifications: z.array(z.string()),
countries: z.array(z.string()),
securityPageUrl: z.string(),
trustPageUrl: z.string(),
securityPageUrl: z.string().optional(),
trustPageUrl: z.string().optional(),
businessOwnerId: z.string().nullish(),
securityOwnerId: z.string().nullish(),
});
@@ -70,7 +70,7 @@ export function useVendorForm(vendorKey: useVendorFormFragment$key) {
const [mutate] = useMutationWithToasts(vendorUpdateQuery, {
successMessage: __("Vendor updated successfully."),
errorMessage: __("Failed to update vendor. Please try again."),
errorMessage: __("Failed to update vendor"),
});
const defaultValues = useMemo(

View File

@@ -34,7 +34,7 @@ export function useDeleteDocumentMutation() {
deleteDocumentMutation,
{
successMessage: __("Document deleted successfully."),
errorMessage: __("Failed to delete document. Please try again."),
errorMessage: __("Failed to delete document"),
}
);
}
@@ -57,7 +57,7 @@ export function useDeleteDraftDocumentVersionMutation() {
deleteDraftDocumentVersionMutation,
{
successMessage: __("Draft deleted successfully."),
errorMessage: __("Failed to delete draft. Please try again."),
errorMessage: __("Failed to delete draft"),
}
);
}
@@ -79,7 +79,7 @@ export function useBulkDeleteDocumentsMutation() {
bulkDeleteDocumentsMutation,
{
successMessage: __("Documents deleted successfully."),
errorMessage: __("Failed to delete documents. Please try again."),
errorMessage: __("Failed to delete documents"),
}
);
}
@@ -101,7 +101,7 @@ export function useSendSigningNotificationsMutation() {
sendSigningNotificationsMutation,
{
successMessage: __("Signing notifications sent successfully."),
errorMessage: __("Failed to send signing notifications. Please try again."),
errorMessage: __("Failed to send signing notifications"),
}
);
}
@@ -123,7 +123,7 @@ export function useBulkExportDocumentsMutation() {
bulkExportDocumentsMutation,
{
successMessage: __("Document export started successfully. You will receive an email when the export is ready."),
errorMessage: __("Failed to start document export. Please try again."),
errorMessage: __("Failed to start document export"),
}
);
}

View File

@@ -32,7 +32,7 @@ export function useDeleteMeasureMutation() {
deleteMeasureMutation,
{
successMessage: __("Measure deleted successfully."),
errorMessage: __("Failed to delete measure. Please try again."),
errorMessage: __("Failed to delete measure"),
}
);
}
@@ -83,6 +83,6 @@ export const useUpdateMeasure = () => {
return useMutationWithToasts(measureUpdateMutation, {
successMessage: __("Measure updated successfully."),
errorMessage: __("Failed to update measure. Please try again."),
errorMessage: __("Failed to update measure"),
});
};

View File

@@ -33,7 +33,7 @@ export function useDeleteOrganizationMutation() {
deleteOrganizationMutation,
{
successMessage: __("Organization deleted successfully."),
errorMessage: __("Failed to delete organization. Please try again."),
errorMessage: __("Failed to delete organization"),
}
);
}

View File

@@ -10,9 +10,9 @@ import {
import { useMemo } from "react";
import type { PeopleGraphPaginatedQuery } from "./__generated__/PeopleGraphPaginatedQuery.graphql";
import type { PeopleGraphPaginatedFragment$key } from "./__generated__/PeopleGraphPaginatedFragment.graphql";
import { useConfirm } from "@probo/ui";
import { useConfirm, useToast } from "@probo/ui";
import type { PeopleGraphDeleteMutation } from "./__generated__/PeopleGraphDeleteMutation.graphql";
import { promisifyMutation, sprintf } from "@probo/helpers";
import { promisifyMutation, sprintf, formatError, type GraphQLError } from "@probo/helpers";
import { useTranslate } from "@probo/i18n";
const peopleQuery = graphql`
@@ -132,6 +132,7 @@ export const useDeletePeople = (
) => {
const [mutate] = useMutation<PeopleGraphDeleteMutation>(deletePeopleMutation);
const confirm = useConfirm();
const { toast } = useToast();
const { __ } = useTranslate();
return () => {
@@ -147,6 +148,12 @@ export const useDeletePeople = (
},
connections: [connectionId],
},
}).catch((error) => {
toast({
title: __("Error"),
description: formatError(__("Failed to delete people"), error as GraphQLError),
variant: "error",
});
}),
{
message: sprintf(

View File

@@ -26,7 +26,7 @@ export function useDeleteRiskMutation() {
return useMutationWithToasts<RiskGraphDeleteMutation>(deleteRiskMutation, {
successMessage: __("Risk deleted successfully."),
errorMessage: __("Failed to delete risk. Please try again."),
errorMessage: __("Failed to delete risk"),
});
}

View File

@@ -137,7 +137,7 @@ export function useCreateSAMLConfigurationMutation() {
createSAMLConfigurationMutation,
{
successMessage: "SAML configuration created successfully.",
errorMessage: "Failed to create SAML configuration. Please try again.",
errorMessage: "Failed to create SAML configuration",
}
);
}

View File

@@ -22,7 +22,7 @@ export function useTrustCenterAuditUpdate() {
trustCenterAuditUpdateMutation,
{
successMessage: __("Audit visibility updated successfully."),
errorMessage: __("Failed to update audit visibility. Please try again."),
errorMessage: __("Failed to update audit visibility"),
}
);
}

View File

@@ -40,7 +40,7 @@ export function useUpdateDocumentVisibilityMutation() {
updateDocumentVisibilityMutation,
{
successMessage: __("Document visibility updated successfully."),
errorMessage: __("Failed to update document visibility. Please try again."),
errorMessage: __("Failed to update document visibility"),
}
);
}

View File

@@ -22,7 +22,7 @@ export function useTrustCenterVendorUpdate() {
trustCenterVendorUpdateMutation,
{
successMessage: __("Vendor visibility updated successfully."),
errorMessage: __("Failed to update vendor visibility. Please try again."),
errorMessage: __("Failed to update vendor visibility"),
}
);
}

View File

@@ -36,7 +36,7 @@ export function useCreateVendorMutation() {
createVendorMutation,
{
successMessage: __("Vendor created successfully."),
errorMessage: __("Failed to create vendor. Please try again."),
errorMessage: __("Failed to create vendor"),
}
);
}

View File

@@ -10,6 +10,9 @@ import {
type GraphQLTaggedNode,
type MutationParameters,
} from "relay-runtime";
import { useToast } from "@probo/ui";
import { useTranslate } from "@probo/i18n";
import { formatError, type GraphQLError } from "@probo/helpers";
const defaultOptions = {
field: "totalCount",
@@ -26,17 +29,27 @@ export function useMutationWithIncrement<T extends MutationParameters>(
node: string;
field?: string;
value?: 1 | -1;
errorMessage?: string;
},
) {
const [mutate, isLoading] = useMutation<T>(query);
const relayEnv = useRelayEnvironment();
const { toast } = useToast();
const { __ } = useTranslate();
const options = { ...defaultOptions, ...baseOptions };
const mutateAndIncrement = useCallback(
(queryOptions: UseMutationConfig<T>) => {
return mutate({
...queryOptions,
onCompleted: (response, error) => {
if (!error) {
if (error) {
const errorTitle = options.errorMessage ?? __("Failed to commit this operation");
toast({
title: __("Error"),
description: formatError(errorTitle, error as GraphQLError[]),
variant: "error",
});
} else {
updateStoreCounter(
relayEnv,
options.id,
@@ -47,9 +60,18 @@ export function useMutationWithIncrement<T extends MutationParameters>(
}
queryOptions.onCompleted?.(response, error);
},
onError: (error) => {
const errorTitle = options.errorMessage ?? __("Failed to commit this operation");
toast({
title: __("Error"),
description: formatError(errorTitle, error as GraphQLError),
variant: "error",
});
queryOptions.onError?.(error);
},
});
},
[mutate, options.id, options.node, options.field, options.value, relayEnv],
[mutate, options.id, options.node, options.field, options.value, options.errorMessage, relayEnv, toast, __],
);
return [mutateAndIncrement, isLoading] as const;

View File

@@ -3,6 +3,7 @@ import { useMutation, type UseMutationConfig } from "react-relay";
import { useToast } from "@probo/ui";
import { useTranslate } from "@probo/i18n";
import type { MutationParameters, GraphQLTaggedNode } from "relay-runtime";
import { formatError, type GraphQLError } from "@probo/helpers";
/**
* A decorated useMutation hook that emits toast notifications on success or error.
@@ -32,11 +33,10 @@ export function useMutationWithToasts<T extends MutationParameters>(
onCompleted: (response, error) => {
options.onCompleted?.(response, error);
if (error) {
const errorTitle = options.errorMessage ?? __("Failed to commit this operation");
toast({
title: __("Error"),
description:
options.errorMessage ??
__("Failed to commit this operation."),
description: formatError(errorTitle, error as GraphQLError[]),
variant: "error",
});
reject(error);
@@ -57,10 +57,10 @@ export function useMutationWithToasts<T extends MutationParameters>(
resolve();
},
onError: (error) => {
const errorTitle = options.errorMessage ?? __("Failed to commit this operation");
toast({
title: __("Error"),
description:
options.errorMessage ?? __("Failed to commit this operation."),
description: formatError(errorTitle, error as GraphQLError),
variant: "error",
});
reject(error);

View File

@@ -81,7 +81,7 @@ export default function ConfirmEmailPage() {
onError: (err) => {
toast({
title: __("Error"),
description: err.message || __("Failed to confirm email. Please try again."),
description: err.message || __("Failed to confirm email"),
variant: "error",
});
setIsLoading(false);
@@ -90,7 +90,7 @@ export default function ConfirmEmailPage() {
} catch (error) {
toast({
title: __("Error"),
description: error instanceof Error ? error.message : __("Failed to confirm email. Please try again."),
description: error instanceof Error ? error.message : __("Failed to confirm email"),
variant: "error",
});
setIsLoading(false);

View File

@@ -6,6 +6,7 @@ import type { NewOrganizationPageQuery as NewOrganizationPageQueryType } from ".
import type { NewOrganizationPageMutation as NewOrganizationPageMutationType } from "./__generated__/NewOrganizationPageMutation.graphql";
import { useState, type FormEventHandler } from "react";
import { useNavigate } from "react-router";
import { formatError, type GraphQLError } from "@probo/helpers";
const createOrganizationMutation = graphql`
mutation NewOrganizationPageMutation(
@@ -75,11 +76,12 @@ export default function NewOrganizationPage() {
variant: "success",
});
},
onError: (e) => {
onError: (e: GraphQLError) => {
setIsFetching(false);
toast({
title: __("Error"),
description: e.message ?? __("Failed to create organization"),
description: formatError(__("Failed to create organization"), e),
variant: "error",
});
},

View File

@@ -32,7 +32,7 @@ import { FrameworkLogo } from "/components/FrameworkLogo";
import { ControlledField } from "/components/form/ControlledField";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import z from "zod";
import { getAuditStateLabel, getAuditStateVariant, auditStates, fileSize, sprintf, formatDatetime, formatDate } from "@probo/helpers";
import { getAuditStateLabel, getAuditStateVariant, auditStates, fileSize, sprintf, formatDatetime, formatError, formatDate, type GraphQLError } from "@probo/helpers";
import type { AuditGraphNodeQuery } from "/hooks/graph/__generated__/AuditGraphNodeQuery.graphql";
const updateAuditSchema = z.object({
@@ -96,7 +96,7 @@ export default function AuditDetailsPage(props: Props) {
} catch (error) {
toast({
title: __("Error"),
description: error instanceof Error ? error.message : __("Failed to update audit"),
description: formatError(__("Failed to update audit"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -16,7 +16,7 @@ import z from "zod";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { ControlledField } from "/components/form/ControlledField";
import { useCreateAudit } from "/hooks/graph/AuditGraph";
import { auditStates, getAuditStateLabel, formatDatetime } from "@probo/helpers";
import { auditStates, getAuditStateLabel, formatDatetime, formatError, type GraphQLError } from "@probo/helpers";
import { useLazyLoadQuery } from "react-relay";
import { graphql } from "relay-runtime";
import { Suspense } from "react";
@@ -94,7 +94,7 @@ export function CreateAuditDialog({
} catch (error) {
toast({
title: __("Error"),
description: error instanceof Error ? error.message : __("Failed to create audit"),
description: formatError(__("Failed to create audit"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -30,6 +30,7 @@ import { useOrganizationId } from "/hooks/useOrganizationId";
import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import z from "zod";
import { getStatusVariant, getStatusLabel, formatDatetime, validateSnapshotConsistency } from "@probo/helpers";
import { SnapshotBanner } from "/components/SnapshotBanner";
@@ -113,7 +114,7 @@ export default function ContinualImprovementDetailsPage(props: Props) {
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to update continual improvement entry"),
description: formatError(__("Failed to update continual improvement"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -20,6 +20,7 @@ import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { useCreateContinualImprovement } from "../../../../hooks/graph/ContinualImprovementGraph";
import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import { formatDatetime } from "@probo/helpers";
const schema = z.object({
@@ -87,7 +88,7 @@ export function CreateContinualImprovementDialog({
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to create continual improvement entry"),
description: formatError(__("Failed to create continual improvement"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -245,7 +245,7 @@ export default function DocumentDetailPage(props: Props) {
publishDocumentVersionMutation,
{
successMessage: __("Document published successfully."),
errorMessage: __("Failed to publish document. Please try again."),
errorMessage: __("Failed to publish document"),
}
);
const [deleteDocument, isDeleting] = useDeleteDocumentMutation();
@@ -256,23 +256,19 @@ export default function DocumentDetailPage(props: Props) {
exportDocumentVersionPDFMutation,
{
successMessage: __("PDF download started."),
errorMessage: __("Failed to generate PDF. Please try again."),
errorMessage: __("Failed to generate PDF"),
}
);
const userEmailData = useLazyLoadQuery<DocumentDetailPageUserEmailQuery>(
UserEmailQuery,
{}
);
const userEmailData = useLazyLoadQuery<DocumentDetailPageUserEmailQuery>(UserEmailQuery, {});
const defaultEmail = userEmailData.viewer.user.email;
const [updateDocument, isUpdatingDocument] =
useMutationWithToasts<DocumentDetailPageUpdateMutation>(
updateDocumentMutation,
{
successMessage: __("Document updated successfully."),
errorMessage: __("Failed to update document. Please try again."),
}
);
const [updateDocument, isUpdatingDocument] = useMutationWithToasts<DocumentDetailPageUpdateMutation>(
updateDocumentMutation,
{
successMessage: __("Document updated successfully."),
errorMessage: __("Failed to update document"),
}
);
const versionConnectionId = document.versions.__id;
const { register, control, handleSubmit, reset } = useFormWithSchema(

View File

@@ -67,7 +67,7 @@ export function CreateDocumentDialog({ trigger, connection }: Props) {
connections: [connection!],
},
successMessage: __("Document created successfully."),
errorMessage: __("Failed to create document. Please try again."),
errorMessage: __("Failed to create document"),
onSuccess: () => {
dialogRef.current?.close();
reset();

View File

@@ -89,7 +89,7 @@ export default function UpdateVersionDialog({
UpdateDocumentMutation,
{
successMessage: __("Document updated successfully."),
errorMessage: __("Failed to update document. Please try again."),
errorMessage: __("Failed to update document"),
}
);
const { handleSubmit, register } = useFormWithSchema(versionSchema, {

View File

@@ -78,6 +78,7 @@ export default function DocumentControlsTab() {
{
...incrementOptions,
value: -1,
errorMessage: "Failed to unlink control",
},
);
const [attachControl, isAttaching] = useMutationWithIncrement(
@@ -85,6 +86,7 @@ export default function DocumentControlsTab() {
{
...incrementOptions,
value: 1,
errorMessage: "Failed to link control",
},
);
const isLoading = isDetaching || isAttaching;

View File

@@ -2,8 +2,9 @@ import {
useMutation,
usePreloadedQuery,
type PreloadedQuery,
type UseMutationConfig,
} from "react-relay";
import { graphql } from "relay-runtime";
import { graphql, type MutationParameters } from "relay-runtime";
import {
ActionDropdown,
Button,
@@ -11,8 +12,10 @@ import {
IconPencil,
IconTrashCan,
useConfirm,
useToast,
} from "@probo/ui";
import { useTranslate } from "@probo/i18n";
import { formatError, type GraphQLError } from "@probo/helpers";
import { LinkedMeasuresCard } from "/components/measures/LinkedMeasuresCard";
import { useNavigate, useOutletContext } from "react-router";
import { useOrganizationId } from "/hooks/useOrganizationId";
@@ -153,6 +156,7 @@ type Props = {
*/
export default function FrameworkControlPage({ queryRef }: Props) {
const { __ } = useTranslate();
const { toast } = useToast();
const { framework } = useOutletContext<{
framework: FrameworkDetailPageFragment$data;
}>();
@@ -161,25 +165,44 @@ export default function FrameworkControlPage({ queryRef }: Props) {
const organizationId = useOrganizationId();
const confirm = useConfirm();
const navigate = useNavigate();
// Mutations
const [detachMeasure, isDetachingMeasure] = useMutation(
detachMeasureMutation
);
const [attachMeasure, isAttachingMeasure] = useMutation(
attachMeasureMutation
);
const [detachDocument, isDetachingDocument] = useMutation(
detachDocumentMutation
);
const [attachDocument, isAttachingDocument] = useMutation(
attachDocumentMutation
);
const [detachMeasure, isDetachingMeasure] = useMutation(detachMeasureMutation);
const [attachMeasure, isAttachingMeasure] = useMutation(attachMeasureMutation);
const [detachDocument, isDetachingDocument] = useMutation(detachDocumentMutation);
const [attachDocument, isAttachingDocument] = useMutation(attachDocumentMutation);
const [detachAudit, isDetachingAudit] = useMutation(detachAuditMutation);
const [attachAudit, isAttachingAudit] = useMutation(attachAuditMutation);
const [detachSnapshot, isDetachingSnapshot] = useMutation(detachSnapshotMutation);
const [attachSnapshot, isAttachingSnapshot] = useMutation(attachSnapshotMutation);
const [deleteControl] = useMutation(deleteControlMutation);
const withErrorHandling = <T extends MutationParameters>(
mutationFn: (config: UseMutationConfig<T>) => void,
errorMessage: string
) => (options: UseMutationConfig<T>) => {
mutationFn({
...options,
onCompleted: (response, error) => {
if (error) {
toast({
title: __("Error"),
description: formatError(errorMessage, error as GraphQLError),
variant: "error",
});
}
options.onCompleted?.(response, error);
},
onError: (error) => {
toast({
title: __("Error"),
description: formatError(errorMessage, error as GraphQLError),
variant: "error",
});
options.onError?.(error);
},
});
};
const onDelete = () => {
confirm(
() => {
@@ -253,8 +276,8 @@ export default function FrameworkControlPage({ queryRef }: Props) {
measures={control.measures?.edges.map((edge) => edge.node) ?? []}
params={{ controlId: control.id }}
connectionId={control.measures?.__id!}
onAttach={attachMeasure}
onDetach={detachMeasure}
onAttach={withErrorHandling(attachMeasure, __("Failed to link measure"))}
onDetach={withErrorHandling(detachMeasure, __("Failed to unlink measure"))}
disabled={isAttachingMeasure || isDetachingMeasure}
/>
</div>
@@ -264,8 +287,8 @@ export default function FrameworkControlPage({ queryRef }: Props) {
documents={control.documents?.edges.map((edge) => edge.node) ?? []}
params={{ controlId: control.id }}
connectionId={control.documents?.__id!}
onAttach={attachDocument}
onDetach={detachDocument}
onAttach={withErrorHandling(attachDocument, __("Failed to link document"))}
onDetach={withErrorHandling(detachDocument, __("Failed to unlink document"))}
disabled={isAttachingDocument || isDetachingDocument}
/>
</div>
@@ -275,8 +298,8 @@ export default function FrameworkControlPage({ queryRef }: Props) {
audits={control.audits?.edges.map((edge) => edge.node) ?? []}
params={{ controlId: control.id }}
connectionId={control.audits?.__id!}
onAttach={attachAudit}
onDetach={detachAudit}
onAttach={withErrorHandling(attachAudit, __("Failed to link audit"))}
onDetach={withErrorHandling(detachAudit, __("Failed to unlink audit"))}
disabled={isAttachingAudit || isDetachingAudit}
/>
</div>
@@ -286,8 +309,8 @@ export default function FrameworkControlPage({ queryRef }: Props) {
snapshots={control.snapshots?.edges.map((edge) => edge.node) ?? []}
params={{ controlId: control.id }}
connectionId={control.snapshots?.__id!}
onAttach={attachSnapshot}
onDetach={detachSnapshot}
onAttach={withErrorHandling(attachSnapshot, __("Failed to link snapshot"))}
onDetach={withErrorHandling(detachSnapshot, __("Failed to unlink snapshot"))}
disabled={isAttachingSnapshot || isDetachingSnapshot}
/>
</div>

View File

@@ -86,11 +86,11 @@ export function FrameworkControlDialog(props: Props) {
const [mutate, isMutating] = props.control
? useMutationWithToasts(updateMutation, {
successMessage: __("Control updated successfully."),
errorMessage: __("Failed to update control. Please try again."),
errorMessage: __("Failed to update control"),
})
: useMutationWithToasts(createMutation, {
successMessage: __("Control created successfully."),
errorMessage: __("Failed to create control. Please try again."),
errorMessage: __("Failed to create control"),
});
const defaultValues = useMemo(() => ({

View File

@@ -107,7 +107,7 @@ export default function MeasuresPage(props: Props) {
importMeasuresMutation,
{
successMessage: __("Measures imported successfully."),
errorMessage: __("Failed to import measures. Please try again."),
errorMessage: __("Failed to import measures"),
}
);
const importFileRef = useRef<HTMLInputElement>(null);

View File

@@ -3,11 +3,11 @@ import {
Dialog,
DialogContent,
DialogFooter,
Field,
Input,
Label,
Option,
PropertyRow,
Textarea,
useDialogRef,
type DialogRef,
} from "@probo/ui";
@@ -51,9 +51,9 @@ const measureCreateMutation = graphql`
`;
const measureSchema = z.object({
name: z.string(),
description: z.string(),
category: z.string(),
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
category: z.string().min(1, "Category is required"),
state: z.enum(measureStates),
});
@@ -73,7 +73,7 @@ export default function MeasureFormDialog(props: Props) {
? useUpdateMeasure()
: useMutationWithToasts(measureCreateMutation, {
successMessage: __("Measure created successfully."),
errorMessage: __("Failed to create measure. Please try again."),
errorMessage: __("Failed to create measure"),
});
const { control, handleSubmit, register, formState, reset } =
@@ -131,20 +131,21 @@ export default function MeasureFormDialog(props: Props) {
>
<form onSubmit={onSubmit}>
<DialogContent className="grid grid-cols-[1fr_420px]">
<div className="py-8 px-10 space-y-4">
<Input
id="title"
required
variant="title"
placeholder={__("Measure title")}
<div className="py-8 px-10 space-y-6">
<Field
{...register("name")}
error={formState.errors.name?.message}
label={__("Measure name")}
placeholder={__("Measure title")}
required
/>
<Textarea
id="content"
variant="ghost"
autogrow
placeholder={__("Add description")}
<Field
{...register("description")}
error={formState.errors.description?.message}
label={__("Description")}
placeholder={__("Add description")}
type="textarea"
required
/>
</div>
{/* Properties form */}

View File

@@ -32,7 +32,7 @@ import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { AuditSelectField } from "/components/form/AuditSelectField";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import z from "zod";
import { getStatusVariant, getStatusLabel, formatDatetime, validateSnapshotConsistency, getStatusOptions } from "@probo/helpers";
import { getStatusVariant, getStatusLabel, formatDatetime, validateSnapshotConsistency, getStatusOptions, formatError, type GraphQLError } from "@probo/helpers";
import type { NonconformityGraphNodeQuery } from "/hooks/graph/__generated__/NonconformityGraphNodeQuery.graphql";
const updateNonconformitySchema = z.object({
@@ -121,7 +121,7 @@ export default function NonconformityDetailsPage(props: Props) {
} catch (error) {
toast({
title: __("Error"),
description: error instanceof Error ? error.message : __("Failed to update nonconformity"),
description: formatError(__("Failed to update nonconformity"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -21,6 +21,7 @@ import { useCreateNonconformity } from "../../../../hooks/graph/NonconformityGra
import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { AuditSelectField } from "/components/form/AuditSelectField";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import { formatDatetime, getStatusOptions } from "@probo/helpers";
const schema = z.object({
@@ -98,7 +99,7 @@ export function CreateNonconformityDialog({
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to create nonconformity"),
description: formatError(__("Failed to create nonconformity"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -30,6 +30,7 @@ import { useOrganizationId } from "/hooks/useOrganizationId";
import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import z from "zod";
import { getObligationStatusVariant, getObligationStatusLabel, formatDatetime, getObligationStatusOptions, validateSnapshotConsistency } from "@probo/helpers";
import { SnapshotBanner } from "/components/SnapshotBanner";
@@ -120,10 +121,10 @@ export default function ObligationDetailsPage(props: Props) {
description: __("Obligation updated successfully"),
variant: "success",
});
} catch {
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to update obligation"),
description: formatError(__("Failed to update obligation"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -20,6 +20,7 @@ import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { useCreateObligation } from "../../../../hooks/graph/ObligationGraph";
import { PeopleSelectField } from "/components/form/PeopleSelectField";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import { formatDatetime, getObligationStatusOptions } from "@probo/helpers";
const schema = z.object({
@@ -91,10 +92,10 @@ export function CreateObligationDialog({
reset();
dialogRef.current?.close();
} catch {
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to create obligation"),
description: formatError(__("Failed to create obligation"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -68,7 +68,7 @@ export function CreatePeopleDialog({ children, connectionId }: Props) {
const [mutate, isMutating] = useMutationWithToasts(createPeopleMutation, {
successMessage: __("Person created successfully."),
errorMessage: __("Failed to create person. Please try again."),
errorMessage: __("Failed to create person"),
});
const onSubmit = handleSubmit((data) => {

View File

@@ -45,7 +45,7 @@ export default function PeopleProfileTab() {
updatePeopleMutation,
{
successMessage: __("Member updated successfully."),
errorMessage: __("Failed to update member. Please try again."),
errorMessage: __("Failed to update member"),
}
);

View File

@@ -33,7 +33,7 @@ export default function PeopleRoleTab() {
updatePeopleMutation,
{
successMessage: __("Member updated successfully."),
errorMessage: __("Failed to update member. Please try again."),
errorMessage: __("Failed to update member"),
}
);

View File

@@ -27,6 +27,7 @@ import { useOrganizationId } from "/hooks/useOrganizationId";
import { useParams } from "react-router";
import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { Controller } from "react-hook-form";
import { formatError, type GraphQLError } from "@probo/helpers";
import z from "zod";
import { validateSnapshotConsistency } from "@probo/helpers";
import { SnapshotBanner } from "/components/SnapshotBanner";
@@ -146,7 +147,7 @@ export default function ProcessingActivityDetailsPage(props: Props) {
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to update processing activity"),
description: formatError(__("Failed to update processing activity"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -19,6 +19,7 @@ import { useFormWithSchema } from "/hooks/useFormWithSchema";
import { useCreateProcessingActivity } from "../../../../hooks/graph/ProcessingActivityGraph";
import { Controller } from "react-hook-form";
import { VendorsMultiSelectField } from "/components/form/VendorsMultiSelectField";
import { formatError, type GraphQLError } from "@probo/helpers";
import {
SpecialOrCriminalDataOptions,
LawfulBasisOptions,
@@ -119,7 +120,7 @@ export function CreateProcessingActivityDialog({
} catch (error) {
toast({
title: __("Error"),
description: __("Failed to create processing activity"),
description: formatError(__("Failed to create processing activity"), error as GraphQLError),
variant: "error",
});
}

View File

@@ -113,7 +113,7 @@ export default function FormRiskDialog({
},
},
successMessage: __("Risk updated successfully."),
errorMessage: __("Failed to update risk. Please try again."),
errorMessage: __("Failed to update risk"),
onSuccess: () => {
ref?.current?.close();
},
@@ -129,7 +129,7 @@ export default function FormRiskDialog({
connections: [connection!],
},
successMessage: __("Risk created successfully."),
errorMessage: __("Failed to create risk. Please try again."),
errorMessage: __("Failed to create risk"),
onSuccess: () => {
ref?.current?.close();
reset();

View File

@@ -57,7 +57,7 @@ export default function SnapshotFormDialog(props: Props) {
const organizationId = useOrganizationId();
const [mutate] = useMutationWithToasts(snapshotCreateMutation, {
successMessage: __("Snapshot created successfully."),
errorMessage: __("Failed to create snapshot. Please try again."),
errorMessage: __("Failed to create snapshot"),
});
const { handleSubmit, register, reset, control, formState: { errors } } =

View File

@@ -142,15 +142,15 @@ export default function TrustCenterAccessTab() {
const [createInvitation, isCreating] = useMutationWithToasts(createTrustCenterAccessMutation, {
successMessage: __("Access created successfully"),
errorMessage: __("Failed to create access. Please try again."),
errorMessage: __("Failed to create access"),
});
const [updateInvitation, isUpdating] = useMutationWithToasts(updateTrustCenterAccessMutation, {
successMessage: __("Access updated successfully"),
errorMessage: __("Failed to update access. Please try again."),
errorMessage: __("Failed to update access"),
});
const [deleteInvitation, isDeleting] = useMutationWithToasts(deleteTrustCenterAccessMutation, {
successMessage: __("Access deleted successfully"),
errorMessage: __("Failed to delete access. Please try again."),
errorMessage: __("Failed to delete access"),
});
const dialogRef = useDialogRef();

View File

@@ -47,8 +47,8 @@ export function CreateContactDialog({
const schema = z.object({
fullName: z.string().optional(),
email: z.string().email(__("Please enter a valid email address")).optional().or(z.literal("")),
phone: z.string().regex(phoneRegex, __("Phone number must be in international format (e.g., +1234567890)")).optional().or(z.literal("")),
email: z.union([z.string().email(__("Please enter a valid email address")), z.literal("")]),
phone: z.union([z.string().regex(phoneRegex, __("Phone number must be in international format (e.g., +1234567890)")), z.literal("")]),
role: z.string().optional(),
});
@@ -67,7 +67,7 @@ export function CreateContactDialog({
createContactMutation,
{
successMessage: __("Contact created successfully."),
errorMessage: __("Failed to create contact. Please try again."),
errorMessage: __("Failed to create contact"),
}
);

View File

@@ -65,7 +65,7 @@ export function CreateRiskAssessmentDialog({
createRiskAssessmentMutation,
{
successMessage: __("Risk Assessment created successfully."),
errorMessage: __("Failed to create Risk Assessment. Please try again."),
errorMessage: __("Failed to create Risk Assessment"),
}
);

View File

@@ -61,7 +61,7 @@ export function CreateServiceDialog({
createServiceMutation,
{
successMessage: __("Service created successfully."),
errorMessage: __("Failed to create service. Please try again."),
errorMessage: __("Failed to create service"),
}
);

View File

@@ -43,8 +43,8 @@ export function EditContactDialog({ contactId, contact, onClose }: Props) {
const schema = z.object({
fullName: z.string().optional(),
email: z.string().email(__("Please enter a valid email address")).optional().or(z.literal("")),
phone: z.string().regex(phoneRegex, __("Phone number must be in international format (e.g., +1234567890)")).optional().or(z.literal("")),
email: z.union([z.string().email(__("Please enter a valid email address")), z.literal("")]),
phone: z.union([z.string().regex(phoneRegex, __("Phone number must be in international format (e.g., +1234567890)")), z.literal("")]),
role: z.string().optional(),
});
@@ -64,7 +64,7 @@ export function EditContactDialog({ contactId, contact, onClose }: Props) {
updateContactMutation,
{
successMessage: __("Contact updated successfully."),
errorMessage: __("Failed to update contact. Please try again."),
errorMessage: __("Failed to update contact"),
}
);

View File

@@ -56,7 +56,7 @@ export function EditServiceDialog({ serviceId, service, onClose }: Props) {
updateServiceMutation,
{
successMessage: __("Service updated successfully."),
errorMessage: __("Failed to update service. Please try again."),
errorMessage: __("Failed to update service"),
}
);

View File

@@ -52,7 +52,7 @@ export function ImportAssessmentDialog({ vendorId, children }: Props) {
importAssessmentMutation,
{
successMessage: __("Vendor assessed successfully."),
errorMessage: __("Failed to assess vendor. Please try again."),
errorMessage: __("Failed to assess vendor"),
}
);

View File

@@ -44,6 +44,13 @@ export class AuthenticationRequiredError extends Error {
}
}
export class UnauthorizedError extends Error {
constructor() {
super("UNAUTHORIZED");
this.name = "UnauthorizedError";
}
}
export function buildEndpoint(path: string): string {
const host = import.meta.env.VITE_API_URL;
@@ -71,6 +78,9 @@ const hasUnauthenticatedError = (error: GraphQLError) =>
const hasAuthenticationRequiredError = (error: GraphQLError) =>
error.extensions?.code == "AUTHENTICATION_REQUIRED";
const hasUnauthorizedError = (error: GraphQLError) =>
error.extensions?.code == "UNAUTHORIZED";
const fetchRelay: FetchFunction = async (
request,
variables,
@@ -141,12 +151,10 @@ const fetchRelay: FetchFunction = async (
throw new UnAuthenticatedError();
}
// Check for authentication required errors
const authRequiredError = errors.find(hasAuthenticationRequiredError);
if (authRequiredError?.extensions) {
const { redirectUrl, requiresSaml, organizationId, samlConfigId } = authRequiredError.extensions;
// Throw the error with all the redirect information
throw new AuthenticationRequiredError({
redirectUrl: redirectUrl as string,
requiresSaml: requiresSaml as boolean,
@@ -155,13 +163,9 @@ const fetchRelay: FetchFunction = async (
});
}
throw new Error(
`Error fetching GraphQL query '${
request.name
}' with variables '${JSON.stringify(variables)}': ${JSON.stringify(
json.errors
)}`
);
if (errors.find(hasUnauthorizedError)) {
throw new UnauthorizedError();
}
}
return json;

View File

@@ -12,6 +12,7 @@ import { Fragment, Suspense } from "react";
import {
relayEnvironment,
UnAuthenticatedError,
UnauthorizedError,
} from "./providers/RelayProviders";
import { PageSkeleton } from "./components/skeletons/PageSkeleton.tsx";
import { loadQuery, type PreloadedQuery } from "react-relay";
@@ -53,6 +54,10 @@ function ErrorBoundary({ error: propsError }: { error?: string }) {
return <Navigate to="/auth/login" />;
}
if (error instanceof UnauthorizedError) {
return <PageError error="UNAUTHORIZED" />;
}
return <PageError error={error?.toString()} />;
}

View File

@@ -0,0 +1,26 @@
export interface GraphQLError {
message?: string;
source?: {
errors?: Array<{ message: string }>;
};
}
export function formatError(title: string, error: GraphQLError | GraphQLError[]): string {
const messages: string[] = [];
if (Array.isArray(error)) {
messages.push(...error.map((e) => e.message).filter(Boolean) as string[]);
} else if (error.source?.errors && Array.isArray(error.source.errors)) {
messages.push(...error.source.errors.map((e) => e.message).filter(Boolean));
} else if (error.message) {
messages.push(error.message);
}
if (messages.length === 0) {
return title;
}
const errorList = messages.join(", ");
return `${title}: ${errorList}${errorList.endsWith('.') ? '' : '.'}`;
}

View File

@@ -59,3 +59,4 @@ export { promisifyMutation } from "./relay";
export { fileType, fileSize } from "./file";
export { formatDatetime, formatDate } from "./date";
export { getLogoUrl, getTrustCenterUrl } from "./trustCenter";
export { formatError, type GraphQLError } from "./error";

View File

@@ -12,6 +12,6 @@ type Story = StoryObj<typeof ErrorLayout>;
export const Default: Story = {
args: {
title: "Something went wrong",
description: "An unexpected error occurred. Please try again later.",
description: "An unexpected error occurred",
},
};

View File

@@ -82,10 +82,8 @@ export function ConfirmDialog() {
const handleConfirm = () => {
setLoading(true);
onConfirm()
.then(() => {
close();
})
.finally(() => {
close();
setLoading(false);
});
};

View File

@@ -29,6 +29,14 @@ import (
"go.gearno.de/kit/pg"
)
type TenantAccessError struct {
Message string
}
func (e *TenantAccessError) Error() string {
return "not authorized"
}
type (
Service struct {
pg *pg.Client

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -42,8 +43,24 @@ type (
}
Assets []*Asset
ErrAssetNotFound struct {
Identifier string
}
ErrAssetAlreadyExists struct {
message string
}
)
func (e ErrAssetNotFound) Error() string {
return fmt.Sprintf("asset not found: %q", e.Identifier)
}
func (e ErrAssetAlreadyExists) Error() string {
return e.message
}
func (a *Asset) CursorKey(field AssetOrderField) page.CursorKey {
switch field {
case AssetOrderFieldCreatedAt:
@@ -94,6 +111,10 @@ LIMIT 1;
asset, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Asset])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrAssetNotFound{Identifier: assetID.String()}
}
return fmt.Errorf("cannot collect asset: %w", err)
}
@@ -140,6 +161,10 @@ LIMIT 1;
asset, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Asset])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrAssetNotFound{Identifier: a.OwnerID.String()}
}
return fmt.Errorf("cannot collect asset: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -42,8 +43,24 @@ type (
}
Audits []*Audit
ErrAuditNotFound struct {
Identifier string
}
ErrAuditAlreadyExists struct {
message string
}
)
func (e ErrAuditNotFound) Error() string {
return fmt.Sprintf("audit not found: %q", e.Identifier)
}
func (e ErrAuditAlreadyExists) Error() string {
return e.message
}
func (a *Audit) CursorKey(field AuditOrderField) page.CursorKey {
switch field {
case AuditOrderFieldCreatedAt:
@@ -98,6 +115,10 @@ LIMIT 1;
audit, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Audit])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrAuditNotFound{Identifier: auditID.String()}
}
return fmt.Errorf("cannot collect audit: %w", err)
}
@@ -508,6 +529,10 @@ LIMIT 1;
audit, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Audit])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrAuditNotFound{Identifier: reportID.String()}
}
return fmt.Errorf("cannot collect audit: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -48,8 +50,24 @@ type (
Status *ControlStatus
ExclusionJustification *string
}
ErrControlNotFound struct {
Identifier string
}
ErrControlAlreadyExists struct {
message string
}
)
func (e ErrControlNotFound) Error() string {
return fmt.Sprintf("control not found: %q", e.Identifier)
}
func (e ErrControlAlreadyExists) Error() string {
return e.message
}
func (c Control) CursorKey(orderBy ControlOrderField) page.CursorKey {
switch orderBy {
case ControlOrderFieldCreatedAt:
@@ -628,6 +646,10 @@ LIMIT 1;
control, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Control])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrControlNotFound{Identifier: fmt.Sprintf("%s:%s", frameworkID, sectionTitle)}
}
return fmt.Errorf("cannot collect control: %w", err)
}
@@ -671,6 +693,10 @@ LIMIT 1;
control, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Control])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrControlNotFound{Identifier: controlID.String()}
}
return fmt.Errorf("cannot collect control: %w", err)
}
@@ -725,7 +751,20 @@ VALUES (
"updated_at": c.UpdatedAt,
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "controls_framework_ref_unique" {
return &ErrControlAlreadyExists{
message: fmt.Sprintf("control with framework_id %s and section_title %q already exists", c.FrameworkID, c.SectionTitle),
}
}
}
return fmt.Errorf("cannot insert control: %w", err)
}
return nil
}
func (c Control) Delete(
@@ -810,6 +849,18 @@ RETURNING
control, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Control])
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "controls_framework_ref_unique" {
sectionTitle := ""
if params.SectionTitle != nil {
sectionTitle = *params.SectionTitle
}
return &ErrControlAlreadyExists{
message: fmt.Sprintf("control with section_title %q already exists", sectionTitle),
}
}
}
return fmt.Errorf("cannot collect control: %w", err)
}

View File

@@ -17,6 +17,7 @@ package coredata
import (
"context"
"crypto/tls"
"errors"
"fmt"
"maps"
"time"
@@ -25,6 +26,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -49,8 +51,24 @@ type (
}
CustomDomains []*CustomDomain
ErrCustomDomainNotFound struct {
Identifier string
}
ErrCustomDomainAlreadyExists struct {
message string
}
)
func (e ErrCustomDomainNotFound) Error() string {
return fmt.Sprintf("custom domain not found: %q", e.Identifier)
}
func (e ErrCustomDomainAlreadyExists) Error() string {
return e.message
}
func NewCustomDomain(tenantID gid.TenantID, domain string) *CustomDomain {
now := time.Now()
return &CustomDomain{
@@ -357,6 +375,14 @@ INSERT INTO custom_domains (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "custom_domains_domain_key" {
return &ErrCustomDomainAlreadyExists{
message: fmt.Sprintf("custom domain with domain %q already exists", cd.Domain),
}
}
}
return fmt.Errorf("cannot insert custom domain: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -41,8 +42,24 @@ type (
}
Documents []*Document
ErrDocumentNotFound struct {
Identifier string
}
ErrDocumentAlreadyExists struct {
message string
}
)
func (e ErrDocumentNotFound) Error() string {
return fmt.Sprintf("document not found: %q", e.Identifier)
}
func (e ErrDocumentAlreadyExists) Error() string {
return e.message
}
func (p Document) CursorKey(orderBy DocumentOrderField) page.CursorKey {
switch orderBy {
case DocumentOrderFieldCreatedAt:
@@ -95,6 +112,10 @@ LIMIT 1;
document, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Document])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrDocumentNotFound{Identifier: documentID.String()}
}
return fmt.Errorf("cannot collect document: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -43,8 +45,32 @@ type (
}
DocumentVersions []*DocumentVersion
ErrDocumentVersionNotFound struct {
Identifier string
}
ErrDocumentVersionAlreadyExists struct {
message string
}
ErrDocumentVersionNoChanges struct {
Message string
}
)
func (e ErrDocumentVersionNotFound) Error() string {
return fmt.Sprintf("document version not found: %q", e.Identifier)
}
func (e ErrDocumentVersionAlreadyExists) Error() string {
return e.message
}
func (e ErrDocumentVersionNoChanges) Error() string {
return e.Message
}
func (p *DocumentVersions) LoadByDocumentID(
ctx context.Context,
conn pg.Conn,
@@ -207,6 +233,21 @@ VALUES (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" {
if pgErr.ConstraintName == "document_versions_document_id_version_number_key" {
return &ErrDocumentVersionAlreadyExists{
message: fmt.Sprintf("document version with document_id %s and version_number %d already exists", p.DocumentID, p.VersionNumber),
}
}
if pgErr.ConstraintName == "document_one_draft_version_idx" {
return &ErrDocumentVersionAlreadyExists{
message: fmt.Sprintf("document %s already has a draft version", p.DocumentID),
}
}
}
}
return fmt.Errorf("error creating document version: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -46,8 +48,24 @@ type (
}
DocumentVersionSignaturesWithPeople []*DocumentVersionSignatureWithPeople
ErrDocumentVersionSignatureNotFound struct {
Identifier string
}
ErrDocumentVersionSignatureAlreadyExists struct {
message string
}
)
func (e ErrDocumentVersionSignatureNotFound) Error() string {
return fmt.Sprintf("document version signature not found: %q", e.Identifier)
}
func (e ErrDocumentVersionSignatureAlreadyExists) Error() string {
return e.message
}
func (pvs DocumentVersionSignature) CursorKey(orderBy DocumentVersionSignatureOrderField) page.CursorKey {
switch orderBy {
case DocumentVersionSignatureOrderFieldCreatedAt:
@@ -191,6 +209,14 @@ INSERT INTO document_version_signatures (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "policy_version_signatures_policy_version_id_signed_by_key" {
return &ErrDocumentVersionSignatureAlreadyExists{
message: fmt.Sprintf("document version signature with document_version_id %s and signed_by %s already exists", pvs.DocumentVersionID, pvs.SignedBy),
}
}
}
return fmt.Errorf("cannot insert document version signature: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -42,8 +44,24 @@ type (
}
Evidences []*Evidence
ErrEvidenceNotFound struct {
Identifier string
}
ErrEvidenceAlreadyExists struct {
message string
}
)
func (e ErrEvidenceNotFound) Error() string {
return fmt.Sprintf("evidence not found: %q", e.Identifier)
}
func (e ErrEvidenceAlreadyExists) Error() string {
return e.message
}
func (e Evidence) CursorKey(orderBy EvidenceOrderField) page.CursorKey {
switch orderBy {
case EvidenceOrderFieldCreatedAt:
@@ -165,7 +183,20 @@ VALUES (
"description": e.Description,
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "evidences_reference_id_key" {
return &ErrEvidenceAlreadyExists{
message: fmt.Sprintf("evidence with task_id %s and reference_id %q already exists", e.TaskID, e.ReferenceID),
}
}
}
return fmt.Errorf("cannot insert evidence: %w", err)
}
return nil
}
func (e *Evidence) LoadByID(

View File

@@ -16,12 +16,14 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
"github.com/getprobo/probo/pkg/gid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -39,8 +41,24 @@ type (
}
Files []*File
ErrFileNotFound struct {
Identifier string
}
ErrFileAlreadyExists struct {
message string
}
)
func (e ErrFileNotFound) Error() string {
return fmt.Sprintf("file not found: %q", e.Identifier)
}
func (e ErrFileAlreadyExists) Error() string {
return e.message
}
func (f *File) LoadByID(
ctx context.Context,
conn pg.Conn,
@@ -79,6 +97,10 @@ LIMIT 1;
file, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[File])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrFileNotFound{Identifier: fileID.String()}
}
return fmt.Errorf("cannot collect file: %w", err)
}
@@ -133,7 +155,20 @@ VALUES (
"deleted_at": f.DeletedAt,
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "files_file_key_key" {
return &ErrFileAlreadyExists{
message: fmt.Sprintf("file with file_key %q already exists", f.FileKey),
}
}
}
return fmt.Errorf("cannot insert file: %w", err)
}
return nil
}
func (f File) SoftDelete(ctx context.Context, conn pg.Conn, scope Scoper) error {

View File

@@ -41,12 +41,28 @@ type (
Frameworks []*Framework
ErrFrameworkNotFound struct {
Identifier string
}
ErrFrameworkAlreadyExists struct {
message string
}
ErrFrameworkReferenceIDAlreadyExists struct {
ReferenceID string
OrganizationID gid.GID
}
)
func (e ErrFrameworkNotFound) Error() string {
return fmt.Sprintf("framework not found: %q", e.Identifier)
}
func (e ErrFrameworkAlreadyExists) Error() string {
return e.message
}
func (e ErrFrameworkReferenceIDAlreadyExists) Error() string {
return fmt.Sprintf("framework with reference ID %q already exists for organization %s", e.ReferenceID, e.OrganizationID)
}
@@ -169,6 +185,10 @@ LIMIT 1;
framework, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Framework])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrFrameworkNotFound{Identifier: referenceID}
}
return fmt.Errorf("cannot collect framework: %w", err)
}
@@ -211,6 +231,10 @@ LIMIT 1;
framework, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Framework])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrFrameworkNotFound{Identifier: frameworkID.String()}
}
return fmt.Errorf("cannot collect framework: %w", err)
}
@@ -311,7 +335,7 @@ SET
name = @name,
description = @description,
updated_at = @updated_at
WHERE
WHERE
%s
AND id = @framework_id
`

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -41,8 +43,24 @@ type (
}
Measures []*Measure
ErrMeasureNotFound struct {
Identifier string
}
ErrMeasureAlreadyExists struct {
message string
}
)
func (e ErrMeasureNotFound) Error() string {
return fmt.Sprintf("measure not found: %q", e.Identifier)
}
func (e ErrMeasureAlreadyExists) Error() string {
return e.message
}
func (m Measure) CursorKey(orderBy MeasureOrderField) page.CursorKey {
switch orderBy {
case MeasureOrderFieldCreatedAt:
@@ -395,6 +413,10 @@ LIMIT 1;
measure, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Measure])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrMeasureNotFound{Identifier: measureID.String()}
}
return fmt.Errorf("cannot collect measures: %w", err)
}
@@ -525,7 +547,20 @@ VALUES (
"state": m.State,
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "mitigations_org_ref_unique" {
return &ErrMeasureAlreadyExists{
message: fmt.Sprintf("measure with organization_id %s and reference_id %q already exists", m.OrganizationID, m.ReferenceID),
}
}
}
return fmt.Errorf("cannot insert measure: %w", err)
}
return nil
}
func (m *Measure) Update(

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -43,8 +44,24 @@ type (
}
Organizations []*Organization
ErrOrganizationNotFound struct {
Identifier string
}
ErrOrganizationAlreadyExists struct {
message string
}
)
func (e ErrOrganizationNotFound) Error() string {
return fmt.Sprintf("organization not found: %q", e.Identifier)
}
func (e ErrOrganizationAlreadyExists) Error() string {
return e.message
}
func (o Organization) CursorKey(orderBy OrganizationOrderField) page.CursorKey {
switch orderBy {
case OrganizationOrderFieldName:
@@ -98,6 +115,10 @@ LIMIT 1;
organization, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Organization])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrOrganizationNotFound{Identifier: organizationID.String()}
}
return fmt.Errorf("cannot collect organization: %w", err)
}
@@ -372,6 +393,10 @@ LIMIT 1
organization, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Organization])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrOrganizationNotFound{Identifier: customDomainID.String()}
}
return fmt.Errorf("cannot collect organization: %w", err)
}

View File

@@ -47,12 +47,20 @@ type (
ErrPeopleNotFound struct {
Identifier string
}
ErrPeopleAlreadyExists struct {
message string
}
)
func (e ErrPeopleNotFound) Error() string {
return fmt.Sprintf("people not found: %s", e.Identifier)
}
func (e ErrPeopleAlreadyExists) Error() string {
return e.message
}
func (p People) CursorKey(orderBy PeopleOrderField) page.CursorKey {
switch orderBy {
case PeopleOrderFieldCreatedAt:
@@ -105,6 +113,10 @@ LIMIT 1;
people, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[People])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrPeopleNotFound{Identifier: peopleID.String()}
}
return fmt.Errorf("cannot collect people: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -56,8 +57,24 @@ type (
RiskSnapshotter interface {
InsertRiskSnapshots(ctx context.Context, conn pg.Conn, scope Scoper, organizationID, snapshotID gid.GID) error
}
ErrRiskNotFound struct {
Identifier string
}
ErrRiskAlreadyExists struct {
message string
}
)
func (e ErrRiskNotFound) Error() string {
return fmt.Sprintf("risk not found: %q", e.Identifier)
}
func (e ErrRiskAlreadyExists) Error() string {
return e.message
}
func (r *Risk) CursorKey(orderBy RiskOrderField) page.CursorKey {
switch orderBy {
case RiskOrderFieldCreatedAt:
@@ -374,6 +391,10 @@ LIMIT 1;
risk, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Risk])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrRiskNotFound{Identifier: riskID.String()}
}
return fmt.Errorf("cannot collect risk: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"time"
@@ -35,32 +36,34 @@ type (
UpdatedAt time.Time `db:"updated_at"`
}
// SessionData stores authentication context for a user session
// Stored as JSONB in database
SessionData struct {
// PasswordAuthenticated indicates if user authenticated with email/password
// Required for accessing organizations without SAML
PasswordAuthenticated bool `json:"password_authenticated"`
// SAMLAuthenticatedOrgs tracks which organizations user has SAML-authenticated for
// Key: organization ID as string, Value: SAML authentication info
// Required for accessing organizations with SAML enforcement
PasswordAuthenticated bool `json:"password_authenticated"`
SAMLAuthenticatedOrgs map[string]SAMLAuthInfo `json:"saml_authenticated_orgs,omitempty"`
}
// SAMLAuthInfo stores SAML authentication details for an organization
SAMLAuthInfo struct {
// AuthenticatedAt is when the user SAML-
AuthenticatedAt time.Time `json:"authenticated_at"`
SAMLConfigID gid.GID `json:"saml_config_id"`
SAMLSubject string `json:"saml_subject"`
}
// SAMLConfigID is the SAML configuration used for authentication
SAMLConfigID gid.GID `json:"saml_config_id"`
ErrSessionNotFound struct {
Identifier string
}
// SAMLSubject is the NameID from the SAML assertion (email address)
SAMLSubject string `json:"saml_subject"`
ErrSessionAlreadyExists struct {
message string
}
)
func (e ErrSessionNotFound) Error() string {
return fmt.Sprintf("session not found: %q", e.Identifier)
}
func (e ErrSessionAlreadyExists) Error() string {
return e.message
}
func (s Session) CursorKey(orderBy SessionOrderField) page.CursorKey {
switch orderBy {
case SessionOrderFieldCreatedAt:
@@ -99,6 +102,10 @@ LIMIT 1;
session, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Session])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrSessionNotFound{Identifier: sessionID.String()}
}
return fmt.Errorf("cannot collect session: %w", err)
}
*s = session

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -44,8 +46,24 @@ type (
}
Tasks []*Task
ErrTaskNotFound struct {
Identifier string
}
ErrTaskAlreadyExists struct {
message string
}
)
func (e ErrTaskNotFound) Error() string {
return fmt.Sprintf("task not found: %q", e.Identifier)
}
func (e ErrTaskAlreadyExists) Error() string {
return e.message
}
func (c Task) CursorKey(orderBy TaskOrderField) page.CursorKey {
switch orderBy {
case TaskOrderFieldCreatedAt:
@@ -95,6 +113,10 @@ LIMIT 1;
task, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Task])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrTaskNotFound{Identifier: taskID.String()}
}
return fmt.Errorf("cannot collect tasks: %w", err)
}
@@ -158,7 +180,20 @@ VALUES (
"updated_at": c.UpdatedAt,
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "tasks_reference_id_unique" {
return &ErrTaskAlreadyExists{
message: fmt.Sprintf("task with measure_id %s and reference_id %q already exists", c.MeasureID, c.ReferenceID),
}
}
}
return fmt.Errorf("cannot insert task: %w", err)
}
return nil
}
func (c *Task) Upsert(

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -39,8 +41,24 @@ type (
}
TrustCenters []*TrustCenter
ErrTrustCenterNotFound struct {
Identifier string
}
ErrTrustCenterAlreadyExists struct {
message string
}
)
func (e ErrTrustCenterNotFound) Error() string {
return fmt.Sprintf("trust center not found: %q", e.Identifier)
}
func (e ErrTrustCenterAlreadyExists) Error() string {
return e.message
}
func (tc *TrustCenter) CursorKey(orderBy TrustCenterOrderField) page.CursorKey {
switch orderBy {
case TrustCenterOrderFieldCreatedAt:
@@ -218,6 +236,14 @@ INSERT INTO trust_centers (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "trust_centers_slug_key" {
return &ErrTrustCenterAlreadyExists{
message: fmt.Sprintf("trust center with slug %q already exists", tc.Slug),
}
}
}
return fmt.Errorf("cannot insert trust center: %w", err)
}

View File

@@ -25,6 +25,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -49,12 +50,20 @@ type (
ErrTrustCenterAccessNotFound struct {
Identifier string
}
ErrTrustCenterAccessAlreadyExists struct {
message string
}
)
func (e ErrTrustCenterAccessNotFound) Error() string {
return fmt.Sprintf("trust center access not found: %s", e.Identifier)
}
func (e ErrTrustCenterAccessAlreadyExists) Error() string {
return e.message
}
func (tca *TrustCenterAccess) CursorKey(orderBy TrustCenterAccessOrderField) page.CursorKey {
switch orderBy {
case TrustCenterAccessOrderFieldCreatedAt:
@@ -216,6 +225,14 @@ INSERT INTO trust_center_accesses (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "trust_center_accesses_trust_center_id_email_key" {
return &ErrTrustCenterAccessAlreadyExists{
message: "trust center access already exists",
}
}
}
return fmt.Errorf("cannot insert trust center access: %w", err)
}

View File

@@ -24,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -45,12 +46,20 @@ type (
ErrTrustCenterDocumentAccessNotFound struct {
Identifier string
}
ErrTrustCenterDocumentAccessAlreadyExists struct {
message string
}
)
func (e ErrTrustCenterDocumentAccessNotFound) Error() string {
return fmt.Sprintf("trust center document access not found: %s", e.Identifier)
}
func (e ErrTrustCenterDocumentAccessAlreadyExists) Error() string {
return e.message
}
func (tcda *TrustCenterDocumentAccess) CursorKey(orderBy TrustCenterDocumentAccessOrderField) page.CursorKey {
switch orderBy {
case TrustCenterDocumentAccessOrderFieldCreatedAt:
@@ -254,6 +263,25 @@ INSERT INTO trust_center_document_accesses (
_, err := conn.Exec(ctx, q, args)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" {
switch pgErr.ConstraintName {
case "trust_center_document_accesse_trust_center_access_id_docume_key":
return &ErrTrustCenterDocumentAccessAlreadyExists{
message: fmt.Sprintf("trust center document access with trust_center_access_id %s and document_id %s already exists", tcda.TrustCenterAccessID, tcda.DocumentID),
}
case "trust_center_document_accesse_trust_center_access_id_report_key":
return &ErrTrustCenterDocumentAccessAlreadyExists{
message: fmt.Sprintf("trust center document access with trust_center_access_id %s and report_id %s already exists", tcda.TrustCenterAccessID, tcda.ReportID),
}
case "trust_center_document_accesses_trust_center_file_id_key":
return &ErrTrustCenterDocumentAccessAlreadyExists{
message: fmt.Sprintf("trust center document access with trust_center_access_id %s and trust_center_file_id %s already exists", tcda.TrustCenterAccessID, tcda.TrustCenterFileID),
}
}
}
}
return fmt.Errorf("cannot insert trust center document access: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -42,12 +44,20 @@ type (
TrustCenterReferences []*TrustCenterReference
ErrTrustCenterReferenceNotFound struct {
ID string
Identifier string
}
ErrTrustCenterReferenceAlreadyExists struct {
message string
}
)
func (e ErrTrustCenterReferenceNotFound) Error() string {
return fmt.Sprintf("trust center reference not found: %s", e.ID)
return fmt.Sprintf("trust center reference not found: %q", e.Identifier)
}
func (e ErrTrustCenterReferenceAlreadyExists) Error() string {
return e.message
}
func (t TrustCenterReference) CursorKey(orderBy TrustCenterReferenceOrderField) page.CursorKey {
@@ -156,6 +166,14 @@ RETURNING rank;
err := conn.QueryRow(ctx, q, args).Scan(&t.Rank)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "trust_center_references_trust_center_id_rank_key" {
return &ErrTrustCenterReferenceAlreadyExists{
message: fmt.Sprintf("trust center reference with trust_center_id %s and rank already exists", t.TrustCenterID),
}
}
}
return fmt.Errorf("cannot insert trust center reference: %w", err)
}
@@ -198,7 +216,7 @@ WHERE
}
if result.RowsAffected() == 0 {
return ErrTrustCenterReferenceNotFound{ID: t.ID.String()}
return ErrTrustCenterReferenceNotFound{Identifier: t.ID.String()}
}
return nil

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -62,8 +63,24 @@ type (
VendorSnapshotter interface {
InsertVendorSnapshots(ctx context.Context, conn pg.Conn, scope Scoper, organizationID, snapshotID gid.GID) error
}
ErrVendorNotFound struct {
Identifier string
}
ErrVendorAlreadyExists struct {
message string
}
)
func (e ErrVendorNotFound) Error() string {
return fmt.Sprintf("vendor not found: %q", e.Identifier)
}
func (e ErrVendorAlreadyExists) Error() string {
return e.message
}
func (v Vendor) CursorKey(orderBy VendorOrderField) page.CursorKey {
switch orderBy {
case VendorOrderFieldCreatedAt:
@@ -133,6 +150,10 @@ LIMIT 1;
vendor, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Vendor])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &ErrVendorNotFound{Identifier: vendorID.String()}
}
return fmt.Errorf("cannot collect vendor: %w", err)
}

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -41,8 +43,24 @@ type (
}
VendorBusinessAssociateAgreements []*VendorBusinessAssociateAgreement
ErrVendorBusinessAssociateAgreementNotFound struct {
Identifier string
}
ErrVendorBusinessAssociateAgreementAlreadyExists struct {
message string
}
)
func (e ErrVendorBusinessAssociateAgreementNotFound) Error() string {
return fmt.Sprintf("vendor business associate agreement not found: %q", e.Identifier)
}
func (e ErrVendorBusinessAssociateAgreementAlreadyExists) Error() string {
return e.message
}
func (v VendorBusinessAssociateAgreement) CursorKey(orderBy VendorBusinessAssociateAgreementOrderField) page.CursorKey {
switch orderBy {
case VendorBusinessAssociateAgreementOrderFieldValidFrom:
@@ -241,7 +259,18 @@ ON CONFLICT (organization_id, vendor_id) DO UPDATE SET
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "vendor_business_associate_agreements_source_id_snapshot_id_key" {
return &ErrVendorBusinessAssociateAgreementAlreadyExists{
message: fmt.Sprintf("vendor business associate agreement with source_id %s and snapshot_id %s already exists", vbaa.SourceID, vbaa.SnapshotID),
}
}
}
return fmt.Errorf("cannot upsert vendor business associate agreement: %w", err)
}
return nil
}
func (vbaa *VendorBusinessAssociateAgreement) Delete(

View File

@@ -16,6 +16,7 @@ package coredata
import (
"context"
"errors"
"fmt"
"maps"
"time"
@@ -23,6 +24,7 @@ import (
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg"
)
@@ -41,8 +43,24 @@ type (
}
VendorDataPrivacyAgreements []*VendorDataPrivacyAgreement
ErrVendorDataPrivacyAgreementNotFound struct {
Identifier string
}
ErrVendorDataPrivacyAgreementAlreadyExists struct {
message string
}
)
func (e ErrVendorDataPrivacyAgreementNotFound) Error() string {
return fmt.Sprintf("vendor data privacy agreement not found: %q", e.Identifier)
}
func (e ErrVendorDataPrivacyAgreementAlreadyExists) Error() string {
return e.message
}
func (v VendorDataPrivacyAgreement) CursorKey(orderBy VendorDataPrivacyAgreementOrderField) page.CursorKey {
switch orderBy {
case VendorDataPrivacyAgreementOrderFieldValidFrom:
@@ -241,7 +259,18 @@ ON CONFLICT (organization_id, vendor_id) DO UPDATE SET
}
_, err := conn.Exec(ctx, q, args)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
if pgErr.Code == "23505" && pgErr.ConstraintName == "vendor_data_privacy_agreements_source_id_snapshot_id_key" {
return &ErrVendorDataPrivacyAgreementAlreadyExists{
message: fmt.Sprintf("vendor data privacy agreement with source_id %s and snapshot_id %s already exists", vdpa.SourceID, vdpa.SnapshotID),
}
}
}
return fmt.Errorf("cannot upsert vendor data privacy agreement: %w", err)
}
return nil
}
func (vdpa *VendorDataPrivacyAgreement) Delete(

View File

@@ -276,7 +276,9 @@ func (s *DocumentService) publishVersionInTx(
if publishedVersion.Content == documentVersion.Content &&
publishedVersion.Title == documentVersion.Title &&
publishedVersion.OwnerID == documentVersion.OwnerID {
return nil, nil, fmt.Errorf("cannot publish version: no changes detected")
return nil, nil, &coredata.ErrDocumentVersionNoChanges{
Message: "no changes detected",
}
}
}

View File

@@ -441,7 +441,7 @@ func validateTenantAccess(ctx context.Context, tenantID gid.TenantID) {
access, _ := ctx.Value(userTenantContextKey).(*userTenantAccess)
if access == nil {
panic(fmt.Errorf("tenant not found"))
panic(&authz.TenantAccessError{Message: "tenant not found"})
}
if !slices.Contains(access.tenantIDs, tenantID) {
@@ -451,6 +451,6 @@ func validateTenantAccess(ctx context.Context, tenantID gid.TenantID) {
}
}
panic(fmt.Errorf("access denied to tenant"))
panic(&authz.TenantAccessError{Message: "tenant not found"})
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,69 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package graphql
import (
"maps"
"github.com/vektah/gqlparser/v2/gqlerror"
)
func Unauthorized() *gqlerror.Error {
return &gqlerror.Error{
Message: "not authorized",
Extensions: map[string]any{
"code": "UNAUTHORIZED",
},
}
}
func AuthenticationRequired(details map[string]any) *gqlerror.Error {
extensions := map[string]any{
"code": "AUTHENTICATION_REQUIRED",
}
maps.Copy(extensions, details)
return &gqlerror.Error{
Message: "Additional authentication required to access this organization",
Extensions: extensions,
}
}
func NotFound(err error) *gqlerror.Error {
return &gqlerror.Error{
Message: err.Error(),
Extensions: map[string]any{
"code": "NOT_FOUND",
},
}
}
func Conflict(err error) *gqlerror.Error {
return &gqlerror.Error{
Message: err.Error(),
Extensions: map[string]any{
"code": "CONFLICT",
},
}
}
func Invalid(err error) *gqlerror.Error {
return &gqlerror.Error{
Message: err.Error(),
Extensions: map[string]any{
"code": "INVALID",
},
}
}

View File

@@ -20,6 +20,7 @@ import (
"runtime/debug"
"github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/vektah/gqlparser/v2/gqlerror"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/log"
@@ -32,29 +33,26 @@ func RecoverFunc(ctx context.Context, err any) error {
var errSAMLRequired auth.ErrSAMLAuthRequired
if errors.As(asError(err), &errSAMLRequired) {
return &gqlerror.Error{
Message: "Additional authentication required to access this organization",
Extensions: map[string]any{
"code": "AUTHENTICATION_REQUIRED",
"requiresSaml": true,
"redirectUrl": errSAMLRequired.RedirectURL,
"samlConfigId": errSAMLRequired.ConfigID.String(),
"organizationId": errSAMLRequired.OrganizationID.String(),
},
}
return AuthenticationRequired(map[string]any{
"requiresSaml": true,
"redirectUrl": errSAMLRequired.RedirectURL,
"samlConfigId": errSAMLRequired.ConfigID.String(),
"organizationId": errSAMLRequired.OrganizationID.String(),
})
}
var errPasswordRequired auth.ErrPasswordAuthRequired
if errors.As(asError(err), &errPasswordRequired) {
return &gqlerror.Error{
Message: "Additional authentication required to access this organization",
Extensions: map[string]any{
"code": "AUTHENTICATION_REQUIRED",
"requiresSaml": false,
"redirectUrl": errPasswordRequired.RedirectURL,
"organizationId": errPasswordRequired.OrganizationID.String(),
},
}
return AuthenticationRequired(map[string]any{
"requiresSaml": false,
"redirectUrl": errPasswordRequired.RedirectURL,
"organizationId": errPasswordRequired.OrganizationID.String(),
})
}
var tenantAccessErr *authz.TenantAccessError
if errTyped, ok := err.(error); ok && errors.As(errTyped, &tenantAccessErr) {
return Unauthorized()
}
logger := httpserver.LoggerFromContext(ctx)