-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
499 lines (338 loc) · 14.8 KB
/
.cursorrules
File metadata and controls
499 lines (338 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# Frontend Documentation
This is a Vite Remix project in React using Typescript, Ant Design and Tailwind and tRPC React query.
## Pages
Pages located at "/app/routes/\_logged.**.tsx" are accessible for logged users.
Other pages located at "/app/routes/**.tsx" are public.
# Authorization Policies on Server
Policies are defined using zenstack on zmodels "/models/models.zmodel".
It automatically protect auto-generated CRUD models and the default Prisma client.
You can use the `@@allow` decorator to define policies.
Example for a model "Foo" at "/models/models.zmodel":
```zmodel
model Foo {
id String @id @default(uuid())
name String?
email String?
isVerified Boolean?
@@allow('all', auth().roles?[name == 'admin'])
@@allow('read', true)
@@allow('create', auth().id == this.id)
@@allow('update', auth().id == this.id)
@@allow('delete', auth().id == this.id && this.isVerified)
}
```
Explanations:
- `auth()` is the authenticated user, you have access to the same properties as the user model.
- `this` is the current model (here Foo)
- `@@allow('read', [condition])` grant read policy if the condition is true. It will also affect how findMany results are filtered.
- `@@allow('update', [condition])` grant update policy if the condition is true.
- `@@allow('delete', [condition])` grant delete policy if the condition is true.
- `@@allow('all', [condition])` grant all policies if the condition is true
- `auth().roles?[name == 'admin']` - you can access relations. In this example, we checking if a user, has a role with the name 'admin'
# Core Utilities
Core utilities, hooks and business logic are located at "/app/core"
- "app/core/context" is where the user context store is setup. It can be used in the application to access information about the logged user.
- "app/core/helpers" is where small utilities to manipulate dates or typescript operations are stored.
- "app/core/hooks" contains hooks for external libraries and API routes that are not using tRPC.
## Sensitive files
- "app/core/authentication" is where the authentication is setup.
- "app/core/configuration" is where the common environment variables are provided.
- "app/core/database" is where the Prisma database is setup for the backend.
- "app/core/trpc" is where the trpc client and server are setup.
Do not updates these files except if asked to do so.
# Design System
The project uses Ant Design for all UI components. On top of that, you can use tailwind className to style and position the UI components.
The design system is setup in the "/app/designSystem" folder.
The following folders and files can safely be updated:
- "/app/designSystem/layouts" contains re-usable layouts components for pages.
- "/app/designSystem/theme/theme.tsx" is where the Ant Design theme can be customised.
- "/app/designSystem/ui" is where custom components that are not part of Ant Design but useful for the whole application are stored.
## Sensitive files
Except if explicitly asked, you must avoid touching the following folders and files:
- "/app/designSystem/core" contains top level components such as HTML and main tags.
- "/app/designSystem/provider.tsx" is where we apply all design system providers.
- "/app/designSystem/style" contains global scss files.
[CHUNK-SEPARATOR]
## How to create a UI component
1. Create your component in "/app/designSystem/ui/[ComponentName]/index.tsx"
2. Code the component
```tsx
// Typical example
type Props = {
key1: string
key2: string
key3: string
}
export const ComponentName: React.FC<Props> = ({ key1, key2, key3 }) => {
return <>...</>
}
```
Tips:
- We usually prefer to export the `const` directly so the component has a consistent import in other files `import { ComponentName } from '@/designSystem/ui/ComponentName'`.
- You can use tailwind className to style the UI components.
- To import Title, Text and Paragraph from Ant Design, you need to import \`import { Typography } from 'antd'\` and then do \`const { Title, Text, Paragraph} = Typography\`. There are no other ways.
## Session
The context available from `import { AuthenticationServer } from '@/core/authentication/server'` is an object with the following structure:
```ts
type Context = {
database: PrismaClient // The default prisma client to use, recommended as there are policies triggered in case the action is not permitted for the user.
databaseUnprotected: PrismaClient // The prisma client without policies, useful when you don't need the policies.
session: {
user?: {
id: string
email: string
name: string
globalRole: string
}
}
}
const context = await AuthenticationServer.getHttpContext({ request })
console.log(context.session.user)
```
## Database Interaction
```ts
const context = await AuthenticationServer.getHttpContext({ request })
const userFetched = await context.database.user.findUnique({
data: { id: context.session.user.id },
})
const filteredUsers = await context.database.user.findMany() // This automatically apply authorization policies to filter the results
const allUsers = await context.databaseUnprotected.user.findMany() // This bypass all the authorization policies
```
# How to create a model
1. Create a model in the file "models/models.zmodel"
2. Define the model using the Prisma syntax (you can look at an existing model to view an example)
[CHUNK-SEPARATOR]
# How to update a Model
When editing a model, any new field must either be optional or have a default value. Failing to do so will cause the app to crash.
```zmodel
model [Name] {
...
fieldOptional String?
fieldWithDefaultValue String @default("the default value")
...
}
```
[CHUNK-SEPARATOR]
## How to add a OneToMany relation
```zmodel
model Parent {
...
children Child[] @relation("parent")
...
}
```
```zmodel
model Child {
...
parentId? String
parent? Parent @relation(fields: [parentId], references: [id], name: "parent")
...
}
```
Constraints:
- It's important that the name:"parent" in the Child matches the @relation("parent") name
- When adding a relation, make sure to add fields on both sides of the relations
## Enums
```zmodel
enum NameEnum{
VALUE1
VALUE2
VALUE3
}
```
# Models
We are using Zenstack (a Prisma superset) and all the models are located in "/models/models.zmodel".
Do not edit the .prisma, only edit the models.zmodel file to edit the data models.
Zenstack generates also all the tRPC endpoints/routers from the models.
[CHUNK-SEPARATOR]
## Using Prisma Types with React State and tRPC
To work with Prisma models in React, import necessary types from @prisma/client. Use Prisma.[name]GetPayload for accurate typing when state involves relations.
```tsx
// Import Prisma types
import { Prisma, User } from '@prisma/client'
import { useState } from 'react'
// Correct typing with relations
const [value, setValue] = useState<Prisma.UserGetPayload<{ include: { relation1: true; relation2: true } }>>()
// tRPC functions have correct typing by default
const { data } = Api.user.findMany.useQuery({ include: { relation1: true; relation2: true } })
```
Always use Prisma.[name]GetPayload to avoid TypeScript errors when including relations.
# Navigation Layout - Important Information
## Navigation Links
- **File:** `app/designSystem/layouts/NavigationLayout/index.tsx`
- All navigation links for the topbar and leftbar are defined here in variables.
- **AI Instruction:** Only modify this file when adding or displaying a new link for the top or left bar.
## Layout Components
- **Folder:** `app/designSystem/layouts/NavigationLayout/`
- Contains the components for layout elements like the **topbar**, **leftbar**, etc.
- **AI Instruction:** For any changes to the layout's structure or appearance, refer to the components inside this folder, not the navigation tabs.
# tRPC & Zenstack
Zenstack automatically auto-generates routers for all models, meaning **there is no need to create these routers when you add or edit a data model, they already exist**.
---
## Common Operations
Zenstack provides model-level endpoint/functions that handle the following operations:
- `findUnique`
- `findFirst`
- `findMany`
- `create`
- `createMany`
- `update`
- `updateMany`
- `delete`
- `deleteMany`
These CRUD routers are **auto-generated** from your models and available in both the server and frontend contexts.
### Frontend: tRPC Client
To interact with the backend, use the pre-built tRPC / React Query client with `@/core/trpc`. No need to manually create routers for CRUD operations. Instead, import the `Api` object that exposes all necessary hooks.
Here’s how to perform common CRUD operations:
#### Example - Fetch a User
```tsx
import { Api } from '@/core/trpc'
const userId = '667'
const {
data: user,
isLoading,
refetch,
} = Api.user.findFirst.useQuery({ where: { id: userId } })
```
#### Example - Fetch many users
```tsx
import { Api } from '@/core/trpc'
const { data: users, isLoading, refetch } = Api.user.findMany.useQuery()
```
#### Example - Create a User
```tsx
import { Api } from '@/core/trpc'
const { mutateAsync: createUser } = Api.user.create.useMutation()
const handleCreate = async () => {
await createUser({ data: { email: 'email', name: 'test' } })
}
```
#### Example - Update a User
```tsx
import { Api } from '@/core/trpc'
const userId = '667'
const { mutateAsync: updateUser } = Api.user.update.useMutation()
const handleUpdate = async () => {
await updateUser({ where: { id: userId }, data: { email: 'new_email' } })
}
```
#### Example - Delete a User
```tsx
import { Api } from '@/core/trpc'
const userId = '667'
const { mutateAsync: deleteUser } = Api.user.delete.useMutation()
const handleDelete = async () => {
await deleteUser({ where: { id: userId } })
}
```
#### Refetch
Information about `refetch` method:
- Calling the refetch method from the useQuery client will automatically update the data object
- The refetch method does not take any argument
- The refetch method does not return anything
#### Fetch a specific direclty from a function
- Use the `Api.useUtils()` hook with its provided `fetch` method
- You must declare the `Api.useUtils()` hook at the root of the component and use it inside the function
Example:
```tsx
import { Api } from '@/core/trpc'
const apiUtils = Api.useUtils()
const handleProjectClicked = async (projectId: string) => {
const project = await apiUtils.project.findUnique.fetch({
where: { id: projectId },
})
// Use the project fetched inside the function (e.g: to redirect the user)
}
```
Important:
- All `useMutation` and `useQuery` hooks must be declared at the top level of the component body, not within nested functions or event handlers. Violating this rule will break the hooks' behavior.
---
## Custom Functions
Most operations are covered out of the box. However, in case you need custom logic, and if the user ask you to do so, you can create custom routers.
In general, it's very rare to create custom router, only create custom routers if the user request asks for it.
### Server: tRPC Custom Routers
Custom routers are defined in `app/server/routers/[name].router.ts`. When creating these routers, you have access to the `ctx` object, which provides:
- `ctx.session.user`: The authenticated user who triggered the request.
- `ctx.database`: The Prisma client with Zenstack policies.
- `ctx.databaseUnprotected`: The Prisma client without Zenstack policies, for unrestricted operations.
#### Example - Custom Mutation
```ts
import { Trpc } from '@/core/trpc/base'
import { z } from 'zod'
export const MyRouter = Trpc.createRouter({
createCustomUser: Trpc.procedure
.input(z.object({ name: z.string(), email: z.string() }))
.mutation(async ({ ctx, input }) => {
const user = await ctx.database.user.create({ data: input })
return user
}),
})
```
To add custom routers, import them in `app/server/index.tsx`:
```ts
import { MyRouter } from './routers/my-router'
const appRouter = Trpc.mergeRouters(Trpc.createRouter({ myRouter: MyRouter }))
```
---
## Common Errors
### Accessing Nested Models
When you need to access foreign relation data in nested models, use the `include` attributes in your fetch query to include the nested models. You can also include sub-level nested models if needed.
### Required Properties in Create Queries
When creating a new entity with the API, ensure that all required properties are included in the create query. If any required properties are missing, the query will fail.
### Do Not Re-Create Routers
The auto-generated routers from Zenstack already exist in the `node_modules`. You cannot see them, but they are always available. Do not attempt to re-create them manually.
### Types & Relations in Frontend
Prisma types do not include relations by default. To avoid TypeScript errors, include relations explicitly in your queries and redeclare types when necessary.
#### Example
```tsx
import { Prisma } from '@prisma'
const [value, setValue] =
useState<Prisma.UserGetPayload<{ include: { relation1: true } }>>(null)
const { data } = Api.user.findMany.useQuery({ include: { relation1: true } })
useEffect(() => {
setValue(data[0])
}, [data])
console.log(value.relation1)
```
---
## Key Takeaways
- No router creation is needed when adding or editing data models; Zenstack generates everything automatically.
- Use the `Api` object for frontend CRUD operations with `@/core/trpc`.
- Custom routers are used for non-CRUD operations, and should be placed in `app/server/routers/[name].router.ts`.
- Use `ctx` in the server for accessing session and Prisma clients.
# Typescript conventions
## Prefer Named Exports
In our TypeScript codebase, **named exports** should be preferred over `export default` except in Remix pages.
This makes it easier to understand what is being imported, encourages consistency, and avoids issues when renaming exports during imports.
### Example: Named Export
Instead of using a default export:
```typescript
// Bad Example: default export
export default function myFunction() {
// implementation
}
```
Use a named export:
```typescript
// Good Example: named export
export function myFunction() {
// implementation
}
```
Named exports are imported like this:
```typescript
import { myFunction } from './myModule'
```
For Remix pages, it's necessary to use the export default convention. In these specific cases, export default is fine:
```typescript
// Remix page example
export default function HomePage() {
// implementation
}
```
But for all other cases, avoid export default and stick to named exports.
## Typescript Tips
- When iterating through an array using `.map`, always ensure the array is not null by using the optional chaining operator (`?`) like this: `items?.map`.
- Use `<InputNumber/>` for any input that requires a user to enter a number.
- You will be penalized if you use Moment.js to manipulate dates. Only dayJs is allowed.
- Always use `toString()` when displaying a number or decimal in the HTML of a component, or TypeScript will throw an error.