-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_docs.diff
More file actions
385 lines (385 loc) · 13.3 KB
/
diff_docs.diff
File metadata and controls
385 lines (385 loc) · 13.3 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
diff --git a/admin/src/pages/Docs.tsx b/admin/src/pages/Docs.tsx
new file mode 100644
index 00000000..2dd45b60
--- /dev/null
+++ b/admin/src/pages/Docs.tsx
@@ -0,0 +1,379 @@
+import React, { useCallback, useMemo, useState } from 'react';
+import { useMutation, useQuery } from '@tanstack/react-query';
+import ReactMarkdown from 'react-markdown';
+import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
+import { Button } from '@/components/ui/Button';
+import { TextArea } from '@/components/ui/TextArea';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
+import { Badge } from '@/components/ui/Badge';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { getDocs, runValidation } from '@/lib/api';
+import type { ValidationRequestDto, ValidationResultDto } from '@/lib/types';
+import { BookOpen, Play, RotateCcw, CheckCircle, XCircle, AlertTriangle } from 'lucide-react';
+
+type DocsTab = 'docs' | 'playground';
+
+const SAMPLE_PAYLOAD = {
+ document: {
+ creditType: 'STANDBY',
+ amount: {
+ value: 100000,
+ currency: 'USD',
+ },
+ expiryDate: '2024-12-31',
+ beneficiary: {
+ name: 'ABC Trading Company',
+ address: '123 Main St, New York, NY 10001',
+ },
+ applicant: {
+ name: 'XYZ Corporation',
+ address: '456 Oak Ave, Chicago, IL 60601',
+ },
+ terms: {
+ transferable: false,
+ partialShipmentAllowed: true,
+ transshipmentAllowed: false,
+ },
+ },
+} as const;
+
+const escapeHtml = (value: string): string =>
+ value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
+
+const highlightJson = (value: string): string =>
+ escapeHtml(value).replace(
+ /("(\u[a-fA-F0-9]{4}|\[^u]|[^\"])*"(?:\s*:)?|\\b(true|false|null)\\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
+ (match) => {
+ let cls = 'text-emerald-400';
+ if (match.startsWith('"')) {
+ cls = match.endsWith(':') ? 'text-orange-400' : 'text-emerald-400';
+ } else if (/true|false/.test(match)) {
+ cls = 'text-purple-400';
+ } else if (/null/.test(match)) {
+ cls = 'text-gray-400';
+ } else {
+ cls = 'text-sky-400';
+ }
+ return `<span class="${cls}">${match}</span>`;
+ }
+ );
+
+const JsonSyntaxPreview: React.FC<{ value: string }> = ({ value }) => {
+ const highlighted = useMemo(() => highlightJson(value), [value]);
+ return (
+ <pre
+ className="max-h-[300px] overflow-auto whitespace-pre-wrap break-words rounded-b-md bg-background px-3 py-3 font-mono text-xs"
+ dangerouslySetInnerHTML={{ __html: highlighted }}
+ />
+ );
+};
+
+const isValidationPayload = (value: unknown): value is ValidationRequestDto =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const Docs: React.FC = () => {
+ const [activeTab, setActiveTab] = useState<DocsTab>('docs');
+ const [playgroundPayload, setPlaygroundPayload] = useState<string>(
+ JSON.stringify(SAMPLE_PAYLOAD, null, 2)
+ );
+ const [syntaxError, setSyntaxError] = useState<string | null>(null);
+
+ const {
+ data: docsContent,
+ isLoading: docsLoading,
+ isError: docsIsError,
+ error: docsError,
+ } = useQuery<string, Error>({
+ queryKey: ['docs'],
+ queryFn: getDocs,
+ retry: 1,
+ staleTime: 5 * 60 * 1000,
+ });
+
+ const validationMutation = useMutation<ValidationResultDto, Error, ValidationRequestDto>({
+ mutationFn: runValidation,
+ });
+
+ const {
+ mutate: triggerValidation,
+ reset: resetValidation,
+ data: validationResult,
+ error: validationError,
+ isError: validationHasError,
+ isPending: isValidating,
+ } = validationMutation;
+
+ const handlePayloadChange = useCallback((event: React.ChangeEvent<HTMLTextAreaElement>) => {
+ setPlaygroundPayload(event.target.value);
+ }, []);
+
+ const handleTabChange = useCallback((tab: DocsTab) => {
+ setActiveTab(tab);
+ }, []);
+
+ const handleValidatePayload = useCallback(() => {
+ setSyntaxError(null);
+ resetValidation();
+
+ const trimmed = playgroundPayload.trim();
+ if (!trimmed) {
+ setSyntaxError('Payload cannot be empty.');
+ return;
+ }
+
+ try {
+ const parsed = JSON.parse(trimmed) as unknown;
+ if (!isValidationPayload(parsed)) {
+ setSyntaxError('Validation payload must be a JSON object.');
+ return;
+ }
+
+ triggerValidation(parsed);
+ } catch {
+ setSyntaxError('Invalid JSON format. Please check your payload syntax.');
+ }
+ }, [playgroundPayload, resetValidation, triggerValidation]);
+
+ const handleResetPayload = useCallback(() => {
+ setPlaygroundPayload(JSON.stringify(SAMPLE_PAYLOAD, null, 2));
+ setSyntaxError(null);
+ resetValidation();
+ }, [resetValidation]);
+
+ const handleFormatJson = useCallback(() => {
+ try {
+ const parsed = JSON.parse(playgroundPayload);
+ setPlaygroundPayload(JSON.stringify(parsed, null, 2));
+ setSyntaxError(null);
+ } catch {
+ setSyntaxError('Invalid JSON format. Unable to format.');
+ }
+ }, [playgroundPayload]);
+
+ const trimmedDocsContent = docsContent?.trim() ?? '';
+ const hasDocsContent = trimmedDocsContent.length > 0;
+
+ const renderValidationFeedback = () => {
+ if (syntaxError) {
+ return (
+ <Alert variant="destructive" className="mt-4" data-testid="validation-syntax-error">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertTitle>Validation Error</AlertTitle>
+ <AlertDescription>{syntaxError}</AlertDescription>
+ </Alert>
+ );
+ }
+
+ if (validationHasError) {
+ const errorMessage = validationError?.message ?? 'Please try again later.';
+ return (
+ <Alert variant="destructive" className="mt-4" data-testid="validation-api-error">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertTitle>Validation Error</AlertTitle>
+ <AlertDescription>{`Validation failed: ${errorMessage}`}</AlertDescription>
+ </Alert>
+ );
+ }
+
+ if (!validationResult) {
+ return null;
+ }
+
+ const { id, status, errors } = validationResult;
+ const isPass = status === 'pass';
+
+ return (
+ <div className="mt-4 space-y-4" data-testid="validation-result">
+ <div className="flex flex-wrap items-center gap-2">
+ {isPass ? (
+ <CheckCircle className="h-5 w-5 text-emerald-500" aria-hidden />
+ ) : (
+ <XCircle className="h-5 w-5 text-destructive" aria-hidden />
+ )}
+ <span className="text-base font-semibold">Validation Result</span>
+ <Badge variant={isPass ? 'success' : 'destructive'}>{isPass ? 'Pass' : 'Fail'}</Badge>
+ </div>
+
+ <div className="text-xs text-muted-foreground">
+ Validation ID:
+ <span className="ml-1 font-mono text-foreground">{id}</span>
+ </div>
+
+ {errors.length > 0 ? (
+ <div className="space-y-2">
+ <h4 className="text-sm font-semibold text-destructive">Errors ({errors.length})</h4>
+ <ul className="list-disc space-y-1 pl-5 text-sm text-destructive">
+ {errors.map((error) => (
+ <li key={error}>{error}</li>
+ ))}
+ </ul>
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ No validation issues detected. Your payload passed all configured rules.
+ </p>
+ )}
+ </div>
+ );
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-2xl font-semibold text-foreground">Documentation & Playground</h1>
+ <p className="text-muted-foreground">
+ Explore the API documentation and test validation rules with the interactive playground.
+ </p>
+ </div>
+ </div>
+
+ <div className="rounded-lg border bg-card shadow-sm">
+ <nav className="flex">
+ <button
+ type="button"
+ onClick={() => handleTabChange('docs')}
+ className={`flex-1 rounded-l-lg px-4 py-2 text-sm font-medium transition-colors ${
+ activeTab === 'docs'
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
+ }`}
+ >
+ Documentation
+ </button>
+ <button
+ type="button"
+ onClick={() => handleTabChange('playground')}
+ className={`flex-1 rounded-r-lg px-4 py-2 text-sm font-medium transition-colors ${
+ activeTab === 'playground'
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
+ }`}
+ >
+ Interactive Playground
+ </button>
+ </nav>
+ </div>
+
+ {activeTab === 'docs' && (
+ <Card>
+ <CardHeader>
+ <CardTitle>API Documentation</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {docsLoading && (
+ <div className="flex items-center justify-center py-8" data-testid="docs-loading">
+ <LoadingSpinner size="md" />
+ </div>
+ )}
+
+ {docsIsError && (
+ <Alert variant="destructive" data-testid="docs-error">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertTitle>Failed to load documentation</AlertTitle>
+ <AlertDescription>
+ {docsError?.message ?? 'Please try again later.'}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {!docsLoading && !docsIsError && !hasDocsContent && (
+ <EmptyState
+ icon={BookOpen}
+ title="Documentation unavailable"
+ description="The documentation content is not available right now. Please check back soon."
+ />
+ )}
+
+ {hasDocsContent && (
+ <div className="prose prose-sm max-w-none">
+ <ReactMarkdown>{trimmedDocsContent}</ReactMarkdown>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )}
+
+ {activeTab === 'playground' && (
+ <div className="grid gap-6 lg:grid-cols-2">
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <CardTitle>JSON Payload</CardTitle>
+ <div className="flex gap-2">
+ <Button variant="outline" size="sm" onClick={handleFormatJson} className="text-xs">
+ Format JSON
+ </Button>
+ <Button variant="outline" size="sm" onClick={handleResetPayload} className="text-xs">
+ <RotateCcw className="mr-1 h-3 w-3" />
+ Reset
+ </Button>
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="rounded-md border">
+ <TextArea
+ value={playgroundPayload}
+ onChange={handlePayloadChange}
+ className="min-h-[280px] rounded-t-md border-0 border-b border-border font-mono text-sm"
+ placeholder="Enter your JSON payload here..."
+ />
+ <JsonSyntaxPreview value={playgroundPayload} />
+ </div>
+
+ <Button
+ onClick={handleValidatePayload}
+ disabled={isValidating}
+ className="w-full"
+ data-testid="run-validation"
+ >
+ {isValidating ? (
+ <>
+ <LoadingSpinner size="sm" className="mr-2" />
+ Validating...
+ </>
+ ) : (
+ <>
+ <Play className="mr-2 h-4 w-4" />
+ Run Validation
+ </>
+ )}
+ </Button>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Validation Results</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {!validationResult && !syntaxError && !validationHasError && !isValidating && (
+ <div className="flex items-center justify-center py-12 text-muted-foreground" data-testid="validation-empty-state">
+ <div className="text-center space-y-2">
+ <Play className="mx-auto h-8 w-8 opacity-50" />
+ <p>Click "Run Validation" to test your payload.</p>
+ </div>
+ </div>
+ )}
+
+ {isValidating && (
+ <div className="flex items-center justify-center py-12" data-testid="validation-loading">
+ <div className="text-center space-y-3">
+ <LoadingSpinner size="lg" />
+ <p className="text-sm text-muted-foreground">Running validation...</p>
+ </div>
+ </div>
+ )}
+
+ {!isValidating && renderValidationFeedback()}
+ </CardContent>
+ </Card>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default Docs;