-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathview-policy-page.tsx
More file actions
462 lines (420 loc) · 19.2 KB
/
Copy pathview-policy-page.tsx
File metadata and controls
462 lines (420 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import {
useDeleteInternalPolicy,
useGetInternalPolicyAssociationsById,
useGetInternalPolicyDetailsById,
useGetPolicyDiscussionById,
useUpdateInternalPolicy,
} from '@/lib/graphql-hooks/internal-policy'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import useFormSchema, { type EditPolicyMetadataFormData } from '@/components/pages/protected/policies/view/hooks/use-form-schema.ts'
import { Form } from '@repo/ui/form'
import DetailsField from '@/components/pages/protected/policies/view/fields/details-field.tsx'
import TitleField from '@/components/pages/protected/policies/view/fields/title-field.tsx'
import { Button } from '@repo/ui/button'
import { ExternalLink, LockOpen, PencilIcon, Trash2 } from 'lucide-react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@repo/ui/tabs'
import AuthorityCard from '@/components/pages/protected/policies/view/cards/authority-card.tsx'
import PropertiesCard from '@/components/pages/protected/policies/view/cards/properties-card.tsx'
import { InternalPolicyDocumentManagementMode, InternalPolicyDocumentStatus, InternalPolicyFrequency, type UpdateInternalPolicyInput } from '@repo/codegen/src/schema.ts'
import HistoricalCard from '@/components/pages/protected/policies/view/cards/historical-card.tsx'
import TagsCard from '@/components/pages/protected/policies/view/cards/tags-card.tsx'
import { useQueryClient } from '@tanstack/react-query'
import { useNotification } from '@/hooks/useNotification.tsx'
import { canDelete, canEdit } from '@/lib/authz/utils'
import { ConfirmationDialog } from '@repo/ui/confirmation-dialog'
import { useRouter } from 'next/navigation'
import Menu from '@/components/shared/menu/menu.tsx'
import CreateItemsFromPolicyToolbar from './create-items-from-policy-toolbar'
import { BreadcrumbContext } from '@/providers/BreadcrumbContext.tsx'
import SlideBarLayout from '@/components/shared/slide-bar/slide-bar.tsx'
import { useOrganization } from '@/hooks/useOrganization'
import { ManagePermissionSheet } from '@/components/shared/policy-procedure.tsx/manage-permissions-sheet'
import { ObjectAssociationNodeEnum } from '@/components/shared/object-association/types/object-association-types.ts'
import ObjectAssociationSwitch from '@/components/shared/object-association/object-association-switch.tsx'
import { parseErrorMessage } from '@/utils/graphQlErrorMatcher'
import { useAssociationRemoval } from '@/hooks/useAssociationRemoval'
import { ASSOCIATION_REMOVAL_CONFIG } from '@/components/shared/object-association/object-association-config'
import Loading from '@/app/(protected)/policies/[id]/view/loading'
import { Card } from '@repo/ui/cardpanel'
import { useAccountRoles } from '@/lib/query-hooks/permissions'
import { type Value } from 'platejs'
import usePlateEditor from '@/components/shared/plate/usePlateEditor.tsx'
import { canonicalizeDetails } from '@/components/shared/plate/plate-utils'
import { SaveButton } from '@/components/shared/save-button/save-button'
import { CancelButton } from '@/components/shared/cancel-button.tsx/cancel-button'
import LinkedProcedures from './fields/linked-procedures'
import { ObjectTypes } from '@repo/codegen/src/type-names'
import HistoryTab from './tabs/history/history-tab'
import { VersionBump } from '@/lib/enums/revision-enum'
import ExternalReferenceView from '@/components/pages/protected/policies/view/fields/external-reference-view'
type TViewPolicyPage = {
policyId: string
}
type TabValue = 'policy' | 'procedures' | 'history'
const ViewPolicyPage: React.FC<TViewPolicyPage> = ({ policyId }) => {
const [isDeleting, setIsDeleting] = useState<boolean>(false)
const { data, isLoading } = useGetInternalPolicyDetailsById(policyId, !isDeleting)
const { mutateAsync: updatePolicy, isPending: isSaving } = useUpdateInternalPolicy()
const policy = data?.internalPolicy
const { form } = useFormSchema()
const [isEditing, setIsEditing] = useState(false)
const [editingField, setEditingField] = useState<string | null>(null)
const queryClient = useQueryClient()
const { successNotification, errorNotification } = useNotification()
const { data: permission } = useAccountRoles(ObjectTypes.INTERNAL_POLICY, policyId)
const deleteAllowed = canDelete(permission?.roles)
const editAllowed = canEdit(permission?.roles)
const { mutateAsync: deletePolicy } = useDeleteInternalPolicy()
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [pendingManagementMode, setPendingManagementMode] = useState<InternalPolicyDocumentManagementMode | null>(null)
const router = useRouter()
const { setCrumbs } = React.use(BreadcrumbContext)
const { currentOrgId, getOrganizationByID } = useOrganization()
const currentOrganization = getOrganizationByID(currentOrgId ?? '')
const [dataInitialized, setDataInitialized] = useState(false)
const initialDetailsCanonicalRef = useRef<string | null>(null)
const [showPermissionsSheet, setShowPermissionsSheet] = useState(false)
const { data: assocData } = useGetInternalPolicyAssociationsById(policyId, !isDeleting)
const { data: discussionData } = useGetPolicyDiscussionById(policyId)
const plateEditorHelper = usePlateEditor()
const [activeTab, setActiveTab] = useState<TabValue>('policy')
const isExternalReference = policy?.managementMode === InternalPolicyDocumentManagementMode.EXTERNAL_REFERENCE
const hasFile = !!policy?.file
const showManagementModeAction = editAllowed && hasFile && !isExternalReference
const handleConfirmManagementModeChange = async () => {
if (!pendingManagementMode) return
await handleUpdateField({ managementMode: pendingManagementMode })
setPendingManagementMode(null)
}
const procedureCount = assocData?.internalPolicy?.procedures?.totalCount ?? 0
const procedures = assocData?.internalPolicy?.procedures?.edges ?? []
const memoizedSections = useMemo(() => {
if (!assocData?.internalPolicy) return {}
return {
procedures: assocData.internalPolicy.procedures,
controls: assocData.internalPolicy.controls,
subcontrols: assocData.internalPolicy.subcontrols,
controlObjectives: assocData.internalPolicy.controlObjectives,
tasks: assocData.internalPolicy.tasks,
programs: assocData.internalPolicy.programs,
risks: assocData.internalPolicy.risks,
assets: assocData.internalPolicy.assets,
entities: assocData.internalPolicy.entities,
identityHolders: assocData.internalPolicy.identityHolders,
}
}, [assocData])
const memoizedCenterNode = useMemo(() => {
if (!policy) return null
return {
node: policy,
type: ObjectAssociationNodeEnum.POLICY,
}
}, [policy])
useEffect(() => {
setCrumbs([
{ label: 'Home', href: '/dashboard' },
{ label: 'Compliance', href: '/programs' },
{ label: 'Policies', href: '/policies' },
{ label: policy?.name, isLoading: isLoading },
])
}, [setCrumbs, policy, isLoading])
useEffect(() => {
if (policy && !dataInitialized) {
form.reset({
name: policy.name,
details: policy?.details ?? '',
detailsJSON: policy?.detailsJSON ? (policy.detailsJSON as Value) : undefined,
tags: policy.tags ?? [],
approvalRequired: policy?.approvalRequired ?? true,
status: policy.status ?? InternalPolicyDocumentStatus.DRAFT,
internalPolicyKindName: policy.internalPolicyKindName ?? '',
reviewDue: policy.reviewDue ? new Date(policy.reviewDue as string) : undefined,
reviewFrequency: policy.reviewFrequency ?? InternalPolicyFrequency.YEARLY,
revision: policy.revision ?? '',
approverID: policy.approver?.id,
delegateID: policy.delegate?.id,
})
initialDetailsCanonicalRef.current = policy.detailsJSON ? canonicalizeDetails(policy.detailsJSON) : null
setDataInitialized(true)
}
}, [policy, form, dataInitialized])
const handleCancel = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
form.reset()
setIsEditing(false)
}
const handleEdit = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
setIsEditing(true)
}
const handleDeletePolicy = async () => {
try {
setIsDeleting(true)
await deletePolicy({ deleteInternalPolicyId: policyId })
successNotification({ title: 'Policy deleted successfully' })
router.push('/policies')
} catch (error) {
const errorMessage = parseErrorMessage(error)
errorNotification({
title: 'Error',
description: errorMessage,
})
}
}
const onSubmitHandler = useCallback(
async (data: EditPolicyMetadataFormData) => {
if (!policy?.id) {
return
}
try {
const { revision, approverID, delegateID, details: _details, detailsJSON, ...restData } = data
const input: UpdateInternalPolicyInput = {
...restData,
tags: data?.tags?.filter((tag): tag is string => typeof tag === 'string') ?? [],
}
if (detailsJSON !== undefined && !isExternalReference) {
input.detailsJSON = detailsJSON
input.details = await plateEditorHelper.convertToHtml(detailsJSON as Value)
}
if (approverID) {
input.approverID = approverID
} else if (policy.approver?.id) {
input.clearApprover = true
}
if (delegateID) {
input.delegateID = delegateID
} else if (policy.delegate?.id) {
input.clearDelegate = true
}
if (revision && revision !== (policy?.revision ?? '')) {
input.revision = revision
} else if (detailsJSON && initialDetailsCanonicalRef.current !== null && canonicalizeDetails(detailsJSON) !== initialDetailsCanonicalRef.current) {
input.RevisionBump = VersionBump.MINOR
}
const formData: {
updateInternalPolicyId: string
input: UpdateInternalPolicyInput
} = {
updateInternalPolicyId: policy?.id,
input,
}
await updatePolicy(formData)
successNotification({
title: 'Policy Updated',
description: 'Policy has been successfully updated',
})
setIsEditing(false)
await queryClient.invalidateQueries({ queryKey: ['internalPolicies'] })
queryClient.invalidateQueries({ queryKey: ['policyDiscussion', policyId] })
setDataInitialized(false)
} catch (error) {
const errorMessage = parseErrorMessage(error)
errorNotification({
title: 'Error',
description: errorMessage,
})
}
},
[policy, plateEditorHelper, updatePolicy, successNotification, errorNotification, queryClient, policyId, initialDetailsCanonicalRef, isExternalReference],
)
const handleFormSubmit = useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
void form.handleSubmit(onSubmitHandler)(e)
},
[form, onSubmitHandler],
)
const handleCreateNewPolicy = async () => {
router.push(`/policies/create`)
}
const handleCreateNewProcedure = async () => {
router.push(`/procedures/create?policyId=${policyId}`)
}
const handleUpdateField = async (input: UpdateInternalPolicyInput, options?: { throwOnError?: boolean }) => {
if (!policy?.id) {
return
}
try {
await updatePolicy({ updateInternalPolicyId: policy?.id, input })
successNotification({
title: 'Policy Updated',
description: 'Policy has been successfully updated',
})
await queryClient.invalidateQueries({ queryKey: ['internalPolicies'] })
setDataInitialized(false)
} catch (error) {
const errorMessage = parseErrorMessage(error)
errorNotification({
title: 'Error',
description: errorMessage,
})
if (options?.throwOnError) {
throw error
}
}
}
const handleRemoveAssociation = useAssociationRemoval({
entityId: policy?.id,
handleUpdateField: (input: UpdateInternalPolicyInput) => handleUpdateField(input, { throwOnError: true }),
queryClient,
cacheTargets: [{ queryKey: ['internalPolicies', policyId, 'associations'], dataRootField: 'internalPolicy' }],
invalidateQueryKeys: [['internalPolicies']],
sectionKeyToRemoveField: ASSOCIATION_REMOVAL_CONFIG.policy.sectionKeyToRemoveField,
sectionKeyToDataField: ASSOCIATION_REMOVAL_CONFIG.policy.sectionKeyToDataField,
sectionKeyToInvalidateQueryKey: ASSOCIATION_REMOVAL_CONFIG.policy.sectionKeyToInvalidateQueryKey,
onRemoved: () => setDataInitialized(false),
})
if (isLoading) {
return <Loading />
}
if (!policy) {
return null
}
const menuComponent = (
<div className="space-y-4">
{isEditing ? (
<div className="flex gap-2 justify-end">
<CancelButton onClick={handleCancel}></CancelButton>
<SaveButton disabled={isSaving} isSaving={isSaving} />
</div>
) : (
<div className="flex gap-2 justify-end">
<CreateItemsFromPolicyToolbar
initialData={{ internalPolicyIDs: [policyId] }}
handleCreateNewPolicy={handleCreateNewPolicy}
handleCreateNewProcedure={handleCreateNewProcedure}
objectAssociationsDisplayIDs={policy?.name ? [policy?.name] : []}
/>
{!editAllowed && !deleteAllowed ? (
<></>
) : (
<Menu
content={
<>
{editAllowed && (
<Button size="sm" variant="transparent" className="flex justify-start space-x-2 " onClick={handleEdit}>
<PencilIcon size={16} strokeWidth={2} />
<span>Edit</span>
</Button>
)}
{deleteAllowed && (
<>
<Button size="sm" variant="transparent" className="flex justify-start space-x-2" onClick={() => setIsDeleteDialogOpen(true)}>
<Trash2 size={16} strokeWidth={2} />
<span>Delete</span>
</Button>
<ConfirmationDialog
open={isDeleteDialogOpen}
onOpenChange={setIsDeleteDialogOpen}
onConfirm={handleDeletePolicy}
title={`Delete Internal Policy`}
description={
<>
This action cannot be undone. This will permanently remove <b>{policy.name}</b> from the organization.
</>
}
/>
</>
)}
<Button size="sm" variant="transparent" className="flex justify-start space-x-2" onClick={() => setShowPermissionsSheet(true)}>
<LockOpen size={16} strokeWidth={2} />
<span>Manage Permissions</span>
</Button>
{showManagementModeAction && (
<Button size="sm" variant="transparent" className="flex justify-start space-x-2" onClick={() => setPendingManagementMode(InternalPolicyDocumentManagementMode.EXTERNAL_REFERENCE)}>
<ExternalLink size={16} strokeWidth={2} />
<span>Switch to externally managed</span>
</Button>
)}
</>
}
/>
)}
<ConfirmationDialog
open={!!pendingManagementMode}
onOpenChange={(open) => {
if (!open) setPendingManagementMode(null)
}}
onConfirm={handleConfirmManagementModeChange}
title="Change management mode"
confirmationText="Switch to externally managed"
confirmationTextVariant="primary"
description={
<>
The Policy view will switch to displaying the attached file and edits inside Openlane will be disabled. Any changes since the file was originally uploaded will not be reflected in the
attached file. The underlying details data stays in place — you can switch back at any time.
</>
}
/>
</div>
)}
</div>
)
const mainContent = (
<div className="p-2">
<TitleField isEditing={isEditing} form={form} handleUpdate={handleUpdateField} initialData={policy.name} editAllowed={editAllowed} />
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as TabValue)} variant="underline">
<TabsList className="relative flex justify-start w-full">
<div className="absolute -bottom-0.5 left-1 right-0 h-px bg-border" />
<TabsTrigger className="relative max-w-26 text-start" value="policy">
Policy
</TabsTrigger>
<TabsTrigger value="procedures" className="relative max-w-28 flex text-start items-center gap-2">
Procedures
{procedureCount > 0 && <span className="inline-flex items-center justify-center min-w-5 h-5 text-xs rounded-full bg-card bg-rounded">{procedureCount}</span>}
</TabsTrigger>
<TabsTrigger value="history" className="relative max-w-26 text-start">
History
</TabsTrigger>
</TabsList>
<TabsContent value="policy">
{isExternalReference && policy.file ? (
<ExternalReferenceView policy={policy} editAllowed={editAllowed} />
) : (
<DetailsField isEditing={isEditing} form={form} policy={policy} discussionData={discussionData?.internalPolicy} />
)}
</TabsContent>
<TabsContent value="procedures">
<LinkedProcedures procedures={procedures} />
</TabsContent>
<TabsContent value="history">
<HistoryTab policyId={policyId} policy={policy} />
</TabsContent>
</Tabs>
</div>
)
const sidebarContent = (
<>
{memoizedCenterNode && <ObjectAssociationSwitch sections={memoizedSections} centerNode={memoizedCenterNode} canEdit={editAllowed} onRemoveAssociation={handleRemoveAssociation} />}
<Card className="p-4">
<h3 className="text-lg font-medium mb-2">Properties</h3>
<AuthorityCard
form={form}
approver={policy.approver}
delegate={policy.delegate}
isEditing={isEditing}
editAllowed={editAllowed}
handleUpdate={handleUpdateField}
activeField={editingField}
setActiveField={setEditingField}
/>
<PropertiesCard form={form} isEditing={isEditing} policy={policy} editAllowed={editAllowed} handleUpdate={handleUpdateField} activeField={editingField} setActiveField={setEditingField} />
<HistoricalCard policy={policy} />
<TagsCard form={form} policy={policy} isEditing={isEditing} handleUpdate={handleUpdateField} editAllowed={editAllowed} activeField={editingField} setActiveField={setEditingField} />
</Card>
</>
)
return (
<>
<title>{`${currentOrganization?.node?.displayName ?? 'Openlane'} | Internal Policies - ${policy.name}`}</title>
<Form {...form}>
<form onSubmit={handleFormSubmit}>
<SlideBarLayout sidebarTitle="Details" sidebarContent={sidebarContent} menu={menuComponent} slideOpen={isEditing} minWidth={430}>
{mainContent}
</SlideBarLayout>
</form>
</Form>
<ManagePermissionSheet open={showPermissionsSheet} onOpenChange={(val) => setShowPermissionsSheet(val)} />
</>
)
}
export default ViewPolicyPage