This repository was archived by the owner on Jun 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBackupPlanCreatePage.tsx
More file actions
232 lines (204 loc) · 7.61 KB
/
Copy pathBackupPlanCreatePage.tsx
File metadata and controls
232 lines (204 loc) · 7.61 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
import { useState, useMemo, useRef } from "react"
import { useNavigate } from "react-router"
import { Archive, Save } from "lucide-react"
import { Button, Section, Spinner } from "@cozystack/ui"
import { useK8sCreate, useK8sList } from "@cozystack/k8s-client"
import { useTenantContext } from "../lib/tenant-context.tsx"
import { useApplicationDefinitions } from "../lib/app-definitions.ts"
import { useCRDSchema } from "../lib/use-crd-schema.ts"
import { SchemaForm, type SchemaFormHandle } from "../components/SchemaForm.tsx"
import { enrichSchemaWithEnums } from "../lib/backup-utils.ts"
export function BackupPlanCreatePage() {
const navigate = useNavigate()
const { tenantNamespace } = useTenantContext()
const { data: appDefs } = useApplicationDefinitions()
const [formData, setFormData] = useState<any>({})
const [name, setName] = useState("")
const schemaFormRef = useRef<SchemaFormHandle>(null)
// Get base schema from CRD
const { schema: baseSchema, isLoading: schemaLoading } = useCRDSchema(
"plans.backups.cozystack.io"
)
// backupClassName and applicationRef.kind are dynamic dropdowns driven by the
// CRD's x-cozystack-options keyword (backupclass / appkind sources), rendered
// by DynamicOptionsWidget. Only applicationRef.name stays on the client-side
// enumMap below, because it depends on the chosen kind — a context the Option
// contract cannot express.
// Get instances for selected kind.
// Strict undefined check so an explicit empty string from the user means
// "no group" — clearing the field opts out of the cozystack defaults.
const selectedKind = formData?.applicationRef?.kind
const rawApiGroup = formData?.applicationRef?.apiGroup
const selectedApiGroup = rawApiGroup === undefined ? "apps.cozystack.io" : rawApiGroup
const selectedAppDef = useMemo(
() => appDefs?.items.find(d => d.spec?.application.kind === selectedKind),
[appDefs, selectedKind]
)
const { data: instancesData } = useK8sList<any>({
apiGroup: "apps.cozystack.io",
apiVersion: "v1alpha1",
plural: selectedAppDef?.spec?.application.plural ?? "",
namespace: tenantNamespace ?? "",
}, { enabled: !!selectedAppDef && !!tenantNamespace && selectedApiGroup === "apps.cozystack.io" })
const createMutation = useK8sCreate({
apiGroup: "backups.cozystack.io",
apiVersion: "v1alpha1",
plural: "plans",
namespace: tenantNamespace ?? "",
})
const schema = useMemo(() => {
if (!baseSchema) return null
let base
try {
base = JSON.parse(baseSchema)
} catch (e) {
console.error("Failed to parse Plan schema:", e)
return null
}
const instances = instancesData?.items.map((inst: any) => inst.metadata.name) ?? []
const enumMap: Record<string, string[]> = {}
// applicationRef.name depends on the selected kind, so it cannot be served
// by the Option contract — keep it on the client-side enumMap. Only fill it
// when the cozystack apiGroup matches (ApplicationDefinitions cover it).
if (selectedApiGroup === "apps.cozystack.io" && selectedKind && instances.length > 0) {
enumMap["applicationRef.name"] = instances
}
// Enrich schema with enum values
const enriched = enrichSchemaWithEnums(base, [], enumMap)
// Add default value for apiGroup
if (enriched.properties?.applicationRef?.properties?.apiGroup) {
enriched.properties.applicationRef.properties.apiGroup.default = "apps.cozystack.io"
}
// Pre-fill cron with a daily 02:00 default so the user starts with a
// valid expression they can edit, rather than an empty required field.
if (enriched.properties?.schedule?.properties?.cron) {
enriched.properties.schedule.properties.cron.default = "0 2 * * *"
}
return JSON.stringify(enriched)
}, [baseSchema, instancesData, selectedKind, selectedApiGroup])
const handleSubmit = async () => {
if (!tenantNamespace) {
alert("Tenant namespace is not available. Please refresh.")
return
}
if (!name.trim()) {
alert("Name is required")
return
}
// Run RJSF validation before the page-level checks so schema-required
// fields render inline errors instead of being masked by the alerts below.
if (schemaFormRef.current && !schemaFormRef.current.validate()) return
if (!formData.applicationRef?.kind || !formData.applicationRef?.name) {
alert("Application reference is required")
return
}
if (!formData.backupClassName) {
alert("Backup class name is required")
return
}
const resource = {
apiVersion: "backups.cozystack.io/v1alpha1",
kind: "Plan",
metadata: {
name: name.trim(),
namespace: tenantNamespace ?? undefined,
},
spec: formData,
}
try {
await createMutation.mutateAsync(resource)
navigate("/console/backups/plans")
} catch (err) {
alert(`Failed to create Plan: ${(err as Error).message}`)
}
}
const handleCancel = () => {
navigate("/console/backups/plans")
}
if (schemaLoading) {
return (
<div className="flex items-center gap-2 p-8 text-slate-500">
<Spinner /> Loading schema...
</div>
)
}
if (!schema) {
return (
<div className="p-8 text-red-600">
Failed to load Plan schema. Please refresh the page.
</div>
)
}
return (
<div className="p-6">
<div className="mb-5 flex items-center gap-3">
<div className="flex size-11 shrink-0 items-center justify-center rounded-md bg-slate-100">
<Archive className="size-6 text-slate-600" />
</div>
<div>
<h1 className="text-lg font-semibold text-slate-900">Create Plan</h1>
<p className="text-xs text-slate-500">
Configure a backup plan for your application
</p>
</div>
</div>
<div>
<Section>
<div className="space-y-4 p-5">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
Plan Name <span className="text-red-500">*</span>
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="my-backup-plan"
className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
required
/>
</div>
<div>
<SchemaForm
ref={schemaFormRef}
openAPISchema={schema}
formData={formData}
onChange={setFormData}
>
<div className="hidden" />
</SchemaForm>
</div>
</div>
<div className="flex items-center gap-2 border-t border-slate-200 px-5 py-3">
<Button
type="button"
variant="primary"
size="sm"
onClick={handleSubmit}
disabled={createMutation.isPending}
>
{createMutation.isPending ? (
<>
<Spinner /> Creating...
</>
) : (
<>
<Save className="size-3.5" /> Create
</>
)}
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleCancel}
disabled={createMutation.isPending}
>
Cancel
</Button>
</div>
</Section>
</div>
</div>
)
}