feat: implement dynamic sidebar attribute injection based on selected campaign rule events and add UI component library.

This commit is contained in:
2026-07-14 19:15:29 +07:00
parent 628d87a55b
commit 19087ec1af
37 changed files with 5807 additions and 205 deletions

1067
Use_Cases_Analysis.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -15,14 +15,20 @@
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/geist": "^5.2.9",
"@hookform/resolvers": "^5.4.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"lucide-react": "^1.24.0",
"msw": "^2.15.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-hook-form": "^7.81.0",
"react-router-dom": "^7.18.1",
"shadcn": "^4.13.0",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0"
"tw-animate-css": "^1.4.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.2",
@@ -36,5 +42,10 @@
"tailwindcss": "^4.3.2",
"typescript": "~6.0.2",
"vite": "^8.1.1"
},
"msw": {
"workerDirectory": [
"public"
]
}
}

926
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,4 @@
allowBuilds:
msw: true
minimumReleaseAgeExclude:
- lucide-react@1.24.0

361
public/mockServiceWorker.js Normal file
View File

@@ -0,0 +1,361 @@
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.15.0'
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
addEventListener('install', function () {
self.skipWaiting()
})
addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})
addEventListener('message', async function (event) {
const clientId = Reflect.get(event.source || {}, 'id')
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll({
type: 'window',
})
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
addEventListener('fetch', function (event) {
const requestInterceptedAt = Date.now()
// Bypass navigation requests.
if (event.request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (
event.request.cache === 'only-if-cached' &&
event.request.mode !== 'same-origin'
) {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
})
/**
* @param {FetchEvent} event
* @param {string} requestId
* @param {number} requestInterceptedAt
*/
async function handleRequest(event, requestId, requestInterceptedAt) {
const client = await resolveMainClient(event)
const requestCloneForEvents = event.request.clone()
const response = await getResponse(
event,
client,
requestId,
requestInterceptedAt,
)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)
// Omit the body of server-sent event stream responses.
// Cloning such responses would prevent client-side stream cancelations
// from reaching the original stream (a teed stream only cancels its
// source once both of its branches cancel) and would buffer the
// entire stream into the unconsumed clone indefinitely.
const isEventStreamResponse = response.headers
.get('content-type')
?.toLowerCase()
.startsWith('text/event-stream')
// Clone the response so both the client and the library could consume it.
const responseClone = isEventStreamResponse ? null : response.clone()
sendToClient(
client,
{
type: 'RESPONSE',
payload: {
isMockedResponse: IS_MOCKED_RESPONSE in response,
request: {
id: requestId,
...serializedRequest,
},
response: {
type: response.type,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: responseClone ? responseClone.body : null,
},
},
},
responseClone && responseClone.body
? [serializedRequest.body, responseClone.body]
: [],
)
}
return response
}
/**
* Resolve the main client for the given event.
* Client that issues a request doesn't necessarily equal the client
* that registered the worker. It's with the latter the worker should
* communicate with during the response resolving phase.
* @param {FetchEvent} event
* @returns {Promise<Client | undefined>}
*/
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (activeClientIds.has(event.clientId)) {
return client
}
if (client?.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll({
type: 'window',
})
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
/**
* @param {FetchEvent} event
* @param {Client | undefined} client
* @param {string} requestId
* @param {number} requestInterceptedAt
* @returns {Promise<Response>}
*/
async function getResponse(event, client, requestId, requestInterceptedAt) {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = event.request.clone()
function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)
// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)
if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}
return fetch(requestClone, { headers })
}
// Bypass mocking when the client is not active.
if (!client) {
return passthrough()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return passthrough()
}
// Notify the client that a request has been intercepted.
const serializedRequest = await serializeRequest(event.request)
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
interceptedAt: requestInterceptedAt,
...serializedRequest,
},
},
[serializedRequest.body],
)
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}
case 'PASSTHROUGH': {
return passthrough()
}
}
return passthrough()
}
/**
* @param {Client} client
* @param {any} message
* @param {Array<Transferable>} transferrables
* @returns {Promise<any>}
*/
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(message, [
channel.port2,
...transferrables.filter(Boolean),
])
})
}
/**
* @param {Response} response
* @returns {Response}
*/
function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}
const mockedResponse = new Response(response.body, response)
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
return mockedResponse
}
/**
* @param {Request} request
*/
async function serializeRequest(request) {
return {
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.arrayBuffer(),
keepalive: request.keepalive,
}
}

View File

@@ -1,12 +1,23 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import CampaignRuleWizard from "./pages/CampaignRuleWizard";
import { EventsList } from "./pages/EventsList";
import { EventForm } from "./pages/EventForm";
import "./index.css"; // Ensure global styles are loaded
import { Layout } from "./components/Layout";
function App() {
return (
<Layout>
<CampaignRuleWizard />
</Layout>
<BrowserRouter>
<Layout>
<Routes>
<Route path="/campaign" element={<CampaignRuleWizard />} />
<Route path="/events" element={<EventsList />} />
<Route path="/events/new" element={<EventForm />} />
<Route path="/events/:id/edit" element={<EventForm />} />
<Route path="*" element={<Navigate to="/events" replace />} />
</Routes>
</Layout>
</BrowserRouter>
);
}

View File

@@ -0,0 +1,77 @@
import { useFieldArray, type Control, type UseFormRegister } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
interface AttributeSchemaBuilderProps {
control: Control<any>;
register: UseFormRegister<any>;
}
export function AttributeSchemaBuilder({ control, register }: AttributeSchemaBuilderProps) {
const { fields, append, remove } = useFieldArray({
control,
name: 'attributes',
});
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-medium">Attributes Schema</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ key: '', type: 'STRING', required: false })}
>
<Plus className="w-4 h-4 mr-2" /> Add Attribute
</Button>
</div>
{fields.length === 0 && (
<p className="text-sm text-gray-500">No attributes defined. Payload will be empty.</p>
)}
<div className="space-y-3">
{fields.map((field, index) => (
<div key={field.id} className="flex items-center gap-3 bg-gray-50 p-3 rounded-md border">
<div className="flex-1">
<Input
placeholder="Attribute Key (e.g. userId)"
{...register(`attributes.${index}.key` as const, { required: true })}
/>
</div>
<div className="w-40">
<select
className="w-full h-10 px-3 py-2 border rounded-md bg-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
{...register(`attributes.${index}.type` as const)}
>
<option value="STRING">String</option>
<option value="NUMBER">Number</option>
<option value="BOOLEAN">Boolean</option>
<option value="DATETIME">DateTime</option>
</select>
</div>
<div className="flex items-center gap-2 w-24">
<input
type="checkbox"
id={`req-${field.id}`}
className="w-4 h-4"
{...register(`attributes.${index}.required` as const)}
/>
<label htmlFor={`req-${field.id}`} className="text-sm">Required</label>
</div>
<Button
type="button"
variant="destructive"
size="icon"
onClick={() => remove(index)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,361 @@
import { useEffect, useState } from 'react';
import { useFieldArray, useWatch, Controller, type Control, type UseFormRegister } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { ThresholdsBuilder } from './ThresholdsBuilder';
const getAvailableOperations = (type?: string) => {
switch (type) {
case 'NUMBER': return [{ value: 'INCREMENT', label: 'Increment' }, { value: 'STREAK_INCREMENT', label: 'Streak Increment' }];
case 'DATETIME': return [{ value: 'COMPUTE_GAP', label: 'Compute Gap' }, { value: 'CHECK_AND_UPDATE_TIMER', label: 'Check & Update Timer' }];
case 'BOOLEAN': return [{ value: 'SET_TRUE_ONCE', label: 'Set True Once' }];
case 'STRING': return [{ value: 'APPEND_UNIQUE', label: 'Append Unique' }];
default: return [
{ value: 'INCREMENT', label: 'Increment' },
{ value: 'STREAK_INCREMENT', label: 'Streak Increment' },
{ value: 'COMPUTE_GAP', label: 'Compute Gap' },
{ value: 'APPEND_UNIQUE', label: 'Append Unique' },
{ value: 'SET_TRUE_ONCE', label: 'Set True Once' },
{ value: 'CHECK_AND_UPDATE_TIMER', label: 'Check & Update Timer' }
];
}
};
interface InstructionsBuilderProps {
control: Control<any>;
register: UseFormRegister<any>;
}
export function InstructionsBuilder({ control, register }: InstructionsBuilderProps) {
const { fields, append, remove } = useFieldArray({
control,
name: 'instructions',
});
const [schema, setSchema] = useState<Record<string, { code: string; type: string }[]>>({});
useEffect(() => {
fetch('/api/v1/attributes/schema')
.then(res => res.json())
.then(data => setSchema(data))
.catch(console.error);
}, []);
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-medium">Counter Instructions</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ name: '', entityType: '', attributeCode: '', operation: 'INCREMENT', thresholds: [] })}
>
<Plus className="w-4 h-4 mr-2" /> Add Instruction
</Button>
</div>
{fields.length === 0 && (
<p className="text-sm text-gray-500">No instructions defined.</p>
)}
<Accordion type="multiple" className="w-full space-y-4">
{fields.map((field, index) => (
<InstructionRow
key={field.id}
fieldId={field.id}
index={index}
control={control}
register={register}
remove={remove}
schema={schema}
/>
))}
</Accordion>
</div>
);
}
function InstructionRow({ fieldId, index, control, register, remove, schema }: any) {
const instructionName = useWatch({ control, name: `instructions.${index}.name` });
const currentEntity = useWatch({ control, name: `instructions.${index}.entityType` });
const currentAttributeCode = useWatch({ control, name: `instructions.${index}.attributeCode` });
const currentOperation = useWatch({ control, name: `instructions.${index}.operation` });
const entities = Object.keys(schema);
const getAttributes = (entity: string) => {
if (!entity || !schema) return [];
const key = Object.keys(schema).find(k => k.toLowerCase() === entity.toLowerCase());
return key ? schema[key] : [];
};
const availableAttributes = getAttributes(currentEntity);
const currentAttribute = availableAttributes.find((attr: any) => attr.code === currentAttributeCode);
const attributeType = currentAttribute?.type;
const availableOperations = getAvailableOperations(attributeType);
return (
<AccordionItem value={fieldId} className="bg-gray-50 border rounded-md px-4">
<div className="flex items-center justify-between w-full">
<AccordionTrigger className="hover:no-underline flex-1 py-4 font-semibold text-gray-700">
{`▼ Instruction ${index + 1}: ${instructionName || 'New Instruction'}`}
</AccordionTrigger>
<Button
type="button"
variant="ghost"
size="sm"
className="text-gray-500 hover:text-red-600 hover:bg-red-50 ml-4"
onClick={(e) => {
e.preventDefault();
remove(index);
}}
>
<Trash2 className="w-4 h-4 mr-1" /> Delete
</Button>
</div>
<AccordionContent className="pb-4 pt-2">
<div className="flex items-center gap-3 mb-4">
<span className="text-sm font-medium text-gray-700 min-w-[120px]">Instruction Name:</span>
<Input
placeholder="e.g. Counter Lượt Xem Tuần"
className="bg-white h-9 flex-1"
{...register(`instructions.${index}.name` as const, { required: true })}
/>
</div>
<div className="flex items-start justify-between gap-4 mb-4">
<div className="grid grid-cols-3 gap-3 flex-1">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Target Entity</label>
<Controller
control={control}
name={`instructions.${index}.entityType` as const}
rules={{ required: true }}
render={({ field }) => {
const normalizedValue = entities.find(e => e.toLowerCase() === field.value?.toLowerCase()) || field.value;
return (
<Select
onValueChange={field.onChange}
value={normalizedValue || ""}
items={entities.reduce((acc, e) => ({ ...acc, [e]: e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() }), {})}
>
<SelectTrigger className="bg-white h-9">
<SelectValue placeholder="Select Entity" />
</SelectTrigger>
<SelectContent>
{entities.map(e => {
const display = e.charAt(0).toUpperCase() + e.slice(1).toLowerCase();
return <SelectItem key={e} value={e} label={display}>{display}</SelectItem>;
})}
</SelectContent>
</Select>
);
}}
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Target Attribute</label>
<Controller
control={control}
name={`instructions.${index}.attributeCode` as const}
rules={{ required: true }}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value || ""}
disabled={!currentEntity}
items={availableAttributes.reduce((acc: any, attr: any) => ({ ...acc, [attr.code]: attr.code }), {})}
>
<SelectTrigger className="bg-white h-9">
<SelectValue placeholder="Select Attribute" />
</SelectTrigger>
<SelectContent>
{availableAttributes.map((attr: any) => (
<SelectItem key={attr.code} value={attr.code} label={attr.code}>
{attr.code} <span className="text-[10px] text-muted-foreground ml-2">({attr.type})</span>
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Operation</label>
<Controller
control={control}
name={`instructions.${index}.operation` as const}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value || ""}
items={availableOperations.reduce((acc, op) => ({ ...acc, [op.value]: op.label }), {})}
>
<SelectTrigger className="bg-white h-9">
<SelectValue placeholder="Select Operation" />
</SelectTrigger>
<SelectContent>
{availableOperations.map(op => (
<SelectItem key={op.value} value={op.value} label={op.label}>{op.label}</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
</div>
</div>
<DynamicFields control={control} register={register} index={index} />
{currentOperation !== 'SET_TRUE_ONCE' && (
<ThresholdsBuilder control={control} register={register} instructionIndex={index} attributeType={attributeType} operation={currentOperation} />
)}
</AccordionContent>
</AccordionItem>
);
}
function DynamicFields({ control, register, index }: { control: Control<any>, register: UseFormRegister<any>, index: number }) {
const operation = useWatch({
control,
name: `instructions.${index}.operation`
});
if (operation === 'INCREMENT' || operation === 'DECREMENT') {
return (
<div className="mb-4 bg-white p-3 rounded border">
<h4 className="text-sm font-medium text-gray-700 mb-3">Counter Configuration</h4>
<div className="flex gap-4">
<div className="flex-1">
<label className="block text-xs text-gray-500 mb-1">Period Type (Lazy Reset)</label>
<Controller
control={control}
name={`instructions.${index}.periodType` as const}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value || "LIFETIME"}
items={{
LIFETIME: 'Lifetime (No Reset)',
DAILY: 'Daily',
WEEKLY: 'Weekly',
MONTHLY: 'Monthly',
YEARLY: 'Yearly'
}}
>
<SelectTrigger className="bg-white h-9">
<SelectValue placeholder="Select Period" />
</SelectTrigger>
<SelectContent>
<SelectItem value="LIFETIME" label="Lifetime (No Reset)">Lifetime (No Reset)</SelectItem>
<SelectItem value="DAILY" label="Daily">Daily</SelectItem>
<SelectItem value="WEEKLY" label="Weekly">Weekly</SelectItem>
<SelectItem value="MONTHLY" label="Monthly">Monthly</SelectItem>
<SelectItem value="YEARLY" label="Yearly">Yearly</SelectItem>
</SelectContent>
</Select>
)}
/>
</div>
<div className="w-48">
<label className="block text-xs text-gray-500 mb-1">Step</label>
<Input
type="number"
placeholder="e.g. 1"
className="bg-white h-9"
{...register(`instructions.${index}.step` as const, { valueAsNumber: true })}
/>
</div>
</div>
</div>
);
}
if (operation === 'APPEND_UNIQUE') {
return (
<div className="mb-4 bg-white p-3 rounded border">
<h4 className="text-sm font-medium text-gray-700 mb-3">Value Mapping</h4>
<div className="flex gap-4">
<div className="flex-1">
<label className="block text-xs text-gray-500 mb-1">Source Field</label>
<Input
placeholder="e.g. event.itemId"
className="bg-white h-9"
{...register(`instructions.${index}.sourceField` as const)}
/>
</div>
<div className="w-48">
<label className="block text-xs text-gray-500 mb-1">Max Length</label>
<Input
type="number"
placeholder="e.g. 100"
className="bg-white h-9"
{...register(`instructions.${index}.maxLength` as const, { valueAsNumber: true })}
/>
</div>
</div>
</div>
);
}
if (operation === 'SET_TRUE_ONCE') {
return (
<div className="mb-4 bg-white p-3 rounded border">
<h4 className="text-sm font-medium text-gray-700 mb-3">One-Time Transition Trigger</h4>
<div className="flex-1">
<label className="block text-xs text-gray-500 mb-1">Trigger Event (on False True)</label>
<Input
placeholder="e.g. First_Login_Reward"
className="bg-white h-9"
{...register(`instructions.${index}.triggerEventOnSuccess` as const)}
/>
</div>
</div>
);
}
if (operation === 'COMPUTE_GAP' || operation === 'CHECK_AND_UPDATE_TIMER') {
return (
<div className="mb-4 bg-white p-3 rounded border">
<label className="block text-xs text-gray-500 mb-1">Unit</label>
<Controller
control={control}
name={`instructions.${index}.unit` as const}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value || ""}
items={{
DAYS: 'Days',
HOURS: 'Hours',
MINUTES: 'Minutes'
}}
>
<SelectTrigger className="bg-white h-9 w-48">
<SelectValue placeholder="Select Unit" />
</SelectTrigger>
<SelectContent>
<SelectItem value="DAYS" label="Days">Days</SelectItem>
<SelectItem value="HOURS" label="Hours">Hours</SelectItem>
<SelectItem value="MINUTES" label="Minutes">Minutes</SelectItem>
</SelectContent>
</Select>
)}
/>
</div>
);
}
return null;
}

View File

@@ -1,8 +1,37 @@
import React from "react";
import { LayoutDashboard, Settings, Bell, Search, User, Megaphone } from "lucide-react";
import { Link, useLocation } from "react-router-dom";
import { LayoutDashboard, Settings, Bell, Search, User, Megaphone, Calendar } from "lucide-react";
import { Button } from "./ui/button";
export function Layout({ children }: { children: React.ReactNode }) {
const location = useLocation();
const path = location.pathname;
const getMenuClass = (basePath: string) => {
const isActive = path.startsWith(basePath);
return isActive
? "flex items-center gap-3 px-3 py-2 bg-primary/10 text-primary rounded-md font-medium"
: "flex items-center gap-3 px-3 py-2 text-gray-600 hover:bg-gray-50 rounded-md font-medium";
};
let pageTitle = "Dashboard";
let breadcrumbs = ["Dashboard"];
if (path.startsWith("/campaign")) {
pageTitle = "Campaign Rule";
breadcrumbs = ["Campaign Management", "Campaign Rule", "Create Campaign Rule"];
} else if (path.startsWith("/events")) {
pageTitle = "Events List";
breadcrumbs = ["Event Management", "Events List"];
if (path.includes("/new")) {
pageTitle = "Create Event";
breadcrumbs = ["Event Management", "Events List", "Create Event"];
} else if (path.includes("/edit")) {
pageTitle = "Edit Event";
breadcrumbs = ["Event Management", "Events List", "Edit Event"];
}
}
return (
<div className="flex h-screen w-full bg-gray-50 text-gray-900 overflow-hidden">
{/* Sidebar */}
@@ -16,14 +45,18 @@ export function Layout({ children }: { children: React.ReactNode }) {
</div>
</div>
<nav className="flex-1 p-4 space-y-1">
<a href="#" className="flex items-center gap-3 px-3 py-2 text-gray-600 hover:bg-gray-50 rounded-md font-medium">
<Link to="/" className={path === "/" ? "flex items-center gap-3 px-3 py-2 bg-primary/10 text-primary rounded-md font-medium" : "flex items-center gap-3 px-3 py-2 text-gray-600 hover:bg-gray-50 rounded-md font-medium"}>
<LayoutDashboard size={20} />
Dashboard
</a>
<a href="#" className="flex items-center gap-3 px-3 py-2 bg-primary/10 text-primary rounded-md font-medium">
</Link>
<Link to="/campaign" className={getMenuClass("/campaign")}>
<Settings size={20} />
Campaigns
</a>
</Link>
<Link to="/events" className={getMenuClass("/events")}>
<Calendar size={20} />
Events
</Link>
</nav>
</aside>
@@ -33,13 +66,14 @@ export function Layout({ children }: { children: React.ReactNode }) {
<header className="h-16 bg-white border-b flex items-center justify-between px-6">
<div className="flex items-center gap-4 flex-1">
<div className="flex flex-col">
<h1 className="text-[15px] font-semibold text-slate-800">Campaign Rule</h1>
<h1 className="text-[15px] font-semibold text-slate-800">{pageTitle}</h1>
<div className="text-muted-foreground text-[11px] mt-0.5 flex items-center gap-1.5">
<span>Campaign Management</span>
<span className="text-slate-300">/</span>
<span>Campaign Rule</span>
<span className="text-slate-300">/</span>
<span className="text-slate-600">Create Campaign Rule</span>
{breadcrumbs.map((crumb, index) => (
<React.Fragment key={index}>
<span className={index === breadcrumbs.length - 1 ? "text-slate-600" : ""}>{crumb}</span>
{index < breadcrumbs.length - 1 && <span className="text-slate-300">/</span>}
</React.Fragment>
))}
</div>
</div>
</div>

View File

@@ -0,0 +1,205 @@
import { useEffect, useState } from 'react';
import { useFieldArray, Controller, type Control, type UseFormRegister } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
import { CreatableCombobox } from '@/components/ui/creatable-combobox';
import { Badge } from '@/components/ui/badge';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
const getAvailableConditions = (type?: string) => {
switch (type) {
case 'BOOLEAN':
case 'STRING':
return [{ value: '==', label: '==' }];
case 'NUMBER':
case 'DATETIME':
default:
return [
{ value: '>=', label: '>=' },
{ value: '<=', label: '<=' },
{ value: '==', label: '==' },
{ value: '>', label: '>' },
{ value: '<', label: '<' }
];
}
};
interface ThresholdsBuilderProps {
control: Control<any>;
register: UseFormRegister<any>;
instructionIndex: number;
attributeType?: string;
operation?: string;
}
export function ThresholdsBuilder({ control, register, instructionIndex, attributeType, operation }: ThresholdsBuilderProps) {
const showResetPolicy = operation === 'INCREMENT' || operation === 'APPEND_UNIQUE' || operation === 'STREAK_INCREMENT';
const availableConditions = getAvailableConditions(attributeType);
const defaultOperator = availableConditions[0]?.value || '>=';
const defaultValue = attributeType === 'BOOLEAN' ? true : attributeType === 'STRING' ? '' : 0;
const { fields, append, remove } = useFieldArray({
control,
name: `instructions.${instructionIndex}.thresholds`,
});
const [eventOptions, setEventOptions] = useState<string[]>([]);
useEffect(() => {
fetch('/api/v1/events')
.then(res => res.json())
.then(data => {
if (Array.isArray(data)) {
setEventOptions(Array.from(new Set(data.map((e: any) => e.name))));
}
})
.catch(console.error);
}, []);
return (
<div className="space-y-3 mt-4 border-l-2 border-blue-200 pl-4">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-gray-700">Thresholds Config</h4>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => append({ operator: defaultOperator, value: defaultValue, triggerEvent: '', resetPolicy: 'NONE' })}
>
<Plus className="w-3 h-3 mr-1" /> Add Threshold
</Button>
</div>
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="flex flex-col gap-4 bg-white p-4 rounded border border-gray-200">
<div className="flex items-center gap-6">
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-700 w-24">Condition:</span>
<Controller
control={control}
name={`instructions.${instructionIndex}.thresholds.${index}.operator` as const}
defaultValue={defaultOperator}
render={({ field }) => {
const currentValue = availableConditions.find(c => c.value === field.value) ? field.value : defaultOperator;
return (
<Select
onValueChange={field.onChange}
value={currentValue}
items={availableConditions.reduce((acc, c) => ({ ...acc, [c.value]: c.label }), {})}
>
<SelectTrigger className="bg-white h-9 w-[70px] px-2 text-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
{availableConditions.map(c => (
<SelectItem key={c.value} value={c.value} label={c.label}>{c.label}</SelectItem>
))}
</SelectContent>
</Select>
)}}
/>
{attributeType === 'BOOLEAN' ? (
<Controller
control={control}
name={`instructions.${instructionIndex}.thresholds.${index}.value` as const}
rules={{ required: true }}
render={({ field }) => (
<Select
onValueChange={(val) => field.onChange(val === 'true')}
value={field.value !== undefined ? String(field.value) : ""}
items={{
'true': 'True',
'false': 'False'
}}
>
<SelectTrigger className="bg-white h-9 w-24">
<SelectValue placeholder="Value" />
</SelectTrigger>
<SelectContent>
<SelectItem value="true" label="True">True</SelectItem>
<SelectItem value="false" label="False">False</SelectItem>
</SelectContent>
</Select>
)}
/>
) : (
<Input
type={attributeType === 'STRING' ? 'text' : 'number'}
placeholder="Value"
className="h-9 w-24"
{...register(`instructions.${instructionIndex}.thresholds.${index}.value` as const, { required: true, valueAsNumber: attributeType === 'NUMBER' })}
/>
)}
</div>
<div className="flex items-center gap-3 flex-1 min-w-[250px] ml-4">
<span className="text-sm font-medium text-gray-700 whitespace-nowrap">Trigger: Fire Event</span>
<div className="flex-1">
<Controller
control={control}
name={`instructions.${instructionIndex}.thresholds.${index}.triggerEvent`}
render={({ field }) => (
<CreatableCombobox
options={eventOptions}
value={field.value}
onChange={field.onChange}
placeholder="e.g. milestone_reached"
/>
)}
/>
</div>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="h-9 w-9 text-red-500 hover:text-red-700 hover:bg-red-50 ml-auto"
onClick={() => remove(index)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
{showResetPolicy && (
<div className="flex items-center gap-6 pt-3 mt-2 border-t border-gray-100">
<span className="text-sm font-medium text-gray-700 w-24">Reset Policy:</span>
<Controller
control={control}
name={`instructions.${instructionIndex}.thresholds.${index}.resetPolicy`}
render={({ field }) => (
<RadioGroup
onValueChange={field.onChange}
value={field.value || ""}
className="flex flex-wrap gap-6"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="NONE" id={`r-none-${index}`} />
<Label htmlFor={`r-none-${index}`} className="cursor-pointer text-sm font-normal text-gray-600">NONE</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="RESET_ON_TRIGGER" id={`r-reset-${index}`} />
<Label htmlFor={`r-reset-${index}`} className="cursor-pointer text-sm font-normal text-gray-600">RESET_ON_TRIGGER</Label>
</div>
</RadioGroup>
)}
/>
</div>
)}
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,72 @@
import { Accordion as AccordionPrimitive } from "@base-ui/react/accordion"
import { cn } from "@/lib/utils"
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
function Accordion({ className, ...props }: AccordionPrimitive.Root.Props) {
return (
<AccordionPrimitive.Root
data-slot="accordion"
className={cn("flex w-full flex-col", className)}
{...props}
/>
)
}
function AccordionItem({ className, ...props }: AccordionPrimitive.Item.Props) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("not-last:border-b", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: AccordionPrimitive.Trigger.Props) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"group/accordion-trigger relative flex flex-1 items-start justify-between rounded-lg border border-transparent py-2.5 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:after:border-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
className
)}
{...props}
>
{children}
<ChevronDownIcon data-slot="accordion-trigger-icon" className="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden" />
<ChevronUpIcon data-slot="accordion-trigger-icon" className="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: AccordionPrimitive.Panel.Props) {
return (
<AccordionPrimitive.Panel
data-slot="accordion-content"
className="overflow-hidden text-sm data-open:animate-accordion-down data-closed:animate-accordion-up"
{...props}
>
<div
className={cn(
"h-(--accordion-panel-height) pt-0 pb-2.5 data-ending-style:h-0 data-starting-style:h-0 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
className
)}
>
{children}
</div>
</AccordionPrimitive.Panel>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@@ -0,0 +1,52 @@
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary:
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
return useRender({
defaultTagName: "span",
props: mergeProps<"span">(
{
className: cn(badgeVariants({ variant }), className),
},
props
),
render,
state: {
slot: "badge",
variant,
},
})
}
export { Badge, badgeVariants }

103
src/components/ui/card.tsx Normal file
View File

@@ -0,0 +1,103 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-(--card-spacing)", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,196 @@
"use client"
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
InputGroup,
InputGroupAddon,
} from "@/components/ui/input-group"
import { SearchIcon, CheckIcon } from "lucide-react"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = false,
...props
}: Omit<React.ComponentProps<typeof Dialog>, "children"> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
children: React.ReactNode
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn(
"top-1/3 translate-y-0 overflow-hidden rounded-xl! p-0",
className
)}
showCloseButton={showCloseButton}
>
{children}
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div data-slot="command-input-wrapper" className="p-1 pb-0">
<InputGroup className="h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!">
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
<InputGroupAddon>
<SearchIcon className="size-4 shrink-0 opacity-50" />
</InputGroupAddon>
</InputGroup>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none",
className
)}
{...props}
/>
)
}
function CommandEmpty({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className={cn("py-6 text-center text-sm", className)}
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
)
}
function CommandItem({
className,
children,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",
className
)}
{...props}
>
{children}
<CheckIcon className="ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100" />
</CommandPrimitive.Item>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-data-selected/command-item:text-foreground",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@@ -0,0 +1,116 @@
import * as React from "react"
import { Check, ChevronsUpDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
interface CreatableComboboxProps {
options: string[]
value?: string
onChange: (value: string) => void
placeholder?: string
emptyText?: string
}
export function CreatableCombobox({
options,
value,
onChange,
placeholder = "Select or create...",
emptyText = "No results found.",
}: CreatableComboboxProps) {
const [open, setOpen] = React.useState(false)
const [inputValue, setInputValue] = React.useState("")
const exactMatchExists = options.some(
option => option.toLowerCase() === inputValue.toLowerCase()
)
const showCreateOption = inputValue.trim() !== "" && !exactMatchExists
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
render={
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-full justify-between font-normal"
/>
}
>
{value || placeholder}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</PopoverTrigger>
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
<Command filter={(value, search) => {
if (value.toLowerCase().includes(search.toLowerCase())) return 1
return 0
}}>
<CommandInput
placeholder={placeholder}
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{showCreateOption ? null : emptyText}
</CommandEmpty>
<CommandGroup>
{options.map((option) => (
<CommandItem
key={option}
value={option}
onSelect={() => {
onChange(option)
setOpen(false)
setInputValue("")
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === option ? "opacity-100" : "opacity-0"
)}
/>
{option}
</CommandItem>
))}
{showCreateOption && (
<CommandItem
value={inputValue}
onSelect={() => {
onChange(inputValue.trim())
setOpen(false)
setInputValue("")
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === inputValue.trim() ? "opacity-100" : "opacity-0"
)}
/>
Create "{inputValue}"
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,266 @@
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import { cn } from "@/lib/utils"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
align = "start",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
className="isolate z-50 outline-none"
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuLabel({
className,
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.GroupLabel
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.SubmenuTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
}
function DropdownMenuSubContent({
align = "start",
alignOffset = -3,
side = "right",
sideOffset = 0,
className,
...props
}: React.ComponentProps<typeof DropdownMenuContent>) {
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
return (
<MenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
}
function DropdownMenuSeparator({
className,
...props
}: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -0,0 +1,156 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
"group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
className
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
"inline-start":
"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
"inline-end":
"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
"block-start":
"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
"block-end":
"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
},
},
defaultVariants: {
align: "inline-start",
},
}
)
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return
}
e.currentTarget.parentElement?.querySelector("input")?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva(
"flex items-center gap-2 text-sm shadow-none",
{
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
sm: "",
"icon-xs":
"size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
}
)
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size" | "type"> &
VariantProps<typeof inputGroupButtonVariants> & {
type?: "button" | "submit" | "reset"
}) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function InputGroupInput({
className,
...props
}: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className
)}
{...props}
/>
)
}
function InputGroupTextarea({
className,
...props
}: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}

View File

@@ -9,7 +9,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
"h-9 w-full min-w-0 rounded-lg border border-input bg-background px-3 py-2 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}

View File

@@ -0,0 +1,88 @@
import * as React from "react"
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
import { cn } from "@/lib/utils"
function Popover({ ...props }: PopoverPrimitive.Root.Props) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
...props
}: PopoverPrimitive.Popup.Props &
Pick<
PopoverPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Positioner
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
className="isolate z-50"
>
<PopoverPrimitive.Popup
data-slot="popover-content"
className={cn(
"z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</PopoverPrimitive.Positioner>
</PopoverPrimitive.Portal>
)
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-0.5 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
return (
<PopoverPrimitive.Title
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: PopoverPrimitive.Description.Props) {
return (
<PopoverPrimitive.Description
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
}

View File

@@ -0,0 +1,38 @@
"use client"
import { Radio as RadioPrimitive } from "@base-ui/react/radio"
import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group"
import { cn } from "@/lib/utils"
function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {
return (
<RadioGroupPrimitive
data-slot="radio-group"
className={cn("grid w-full gap-2", className)}
{...props}
/>
)
}
function RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {
return (
<RadioPrimitive.Root
data-slot="radio-group-item"
className={cn(
"group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
className
)}
{...props}
>
<RadioPrimitive.Indicator
data-slot="radio-group-indicator"
className="flex size-4 items-center justify-center"
>
<span className="absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground" />
</RadioPrimitive.Indicator>
</RadioPrimitive.Root>
)
}
export { RadioGroup, RadioGroupItem }

View File

@@ -0,0 +1,201 @@
"use client"
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
const Select = SelectPrimitive.Root
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
)
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
data-slot="select-value"
className={cn("flex flex-1 text-left", className)}
{...props}
/>
)
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-full items-center justify-between gap-1.5 rounded-lg border border-input bg-background py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon
render={
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
}
/>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
side = "bottom",
sideOffset = 4,
align = "center",
alignOffset = 0,
alignItemWithTrigger = true,
...props
}: SelectPrimitive.Popup.Props &
Pick<
SelectPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Positioner
side={side}
sideOffset={sideOffset}
align={align}
alignOffset={alignOffset}
alignItemWithTrigger={alignItemWithTrigger}
className="isolate z-50"
>
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.List>{children}</SelectPrimitive.List>
<SelectScrollDownButton />
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">
{children}
</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator
render={
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
}
>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
return (
<SelectPrimitive.ScrollUpArrow
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronUpIcon
/>
</SelectPrimitive.ScrollUpArrow>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
return (
<SelectPrimitive.ScrollDownArrow
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronDownIcon
/>
</SelectPrimitive.ScrollDownArrow>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,25 @@
"use client"
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
...props
}: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
data-slot="separator"
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,30 @@
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "@/lib/utils"
function Switch({
className,
size = "default",
...props
}: SwitchPrimitive.Root.Props & {
size?: "sm" | "default"
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
/>
</SwitchPrimitive.Root>
)
}
export { Switch }

114
src/components/ui/table.tsx Normal file
View File

@@ -0,0 +1,114 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -1,5 +1,6 @@
import { createContext, useContext, useState } from "react";
import { createContext, useContext, useState, useEffect } from "react";
import type { ReactNode } from "react";
import type { Event } from "../types/event";
export type RuleCondition = {
id: string;
@@ -29,6 +30,9 @@ export type CampaignRuleState = {
};
formula: any;
notification: any;
availableEvents: Event[];
isLoadingEvents: boolean;
eventsError: string | null;
};
type CampaignRuleContextType = {
@@ -52,6 +56,9 @@ const initialState: CampaignRuleState = {
},
formula: {},
notification: {},
availableEvents: [],
isLoadingEvents: false,
eventsError: null,
};
const CampaignRuleContext = createContext<CampaignRuleContextType | undefined>(undefined);
@@ -60,6 +67,21 @@ export const CampaignRuleProvider = ({ children }: { children: ReactNode }) => {
const [state, setState] = useState<CampaignRuleState>(initialState);
const [currentStep, setCurrentStep] = useState(0);
useEffect(() => {
const fetchEvents = async () => {
setState((prev) => ({ ...prev, isLoadingEvents: true, eventsError: null }));
try {
const res = await fetch('/api/v1/events');
if (!res.ok) throw new Error('Failed to fetch events');
const data = await res.json();
setState((prev) => ({ ...prev, availableEvents: data, isLoadingEvents: false }));
} catch (err: any) {
setState((prev) => ({ ...prev, eventsError: err.message, isLoadingEvents: false }));
}
};
fetchEvents();
}, []);
const updateState = (section: keyof CampaignRuleState, payload: any) => {
setState((prev) => ({
...prev,

View File

@@ -3,8 +3,18 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
async function enableMocking() {
if (import.meta.env.MODE !== 'development') {
return
}
const { worker } = await import('./mocks/browser')
return worker.start()
}
enableMocking().then(() => {
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
})

4
src/mocks/browser.ts Normal file
View File

@@ -0,0 +1,4 @@
import { setupWorker } from 'msw/browser'
import { handlers } from './handlers'
export const worker = setupWorker(...handlers)

276
src/mocks/handlers.ts Normal file
View File

@@ -0,0 +1,276 @@
import { http, HttpResponse, delay } from 'msw'
import type { Event } from '../types/event'
let events: Event[] = [
{
id: 'event-login-unified',
name: 'Login',
type: 'COUNTER',
targetTopic: 'tracking-topic',
attributes: [
{ id: 'attr-login-1', key: 'customerId', displayName: 'Mã Khách Hàng', type: 'STRING', required: true }
],
instructions: [
{
id: 'inst-login-1',
name: 'First Login Bonus',
entityType: 'Customer',
attributeCode: 'first_login_flag',
operation: 'SET_TRUE_ONCE',
triggerEventOnSuccess: 'First_Login_Reward'
},
{
id: 'inst-login-2',
name: 'Login Streak',
entityType: 'Customer',
attributeCode: 'current_streak',
operation: 'STREAK_INCREMENT',
thresholds: [
{ id: 'th-login-2', operator: '>=', value: 7, triggerEvent: 'Login_Streak_7_Days', resetPolicy: 'NONE' },
{ id: 'th-login-3', operator: '>=', value: 30, triggerEvent: 'Login_Streak_30_Days', resetPolicy: 'RESET_ON_TRIGGER' }
]
},
{
id: 'inst-login-3',
name: 'Inactivity Monitor',
entityType: 'Customer',
attributeCode: 'last_login_date',
operation: 'CHECK_AND_UPDATE_TIMER',
thresholds: [
{ id: 'th-login-4', operator: '>=', value: 90, triggerEvent: 'Account_Reactivated', resetPolicy: 'NONE' }
]
}
]
},
{
id: 'uc-03',
name: 'View_Item',
type: 'COUNTER',
targetTopic: 'tracking-topic',
attributes: [
{ id: 'attr-uc03-1', key: 'customerId', displayName: 'Mã Khách Hàng', type: 'STRING', required: true },
{ id: 'attr-uc03-2', key: 'itemId', displayName: 'Mã Sản Phẩm', type: 'STRING', required: true }
],
instructions: [
{
id: 'inst-uc03-1',
name: 'Weekly View Count',
entityType: 'Customer',
attributeCode: 'weekly_view_count',
operation: 'INCREMENT',
periodType: 'WEEKLY',
step: 1,
thresholds: [
{ id: 'th-uc03-1', operator: '>=', value: 10, triggerEvent: 'View_10_Items_Reward', resetPolicy: 'RESET_ON_TRIGGER' }
]
},
{
id: 'inst-uc03-2',
name: 'Item View Count',
entityType: 'Item',
attributeCode: 'item_view_count',
operation: 'INCREMENT',
step: 1,
thresholds: []
},
{
id: 'inst-uc03-3',
name: 'Recently Viewed Items',
entityType: 'Customer',
attributeCode: 'recently_viewed',
operation: 'APPEND_UNIQUE',
sourceField: 'event.itemId',
maxLength: 50,
thresholds: []
}
]
},
{
id: 'uc-04',
name: 'Transfer_Balance',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: 'TRANSFER',
attributes: [
{ id: 'attr-uc04-1', key: 'fromCustomerId', displayName: 'Người Gửi', type: 'STRING', required: true },
{ id: 'attr-uc04-2', key: 'toCustomerId', displayName: 'Người Nhận', type: 'STRING', required: true },
{ id: 'attr-uc04-3', key: 'amount', displayName: 'Số Tiền', type: 'NUMBER', required: true }
]
},
{
id: 'uc-06',
name: 'Welcome_Offer',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: 'NEW_CARD_REWARD',
attributes: [
{ id: 'attr-uc06-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc06-2', key: 'cardId', type: 'STRING', required: true }
]
},
{
id: 'uc-07',
name: 'Profile_Completed',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: 'PROFILE_COMPLETE_REWARD',
attributes: [
{ id: 'attr-uc07-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc07-2', key: 'completedAt', type: 'DATETIME', required: true }
]
},
{
id: 'uc-08',
name: 'Survey_Completed',
type: 'COUNTER',
targetTopic: 'events-topic',
transactionCode: 'SURVEY_REWARD',
attributes: [
{ id: 'attr-uc08-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc08-2', key: 'surveyId', type: 'STRING', required: true }
],
instructions: [
{
id: 'inst-uc08-1',
name: 'Mark Survey Completed',
entityType: 'Customer',
attributeCode: 'survey_completed',
operation: 'SET_TRUE_ONCE',
triggerEventOnSuccess: 'Survey_Completed_Reward',
thresholds: []
}
]
},
{
id: 'uc-09',
name: 'Redeem_Item',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: 'REDEEM',
attributes: [
{ id: 'attr-uc09-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc09-2', key: 'itemId', type: 'STRING', required: true },
{ id: 'attr-uc09-3', key: 'pointCost', type: 'NUMBER', required: true }
]
},
{
id: 'uc-10',
name: 'Voucher_Used',
type: 'NOTIFICATION',
targetTopic: 'noti-topic',
notificationId: 'TPL_VOUCHER_USED',
attributes: [
{ id: 'attr-uc10-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc10-2', key: 'voucherName', type: 'STRING', required: true }
]
},
{
id: 'uc-11',
name: 'Password_Expiring',
type: 'NOTIFICATION',
targetTopic: 'noti-topic',
notificationId: 'TPL_PWD_EXP',
attributes: [
{ id: 'attr-uc11-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc11-2', key: 'expiryDate', type: 'DATETIME', required: true }
]
},
{
id: 'uc-12',
name: 'Item_Redeemed_Count',
type: 'COUNTER',
targetTopic: 'tracking-topic',
attributes: [
{ id: 'attr-uc12-1', key: 'itemId', type: 'STRING', required: true }
],
instructions: [
{
id: 'inst-uc12-1',
name: 'Total Redeem Count',
entityType: 'Item',
attributeCode: 'total_redeem_count',
operation: 'INCREMENT',
thresholds: []
}
]
},
{
id: 'uc-13',
name: 'Dormant_User',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: 'DORMANT_REWARD',
attributes: [
{ id: 'attr-uc13-1', key: 'customerId', type: 'STRING', required: true },
{ id: 'attr-uc13-2', key: 'inactiveDays', type: 'NUMBER', required: true }
]
}
].map(e => ({ ...e, status: e.status || 'ACTIVE' })) as Event[];
export const handlers = [
http.get('/api/v1/events', async () => {
await delay(300);
return HttpResponse.json(events);
}),
http.get('/api/v1/events/:id', async ({ params }) => {
await delay(300);
const event = events.find(e => e.id === params.id);
if (!event) return new HttpResponse(null, { status: 404 });
return HttpResponse.json(event);
}),
http.post('/api/v1/events', async ({ request }) => {
await delay(500);
const newEvent = await request.json() as Event;
newEvent.id = Math.random().toString(36).substring(7);
events.push(newEvent);
return HttpResponse.json(newEvent, { status: 201 });
}),
http.put('/api/v1/events/:id', async ({ request, params }) => {
await delay(500);
const updatedEvent = await request.json() as Event;
events = events.map(e => e.id === params.id ? { ...updatedEvent, id: params.id as string } : e);
return HttpResponse.json(updatedEvent);
}),
http.delete('/api/v1/events/:id', async ({ params }) => {
await delay(300);
events = events.filter(e => e.id !== params.id);
return new HttpResponse(null, { status: 204 });
}),
http.patch('/api/v1/events/:id/status', async ({ request, params }) => {
await delay(300);
const { status } = await request.json() as { status: 'ACTIVE' | 'INACTIVE' };
events = events.map(e => e.id === params.id ? { ...e, status } : e);
const updated = events.find(e => e.id === params.id);
if (!updated) return new HttpResponse(null, { status: 404 });
return HttpResponse.json(updated);
}),
http.get('/api/v1/attributes/schema', async () => {
await delay(300);
const schema = {
CUSTOMER: [
{ code: 'total_spent', type: 'NUMBER' },
{ code: 'first_login_flag', type: 'BOOLEAN' },
{ code: 'survey_completed', type: 'BOOLEAN' },
{ code: 'weekly_view_count', type: 'NUMBER' },
{ code: 'last_login_date', type: 'DATETIME' },
{ code: 'current_streak', type: 'NUMBER' },
{ code: 'recently_viewed', type: 'STRING' }
],
ITEM: [
{ code: 'total_redeem_count', type: 'NUMBER' },
{ code: 'item_view_count', type: 'NUMBER' }
],
ORGANIZATION: [
{ code: 'active_campaigns', type: 'NUMBER' },
{ code: 'total_budget', type: 'NUMBER' }
]
};
return HttpResponse.json(schema);
})
]

View File

@@ -1,7 +1,9 @@
import type { RuleCondition } from "@/context/CampaignRuleContext";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import { X, ChevronDown } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useCampaignRule } from "@/context/CampaignRuleContext";
type ConditionProps = {
@@ -45,23 +47,72 @@ export function Condition({ condition, groupId }: ConditionProps) {
{condition.label}
</div>
<select
className="flex h-7 w-[110px] items-center justify-between whitespace-nowrap rounded-md border border-input bg-white px-2 py-1 text-xs shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
value={condition.operator}
onChange={(e) => handleUpdate("operator", e.target.value)}
>
<option value="==">Equals</option>
<option value="!=">Not Equals</option>
<option value=">">Greater Than</option>
<option value="<">Less Than</option>
</select>
<Select value={condition.operator} onValueChange={(val) => handleUpdate("operator", val)}>
<SelectTrigger className="h-7 w-[110px] text-xs bg-white">
<SelectValue placeholder="Operator" />
</SelectTrigger>
<SelectContent>
<SelectItem value="==">Equals</SelectItem>
<SelectItem value="!=">Not Equals</SelectItem>
{condition.attribute !== "SYS_EVENT_ID" && (
<>
<SelectItem value=">">Greater Than</SelectItem>
<SelectItem value="<">Less Than</SelectItem>
</>
)}
<SelectItem value="IN">In List</SelectItem>
</SelectContent>
</Select>
<Input
className="flex-1 h-7 text-xs px-2 bg-white"
placeholder="Value"
value={condition.value}
onChange={(e) => handleUpdate("value", e.target.value)}
/>
{condition.attribute === "SYS_EVENT_ID" ? (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" className="flex-1 h-7 text-xs px-2 justify-between bg-white text-left font-normal border-input">
<span className="truncate">
{condition.value
? condition.value.split(",").map(v => state.availableEvents.find(e => e.id === v.trim() || e.name === v.trim())?.name || v).join(", ")
: "Select events..."}
</span>
<ChevronDown className="w-3 h-3 opacity-50 ml-1" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[250px] p-2" align="start">
<div className="flex flex-col gap-1">
<div className="text-xs font-semibold text-muted-foreground mb-1 px-1">Available Events</div>
{state.availableEvents.map(evt => {
const isSelected = condition.value.split(",").map(v => v.trim()).includes(evt.id);
return (
<label key={evt.id} className="flex items-center gap-2 p-1.5 hover:bg-muted/50 rounded-md cursor-pointer">
<input
type="checkbox"
className="w-3.5 h-3.5 rounded-sm border-primary/50 text-primary accent-primary"
checked={isSelected}
onChange={(e) => {
const current = condition.value.split(",").map(v => v.trim()).filter(Boolean);
let next;
if (e.target.checked) {
next = condition.operator === "==" ? [evt.id] : [...current, evt.id];
} else {
next = current.filter(id => id !== evt.id);
}
handleUpdate("value", next.join(", "));
}}
/>
<span className="text-sm">{evt.name}</span>
</label>
);
})}
</div>
</PopoverContent>
</Popover>
) : (
<Input
className="flex-1 h-7 text-xs px-2 bg-white"
placeholder="Value"
value={condition.value}
onChange={(e) => handleUpdate("value", e.target.value)}
/>
)}
<Button variant="ghost" size="icon" onClick={handleDelete} className="text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 h-6 w-6 opacity-0 group-hover:opacity-100 transition-all">
<X className="w-3.5 h-3.5" />

View File

@@ -1,7 +1,8 @@
import { useDraggable } from "@dnd-kit/core";
import { GripVertical, Search, User, Sparkles, Zap, Users, Calculator, CreditCard, Building, Phone, Package, Activity } from "lucide-react";
import { GripVertical, Search, User, Sparkles, Zap, Users, Calculator, CreditCard, Building, Phone, Package, Activity, ChevronDown, Type, Hash, CalendarDays, ToggleLeft, AlertCircle } from "lucide-react";
import { Input } from "@/components/ui/input";
import { useState, useMemo } from "react";
import { useCampaignRule } from "@/context/CampaignRuleContext";
type AttributeGroup = {
id: string;
@@ -89,48 +90,6 @@ export const ATTRIBUTE_GROUPS: AttributeGroup[] = [
{ id: "attr-card-status", label: "Trạng thái thẻ", type: "string" },
],
},
{
id: "evt-txn",
category: "Sự kiện (Events)",
name: "Transaction",
icon: Zap,
items: [
{ id: "evt_txn_amount", label: "Amount", type: "number" },
{ id: "evt_txn_datetime", label: "Transaction Datetime", type: "date" },
{ id: "evt_txn_store_id", label: "Store ID", type: "string" },
{ id: "evt_txn_merchant_id", label: "Merchant ID", type: "string" },
],
},
{
id: "evt-login",
category: "Sự kiện (Events)",
name: "Login",
icon: Zap,
items: [
{ id: "evt_login_datetime", label: "Login Datetime", type: "date" },
{ id: "evt_login_source", label: "Source", type: "string" },
],
},
{
id: "evt-reg",
category: "Sự kiện (Events)",
name: "User Registration",
icon: Zap,
items: [
{ id: "evt_reg_email", label: "Email", type: "string" },
{ id: "evt_reg_date", label: "Registration Date", type: "date" },
{ id: "evt_reg_referral", label: "Referral Code", type: "string" },
],
},
{
id: "evt-birthday",
category: "Sự kiện (Events)",
name: "Birthday",
icon: Zap,
items: [
{ id: "evt_bday_date", label: "Date of Birth", type: "date" },
],
},
{
id: "segments",
category: "Khác",
@@ -155,7 +114,17 @@ export const ATTRIBUTE_GROUPS: AttributeGroup[] = [
export const ATTRIBUTES = ATTRIBUTE_GROUPS.flatMap((g) => g.items);
function DraggableAttribute({ id, label }: { id: string; label: string }) {
const getTypeIcon = (type?: string) => {
switch (type) {
case "date": return <CalendarDays className="w-3.5 h-3.5" />;
case "number": return <Hash className="w-3.5 h-3.5" />;
case "boolean": return <ToggleLeft className="w-3.5 h-3.5" />;
case "string":
default: return <Type className="w-3.5 h-3.5" />;
}
};
function DraggableAttribute({ id, label, type }: { id: string; label: string; type?: string }) {
const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
id,
data: { type: "attribute", label },
@@ -166,121 +135,174 @@ function DraggableAttribute({ id, label }: { id: string; label: string }) {
ref={setNodeRef}
{...listeners}
{...attributes}
className={`flex items-center gap-2 p-2.5 bg-white border rounded-md shadow-sm cursor-grab active:cursor-grabbing hover:border-primary hover:bg-primary/5 transition-colors ${
className={`group flex items-center gap-2 py-1.5 px-2 rounded-md cursor-grab active:cursor-grabbing hover:bg-muted/60 transition-colors ${
isDragging ? "opacity-50" : ""
}`}
>
<GripVertical className="w-4 h-4 text-muted-foreground/50" />
<span className="text-sm font-medium">{label}</span>
<GripVertical className="w-3.5 h-3.5 text-muted-foreground/30 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
<span className="text-[13px] font-medium leading-none truncate flex-1 text-foreground/80 group-hover:text-foreground">{label}</span>
{type && (
<span className="text-muted-foreground/50 group-hover:text-muted-foreground/80 transition-colors shrink-0" title={type}>
{getTypeIcon(type)}
</span>
)}
</div>
);
}
export function Sidebar() {
const { state } = useCampaignRule();
const { availableEvents } = state;
const [search, setSearch] = useState("");
const [selectedGroupIds, setSelectedGroupIds] = useState<string[]>([ATTRIBUTE_GROUPS[0].id]);
// By default, expand events list
const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({
"system-events": true,
[ATTRIBUTE_GROUPS[0].id]: true,
});
const allGroups = useMemo(() => {
const groups = [...ATTRIBUTE_GROUPS];
// Add Event ID Attribute Group
if (availableEvents.length > 0) {
groups.unshift({
id: "system-events",
category: "Sự kiện",
name: "Thông tin Sự kiện",
icon: Zap,
items: [
{ id: "SYS_EVENT_ID", label: "Event Type", type: "string" }
]
});
}
// Add Attributes for events currently configured in Canvas
const activeEventIds = new Set<string>();
state.criteria.groups.forEach(g => {
g.conditions.forEach(c => {
if (c.attribute === "SYS_EVENT_ID" && c.value) {
// split by comma in case user uses IN and comma-separates them
const ids = c.value.split(",").map(s => s.trim()).filter(Boolean);
ids.forEach(id => activeEventIds.add(id));
}
});
});
activeEventIds.forEach(eventId => {
const evt = availableEvents.find(e => e.id === eventId || e.name === eventId);
if (evt) {
groups.splice(1, 0, { // Insert right after Events List
id: `attr-${evt.id}`,
category: `Thuộc tính: ${evt.name}`,
name: `${evt.name} Attributes`,
icon: Zap,
items: evt.attributes.map(attr => ({
id: attr.id || attr.key,
label: attr.displayName || attr.key,
type: attr.type.toLowerCase() === 'datetime' ? 'date' : attr.type.toLowerCase()
}))
});
}
});
return groups;
}, [availableEvents, state.criteria.groups]);
const filteredGroups = useMemo(() => {
if (search.trim()) {
// Khi đang search, tìm trên tất cả các nhóm
const lowerSearch = search.toLowerCase();
return ATTRIBUTE_GROUPS.map(group => ({
return allGroups.map(group => ({
...group,
items: group.items.filter(item => item.label.toLowerCase().includes(lowerSearch))
})).filter(group => group.items.length > 0);
}
return allGroups;
}, [search, allGroups]);
// Khi không search, chỉ hiển thị nhóm được chọn
return ATTRIBUTE_GROUPS.filter(g => selectedGroupIds.includes(g.id));
}, [search, selectedGroupIds]);
const categories = Array.from(new Set(allGroups.map(g => g.category)));
return (
<div className="w-60 shrink-0 border-r bg-gray-50/50 flex flex-col h-full">
<div className="w-64 shrink-0 border-r bg-gray-50/30 flex flex-col h-full">
<div className="p-3 border-b bg-white flex flex-col gap-3">
{/* Ô tìm kiếm */}
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Tìm kiếm tất cả..."
className="pl-9 bg-muted/20"
className="pl-9 bg-muted/30 h-9 text-sm"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{/* Chips chọn nhóm */}
<div className="flex flex-col gap-1.5">
{selectedGroupIds.length > 0 && (
<div className="flex justify-end">
<button
onClick={() => setSelectedGroupIds([])}
className="text-[10px] text-muted-foreground hover:text-primary transition-colors"
>
Bỏ chọn tất cả
</button>
</div>
)}
<div className="flex flex-col gap-3 max-h-[35vh] overflow-y-auto pb-1 pr-1 scrollbar-thin scrollbar-thumb-gray-200">
{Array.from(new Set(ATTRIBUTE_GROUPS.map(g => g.category))).map(category => (
<div key={category} className="flex flex-col gap-1.5">
<div className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">{category}</div>
<div className="flex flex-wrap gap-1.5">
{ATTRIBUTE_GROUPS.filter(g => g.category === category).map(g => {
const isSelected = selectedGroupIds.includes(g.id);
return (
<button
key={g.id}
onClick={() => {
if (isSelected) {
setSelectedGroupIds(prev => prev.filter(id => id !== g.id));
} else {
setSelectedGroupIds(prev => [...prev, g.id]);
}
setSearch(""); // Reset search khi chuyển nhóm
}}
className={`inline-flex items-center px-2.5 py-0.5 text-[11px] font-medium rounded-md border transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 ${
isSelected
? "border-transparent bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm"
: "border-input bg-background hover:bg-accent hover:text-accent-foreground"
}`}
>
{g.name}
</button>
)
})}
</div>
</div>
))}
</div>
</div>
</div>
<div className="flex-1 overflow-y-auto p-3 flex flex-col gap-5">
<div className="flex-1 overflow-y-auto p-3 flex flex-col gap-1 scrollbar-thin scrollbar-thumb-gray-200">
{filteredGroups.length === 0 ? (
<div className="text-center text-sm text-muted-foreground mt-4">
Không tìm thấy trường nào.
</div>
) : (
filteredGroups.map(group => (
<div key={group.id} className="flex flex-col gap-2">
{/* Vẫn giữ tiêu đề nhóm để dễ nhìn kết quả khi đang search */}
<div className="sticky top-0 z-10 bg-gray-50/95 backdrop-blur-sm py-1.5 -mx-2 px-2 flex items-center gap-2 rounded-md">
<group.icon className="w-4 h-4 text-primary" />
<h4 className="text-sm font-semibold text-foreground/80">{group.name}</h4>
<span className="text-xs text-muted-foreground ml-auto bg-muted px-1.5 py-0.5 rounded-full">
{group.items.length}
</span>
categories.map((category) => {
const groupsInCategory = filteredGroups.filter(g => g.category === category);
if (groupsInCategory.length === 0) return null;
return (
<div key={category} className="flex flex-col mb-4">
{/* Category Divider */}
<div className="flex items-center gap-2 mb-2">
<div className="h-px bg-border/60 flex-1" />
<span className="text-[10px] font-semibold text-muted-foreground/70 uppercase tracking-wider">{category}</span>
<div className="h-px bg-border/60 flex-1" />
</div>
{/* Groups in Category */}
<div className="flex flex-col gap-0.5">
{groupsInCategory.map(group => {
const isExpanded = search.trim() !== "" || expandedGroups[group.id] || group.id.startsWith("attr-");
return (
<div key={group.id} className="flex flex-col">
<button
onClick={() => setExpandedGroups(prev => ({ ...prev, [group.id]: !prev[group.id] }))}
className="flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted/50 transition-colors text-left group/btn"
>
<group.icon className="w-4 h-4 text-primary shrink-0 opacity-80 group-hover/btn:opacity-100 transition-opacity" />
<span className="text-[13px] font-medium text-foreground/80 flex-1 group-hover/btn:text-foreground transition-colors">{group.name}</span>
<span className="text-[10px] text-muted-foreground bg-muted/60 px-1.5 py-0.5 rounded-full min-w-5 text-center">
{group.items.length}
</span>
<ChevronDown
className={`w-3.5 h-3.5 text-muted-foreground/50 transition-transform duration-200 ${isExpanded ? "rotate-180" : ""}`}
/>
</button>
{/* Collapsible Content */}
<div
className={`flex flex-col gap-1 overflow-hidden transition-all duration-200 ease-in-out ${
isExpanded ? "mt-1 mb-2 max-h-[1000px] opacity-100" : "max-h-0 opacity-0"
}`}
>
<div className="flex flex-col gap-1 py-1">
{group.items.map(attr => (
<DraggableAttribute
key={attr.id}
id={attr.id}
label={attr.label}
type={attr.type}
/>
))}
</div>
</div>
</div>
);
})}
</div>
</div>
<div className="flex flex-col gap-2">
{group.items.map(attr => (
<DraggableAttribute key={attr.id} id={attr.id} label={attr.label} />
))}
</div>
</div>
))
);
})
)}
</div>
</div>
);
}

View File

@@ -27,39 +27,37 @@ export function CriteriaBuilder() {
const { active, over } = event;
if (!over) return;
const attributeId = active.id as string;
const attributeData = active.data.current;
if (attributeData?.type !== "attribute") return;
const newCondition = {
id: crypto.randomUUID(),
attribute: attributeId,
label: attributeData.label,
operator: "==",
value: "",
};
const dragData = active.data.current;
const overData = over.data.current;
if (over.id === "canvas" || overData?.type === "canvas") {
// Create new group
const newGroup = {
if (dragData?.type === "attribute") {
const attributeId = active.id as string;
const newCondition = {
id: crypto.randomUUID(),
operator: "AND" as const,
conditions: [newCondition],
attribute: attributeId,
label: dragData.label,
operator: "==",
value: "",
};
updateState("criteria", { groups: [...state.criteria.groups, newGroup] });
} else if (overData?.type === "group") {
// Add to existing group
const groupId = overData.groupId;
const newGroups = state.criteria.groups.map(g => {
if (g.id === groupId) {
return { ...g, conditions: [...g.conditions, newCondition] };
}
return g;
});
updateState("criteria", { groups: newGroups });
if (over.id === "canvas" || overData?.type === "canvas") {
const newGroup = {
id: crypto.randomUUID(),
operator: "AND" as const,
conditions: [newCondition],
};
updateState("criteria", { groups: [...state.criteria.groups, newGroup] });
} else if (overData?.type === "group") {
// Add to existing group
const groupId = overData.groupId;
const newGroups = state.criteria.groups.map(g => {
if (g.id === groupId) {
return { ...g, conditions: [...g.conditions, newCondition] };
}
return g;
});
updateState("criteria", { groups: newGroups });
}
}
};

View File

@@ -1,10 +1,11 @@
import { useCampaignRule } from "@/context/CampaignRuleContext";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
export function GeneralStep() {
const { state, updateState } = useCampaignRule();
const { general } = state;
const { general, availableEvents, isLoadingEvents, eventsError } = state;
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
updateState("general", { [e.target.name]: e.target.value });

256
src/pages/EventForm.tsx Normal file
View File

@@ -0,0 +1,256 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { AttributeSchemaBuilder } from '@/components/AttributeSchemaBuilder';
import { InstructionsBuilder } from '@/components/InstructionsBuilder';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
const eventSchema = z.object({
name: z.string().min(1, 'Name is required'),
type: z.enum(['DIRECT', 'COUNTER', 'NOTIFICATION']),
targetTopic: z.string(),
transactionCode: z.string().optional(),
notificationId: z.string().optional(),
attributes: z.array(z.object({
key: z.string().min(1, 'Key is required'),
type: z.enum(['STRING', 'NUMBER', 'BOOLEAN', 'DATETIME']),
required: z.boolean()
})),
instructions: z.array(z.object({
name: z.string().min(1, 'Instruction Name is required'),
entityType: z.string().min(1, 'Entity Type is required'),
attributeCode: z.string().min(1, 'Attribute Code is required'),
operation: z.string(),
maxLength: z.number().optional(),
unit: z.string().optional(),
thresholds: z.array(z.object({
value: z.union([z.number(), z.boolean(), z.string()]),
triggerEvent: z.string().min(1, 'Trigger event is required').regex(/^[a-zA-Z0-9_]+$/, 'Only alphanumeric characters and underscores are allowed'),
resetPolicy: z.string()
})).refine(
(thresholds) => {
const values = thresholds.map(t => String(t.value));
return new Set(values).size === values.length;
},
{ message: 'Threshold values must be unique' }
)
})).optional()
});
type EventFormData = z.infer<typeof eventSchema>;
export function EventForm() {
const { id } = useParams();
const navigate = useNavigate();
const [loading, setLoading] = useState(!!id);
const isEditing = !!id;
const { register, control, handleSubmit, setValue, watch, reset, formState: { errors } } = useForm<EventFormData>({
resolver: zodResolver(eventSchema),
defaultValues: {
name: '',
type: 'DIRECT',
targetTopic: 'events-topic',
transactionCode: '',
notificationId: '',
attributes: [],
instructions: []
}
});
const eventType = watch('type');
useEffect(() => {
if (eventType === 'DIRECT') setValue('targetTopic', 'events-topic');
else if (eventType === 'COUNTER') setValue('targetTopic', 'tracking-topic');
else if (eventType === 'NOTIFICATION') setValue('targetTopic', 'noti-topic');
}, [eventType, setValue]);
useEffect(() => {
if (id) {
fetch(`/api/v1/events/${id}`)
.then(res => res.json())
.then(data => {
reset(data);
setLoading(false);
})
.catch(console.error);
}
}, [id, reset]);
const onSubmit = async (data: EventFormData) => {
try {
const url = isEditing ? `/api/v1/events/${id}` : '/api/v1/events';
const method = isEditing ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (res.ok) {
navigate('/events');
}
} catch (e) {
console.error(e);
}
};
if (loading) return <div className="p-8 text-center text-muted-foreground">Loading event...</div>;
return (
<div className="max-w-5xl mx-auto p-8">
<div className="mb-8 flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">{isEditing ? 'Edit Event' : 'Create Event'}</h1>
<p className="text-muted-foreground mt-1">
{isEditing ? 'Modify the configuration for this event.' : 'Configure a new event and its processing rules.'}
</p>
</div>
<div className="flex gap-3">
<Button variant="outline" onClick={() => navigate('/events')}>Cancel</Button>
<Button onClick={handleSubmit(onSubmit)}>Save Event</Button>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Basic Information</CardTitle>
<CardDescription>Essential details and routing configuration.</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-6">
<div className="space-y-2">
<Label htmlFor="name">Event Name</Label>
<Input id="name" {...register('name')} placeholder="e.g. User Signup" />
{errors.name && <p className="text-sm text-red-500">{errors.name.message}</p>}
</div>
<div className="space-y-2">
<Label>Event Type</Label>
<Controller
name="type"
control={control}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value}
items={{
DIRECT: 'Direct',
COUNTER: 'Counter',
NOTIFICATION: 'Notification'
}}
>
<SelectTrigger>
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="DIRECT" label="Direct">Direct</SelectItem>
<SelectItem value="COUNTER" label="Counter">Counter</SelectItem>
<SelectItem value="NOTIFICATION" label="Notification">Notification</SelectItem>
</SelectContent>
</Select>
)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="targetTopic">Target Topic</Label>
<Input id="targetTopic" {...register('targetTopic')} readOnly className="bg-muted text-muted-foreground cursor-not-allowed" />
</div>
{eventType === 'DIRECT' && (
<div className="space-y-2">
<Label htmlFor="transactionCode">Transaction Code</Label>
<Input id="transactionCode" {...register('transactionCode')} placeholder="e.g. TXN123" />
</div>
)}
{eventType === 'NOTIFICATION' && (
<div className="space-y-2">
<Label>Notification ID</Label>
<Controller
name="notificationId"
control={control}
render={({ field }) => (
<Select
onValueChange={field.onChange}
value={field.value}
items={{
NOTI_001: 'NOTI_001',
NOTI_002: 'NOTI_002',
NOTI_003: 'NOTI_003'
}}
>
<SelectTrigger>
<SelectValue placeholder="Select Notification ID" />
</SelectTrigger>
<SelectContent>
<SelectItem value="NOTI_001" label="NOTI_001">NOTI_001</SelectItem>
<SelectItem value="NOTI_002" label="NOTI_002">NOTI_002</SelectItem>
<SelectItem value="NOTI_003" label="NOTI_003">NOTI_003</SelectItem>
</SelectContent>
</Select>
)}
/>
</div>
)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Attribute Schema</CardTitle>
<CardDescription>Define the payload structure expected by this event.</CardDescription>
</CardHeader>
<CardContent>
<AttributeSchemaBuilder control={control} register={register} />
{errors.attributes && <p className="text-sm text-red-500 mt-2">Please fix attribute errors.</p>}
</CardContent>
</Card>
{eventType === 'COUNTER' && (
<Card>
<CardHeader>
<CardTitle>Counter Instructions</CardTitle>
<CardDescription>Configure rules for incrementing counters and triggering subsequent events.</CardDescription>
</CardHeader>
<CardContent>
<InstructionsBuilder control={control} register={register} />
{errors.instructions && <p className="text-sm text-red-500 mt-2">Please fix instruction errors.</p>}
</CardContent>
</Card>
)}
<Separator className="my-8" />
<div className="flex justify-end gap-3 pb-8">
<Button type="button" variant="outline" onClick={() => navigate('/events')}>Cancel</Button>
<Button type="submit">Save Event</Button>
</div>
</form>
</div>
);
}

252
src/pages/EventsList.tsx Normal file
View File

@@ -0,0 +1,252 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Plus, Trash2, Edit, MoreHorizontal, Search } from 'lucide-react';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import type { Event } from '@/types/event';
export function EventsList() {
const [events, setEvents] = useState<Event[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [filterType, setFilterType] = useState<string>('ALL');
const fetchEvents = async () => {
try {
const res = await fetch('/api/v1/events');
if (res.ok) {
const data = await res.json();
setEvents(data);
setError(null);
} else {
setError('Failed to fetch events.');
}
} catch (e) {
console.error(e);
setError('An error occurred while fetching events.');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchEvents();
}, []);
const handleDelete = async (id: string) => {
if (window.confirm('Are you sure you want to delete this event?')) {
try {
const res = await fetch(`/api/v1/events/${id}`, { method: 'DELETE' });
if (res.ok) {
setEvents(events.filter(e => e.id !== id));
setError(null);
} else {
setError('Failed to delete event.');
}
} catch (e) {
console.error(e);
setError('An error occurred while deleting the event.');
}
}
};
const handleToggleStatus = async (id: string, currentStatus: string | undefined) => {
const newStatus = currentStatus === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
try {
const res = await fetch(`/api/v1/events/${id}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus })
});
if (res.ok) {
setEvents(events.map(e => e.id === id ? { ...e, status: newStatus } : e));
}
} catch (e) {
console.error('Failed to update status', e);
}
};
if (loading) {
return <div className="p-8 text-center text-muted-foreground">Loading events...</div>;
}
const filteredEvents = events.filter((event) => {
const matchesSearch = event.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
event.targetTopic.toLowerCase().includes(searchTerm.toLowerCase());
const matchesType = filterType === 'ALL' || event.type === filterType;
return matchesSearch && matchesType;
});
return (
<div className="max-w-5xl mx-auto p-8 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Event Registry</h1>
<p className="text-muted-foreground mt-1">Manage and configure all system events and their triggers.</p>
</div>
<Link to="/events/new">
<Button>
<Plus className="w-4 h-4 mr-2" /> Create Event
</Button>
</Link>
</div>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
{error}
</div>
)}
<Card>
<CardHeader className="py-4 border-b">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<CardTitle className="text-lg">All Events</CardTitle>
<div className="flex items-center gap-2 w-full sm:w-auto">
<div className="relative flex-1 sm:w-64">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search events..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
/>
</div>
<Select
value={filterType}
onValueChange={setFilterType}
items={{
ALL: 'All Types',
DIRECT: 'Direct',
COUNTER: 'Counter',
NOTIFICATION: 'Notification'
}}
>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL" label="All Types">All Types</SelectItem>
<SelectItem value="DIRECT" label="Direct">Direct</SelectItem>
<SelectItem value="COUNTER" label="Counter">Counter</SelectItem>
<SelectItem value="NOTIFICATION" label="Notification">Notification</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader className="bg-muted/50">
<TableRow>
<TableHead className="w-[250px]">Name</TableHead>
<TableHead>Type</TableHead>
<TableHead>Target Topic</TableHead>
<TableHead>Configured Logic</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right w-[100px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredEvents.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
No events found.
</TableCell>
</TableRow>
) : (
filteredEvents.map((event) => (
<TableRow key={event.id}>
<TableCell className="font-medium">{event.name}</TableCell>
<TableCell>
<Badge
variant={event.type === 'DIRECT' ? 'default' : event.type === 'COUNTER' ? 'secondary' : 'outline'}
className={
event.type === 'DIRECT' ? 'bg-blue-100 text-blue-800 hover:bg-blue-100' :
event.type === 'COUNTER' ? 'bg-purple-100 text-purple-800 hover:bg-purple-100' :
'bg-orange-100 text-orange-800 hover:bg-orange-100'
}
>
{event.type}
</Badge>
</TableCell>
<TableCell className="text-muted-foreground">{event.targetTopic}</TableCell>
<TableCell>
{event.type === 'DIRECT' || event.type === 'NOTIFICATION' ? (
<span className="text-muted-foreground text-sm"> Route directly</span>
) : (
<span className="text-muted-foreground text-sm">
{event.instructions?.length || 0} Instructions, {event.instructions?.reduce((acc, inst) => acc + (inst.thresholds?.length || 0), 0) || 0} Triggers
</span>
)}
</TableCell>
<TableCell>
<Switch
checked={event.status === 'ACTIVE'}
onCheckedChange={() => handleToggleStatus(event.id, event.status)}
/>
</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="ghost" size="icon" className="h-8 w-8" />}
>
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Link to={`/events/${event.id}/edit`}>
<DropdownMenuItem className="cursor-pointer">
<Edit className="w-4 h-4 mr-2 text-muted-foreground" />
Edit
</DropdownMenuItem>
</Link>
<DropdownMenuItem
onClick={() => handleDelete(event.id)}
className="text-red-600 focus:text-red-600 focus:bg-red-50 cursor-pointer"
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}

46
src/types/event.ts Normal file
View File

@@ -0,0 +1,46 @@
export type EventType = 'DIRECT' | 'COUNTER' | 'NOTIFICATION';
export type AttributeType = 'STRING' | 'NUMBER' | 'BOOLEAN' | 'DATETIME';
export type OperationType = 'INCREMENT' | 'STREAK_INCREMENT' | 'COMPUTE_GAP' | 'APPEND_UNIQUE' | 'SET_TRUE_ONCE' | 'CHECK_AND_UPDATE_TIMER';
export interface Attribute {
id?: string;
key: string;
displayName?: string;
type: AttributeType;
required: boolean;
}
export interface Threshold {
id?: string;
operator?: string;
value: number | boolean | string;
triggerEvent: string;
resetPolicy: string;
}
export interface Instruction {
id?: string;
name: string;
entityType: string;
attributeCode: string;
operation: OperationType;
sourceField?: string;
maxLength?: number;
unit?: string;
periodType?: 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY' | 'LIFETIME';
step?: number;
triggerEventOnSuccess?: string;
thresholds: Threshold[];
}
export interface Event {
id: string;
name: string;
status?: 'ACTIVE' | 'INACTIVE';
type: EventType;
targetTopic: string;
transactionCode?: string;
notificationId?: string;
attributes: Attribute[];
instructions?: Instruction[];
}