Awesome Cursor Rules Collection

Showing 1489-1500 of 2626 matches

Python
# Nova Project Rules

documentation:
    docling: docling-docs
    raycast: raycast-docs
    mcp: mcp-docs

package_management:
    - Use uv ONLY
    - Direct pip usage is FORBIDDEN
    - Direct python/python3 usage is FORBIDDEN
    - All Python commands must go through uv

vision_model:
    - Use "gpt-4o" model for vision recognition
    - Do NOT use gpt-4-vision-preview or any other vision models

file_system:
    - All system files MUST be stored in .nova directory
    - All logs, processing files, and system writes go to .nova
    - Input files location must be configurable
    - Default input path: /Users/chadwalters/Library/Mobile Documents/com~apple~CloudDocs/_NovaInput

file_size:
    - All code files MUST be less then 250 lines

testing:
    - Use uv run pytest for ALL test runs
    - Tests should run without approval
    - Test command: uv run pytest -v
    - Type checking MUST be run before tests

ai_commands:
    update_docs:
        procedure:
            - "Parse all Markdown files in docs/**/*.md and README.md"
            - "Extract relevant updates from conversation"
            - "Apply any relevant and useful updates"

    create_plan:
        procedure:
            - "If there is a plan, you MUST delete it"
            - "Create a new plan in .Plan in cursorplan format"
            - "You must include status markers for each step, along with milestones where we should run and get the tests to work"
            - "Extract relevant updates from conversation"
            - "Apply any relevant and useful parts of conversation to the plan"

    update_plan:
        procedure:
            - "You must read the plan in .Plan"
            - "Extract relevant updates from conversation and make appropriate changes to the plan"
            - "You must update status markers for each step, along with milestones where we should run and get the tests to work"
            - "Apply any relevant and useful parts of conversation to the plan"

    update_rules:
        procedure:
            - "Parse .cursorrules file"
            - "Extract rule updates from conversation"
            - "Apply any relevant and useful updates"

    update_scratchpad:
        procedure:
            - "You MUST read the .cursorscratchpad file"
            - "Extract relevant insights from current context"
            - "Interleave your thoughts with previous thoughts in the <SCRATCHPAD> buffer"
            - "You MUST write your thoughts in the <SCRATCHPAD> buffer"
            - "Consolidate your thoughts as necessary, grouping related thoughts together"

    update_note:
        procedure:
            - "You MUST read the .cursornotes and .cursorscratchpad files"
            - "Consolidate previous thoughts from <SCRATCHPAD>"
            - "Integrate new information from current conversation"
            - "Format as dated entry, request date from user"
            - "Append to .cursornotes file"
            - "Clear <SCRATCHPAD> section in .cursorscratchpad"

    run_tests:
        procedure:
            - "Run command: uv run pytest -v"
golang
less
python
shell
solidjs

First seen in:

chadrwalters/nova

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Vue 3, DaisyUI, VueUse, and Tailwind and chrome extensions

Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use composition API and declarative programming patterns; avoid options API.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, composables, helpers, static content, types.

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Use PascalCase for component names (e.g., AuthWizard.vue).
- Use camelCase for composables (e.g., useAuthState.ts).

TypeScript Usage

- Use TypeScript for all code; prefer types over interfaces.
- Avoid enums; use const objects instead.
- Use Vue 3 with TypeScript, leveraging defineComponent and PropType.

Syntax and Formatting

- Use arrow functions for methods and computed properties.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use template syntax for declarative rendering.

UI and Styling

- Use DaisyUI, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization

- Leverage Nuxt's built-in performance optimizations.
- Use Suspense for asynchronous components.
- Implement lazy loading for routes and components.
- Optimize images: use WebP format, include size data, implement lazy loading.

Key Conventions

- Use VueUse for common composables and utility functions.
- Use Pinia for state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Utilize Nuxt's auto-imports feature for components and composables.

Vue 3 and Composition API Best Practices

- Use <script setup> syntax for concise component definitions.
- Leverage ref, reactive, and computed for reactive state management.
- Use provide/inject for dependency injection when appropriate.
- Implement custom composables for reusable logic.

Follow the official Vue.js documentation for up-to-date best practices on Data Fetching, Rendering, and Routing.

Project idea:

- A chrome extension as an extension for the Lighthouse platform.
- Should handle incoming notifications and give alerts based on it
- use manifest.config.ts as the main manifest file
css
html
javascript
nuxt.js
react
scss
tailwindcss
typescript
+2 more
TackJordy/chrome-extension-l-d

Used in 1 repository

HTML
AI 的表现要求:
- 帮助我一步步生成网页代码。
- 每次生成代码后,解释这部分代码的作用。
- 使用简单易懂的语言,不要一次生成太多代码。

已完成的步骤:
1. 创建基本的 HTML 结构
   - 添加头部信息
   - 设置中文语言
   - 添加标题和段落

2. 添加 CSS 样式
   - 设置浅灰色背景
   - 设置红色标题

3. 添加图片功能
   - 插入本地图片 "绝世武功目录.png"
   - 设置图片居中显示
   - 添加图片自适应样式

4. 添加跳转按钮
   - 创建样式化的链接按钮
   - 设置跳转目标为 baidu.com
   - 添加鼠标悬停效果
   - 按钮居中显示

5. 优化布局
   - 调整图片位置到标题下方
   - 更新链接文字和目标

6. 美化页面样式
   - 设置段落文字样式
     * 蓝色文字
     * 微软雅黑字体
     * 16px 字体大小
   - 添加页面边框
     * 1像素黑色边框
     * 添加内边距
     * 限制内容宽度并居中

7. 添加交互功能
   - 添加弹窗按钮
     * 使用 JavaScript alert() 函数
     * 添加按钮样式
     * 设置鼠标悬停效果
   - 实现点击弹出对话框功能

8. 添加表单功能
   - 添加输入框
     * 设置提示文本
     * 添加输入框样式
   - 添加提交按钮
   - 添加欢迎消息显示
   - 添加输入验证
     * 检查空输入
     * 显示错误提示

9. 优化界面和交互
   - 优化按钮样式
     * 添加阴影效果
     * 添加悬停动画
     * 统一按钮样式
   - 添加时间问候功能
     * 根据当前时间显示问候语
     * 自动加载问候信息
     * 添加问候语样式

10. 增强交互效果
    - 添加随机背景色功能
      * 添加新按钮
      * 实现随机颜色生成
      * 添加按钮样式
    - 优化时间问候功能
      * 细分时间段
      * 添加晚上问候语
      * 优化判断逻辑

11. 增强背景色功能
    - 添加长按恢复功能
      * 实现长按检测
      * 添加定时器功能
      * 支持触摸设备
    - 优化视觉效果
      * 添加颜色过渡动画
      * 保存默认颜色值
      * 优化用户体验

注意事项:
- 确保图片文件存在于正确路径
- CSS 样式保持简洁易读
- 代码结构清晰,便于维护
- 注意字体后备方案
- JavaScript 代码简洁可读
html
java
javascript

First seen in:

dzrycs/MyFirstWebsite

Used in 1 repository

Astro
1. Latar Belakang
Aplikasi akuntansi sederhana dirancang untuk membantu UKM, seperti restoran kecil, dalam mencatat dan mengelola pemasukan dengan mudah. Restoran sering menghadapi tantangan dalam memonitor pendapatan harian mereka secara efisien, sehingga sulit untuk menganalisis performa bisnis secara tepat waktu. Dengan aplikasi ini, pengguna dapat mencatat transaksi pemasukan harian, memantau arus kas masuk, dan melihat laporan keuangan yang relevan.

2. Batasan Permasalahan
- Fokus: Aplikasi hanya mencakup pencatatan pemasukan, transfer antar akun, dan penyajian laporan keuangan (Laba Rugi dan Neraca).
- Pengguna: Hanya tersedia tiga peran: User, Admin, dan Manager.
- Skalabilitas: Aplikasi dirancang untuk UKM dengan transaksi sederhana tanpa fitur kompleks seperti integrasi pajak atau payroll otomatis.
- Aksesibilitas: Aplikasi berbasis web, tidak ada dukungan offline.
- Autentikasi dan Otorisasi: Pengguna harus login untuk mengakses fitur, dengan hak akses sesuai peran masing-masing.
3. Proses Bisnis

1. Aktor:
    Manager Keuangan: Mencatat pemasukan dan transfer.
    Admin: Mengelola account, kategori, dan pengguna.
    Owner: Mengakses laporan keuangan dan analisis.
2. Flowchart Pencatatan Transaksi Pemasukan:
Alur proses pencatatan transaksi pemasukan:

Input Data: User memilih jenis transaksi (Income atau Transfer).
Validasi Input: Sistem memvalidasi data (akun tujuan, jumlah, kategori).
Proses Transaksi:
Jika Income: Tambah saldo akun yang dipilih.
Jika Transfer: Kurangi saldo dari akun asal, tambah saldo ke akun tujuan.
Jurnal Entry: Sistem mencatat transaksi ke jurnal.
Konfirmasi: Sistem memberikan notifikasi bahwa transaksi berhasil dicatat.
4. Penyesuaian Aplikasi ke Proses Bisnis
Fitur dan Modul Utama
Accounts Management:

Membuat akun seperti Kas dan Bank.
Menampilkan saldo setiap akun.
Categories Management:

Membuat kategori seperti Penjualan Harian.
Kategori digunakan saat mencatat pemasukan.
Transaction Recording:

Pencatatan pemasukan dan transfer uang.
Fitur autocomplete untuk kategori dan akun.
Financial Reports:

Laporan Laba Rugi dan Neraca.
Grafik analisis tren pemasukan.
User Roles & Permissions:

User: Hanya dapat mencatat transaksi pemasukan.
Admin: Mengelola semua data (akun, kategori, pengguna).
Manager: Mengakses laporan keuangan.
Teknologi yang Digunakan
Framework: Laravel 11 (Backend) dan Bootstrap 5 (Frontend).
Database: MySQL untuk pencatatan transaksi dan laporan keuangan.
Autentikasi: Dibuat sendiri.
Integrasi dengan Proses Bisnis Restoran
Pemasukan: Mencatat pemasukan dari penjualan harian.
Transfer: Mengelola pemindahan kas antar akun (dari brankas ke rekening bank).
Laporan Keuangan: Laporan harian, mingguan, atau bulanan untuk evaluasi profitabilitas restoran.
Aplikasi ini kini berfokus sepenuhnya pada manajemen pemasukan dan penyajian laporan keuangan yang relevan. Dengan penghapusan fitur terkait pengeluaran, aplikasi menjadi lebih sederhana dan langsung mendukung kebutuhan pencatatan pemasukan harian UKM.
astro
blade
bootstrap
css
golang
javascript
laravel
mdx
+5 more

First seen in:

BahasKoding/akutansi

Used in 1 repository

TypeScript
You are a senior software engineer tasked with reviewing existing code and providing suggestions for improvements or new implementations. Your goal is to select the best solutions while avoiding unnecessary duplication and complexity.

First, conduct a deep-dive review of the existing code. Analyze its structure, efficiency, and adherence to best practices. Document your findings within <code_review> tags.

Next, create a detailed plan for the changes or improvements needed. Outline your plan within <planning> tags. Break down the task into discrete changes and consider small tests after each stage to ensure progress is on the right track.

When making suggestions for implementation:

1. Prioritize solutions that maintain a generic and flexible approach.
2. Pay close attention to variable names and string literals, ensuring consistency unless a change is necessary or directed.
3. Use {{UPPERCASE}} for placeholders in your suggestions.
4. If code examples are necessary to illustrate a point, provide them. Otherwise, give explanations without code and wait for further direction if elaboration is needed.
5. For language specific features, use the following versions:
   - Python: >=3.12
      * PEP 585 enabled collections in the Python standard library (like list) to be used as generics directly, instead of importing analogous members from the typing module (like typing.List).

Present your final output in the following format:

<code_review>
[Your detailed code review findings]
</code_review>

<planning>
[Your detailed plan for changes or improvements]
</planning>

<suggestions>
[Your implementation suggestions, broken down into discrete steps]
</suggestions>

Remember that clean code is a top priority. Ensure that every step does not introduce unnecessary complexity or content that might not be human readable.

Consider operational soundness at every step. This includes hosting, management, monitoring, and maintenance of solutions. Highlight any operational concerns where relevant.

If anything in the task description or existing code is unclear or ambiguous, ask for clarifications before proceeding. When multiple implementation options are available, discuss the trade-offs of each approach.

Begin your response now, starting with the code review.
css
dockerfile
golang
html
javascript
less
python
typescript
Brokeshire-Hathaway/ember-widget

Used in 1 repository

Python
# Cursor Agent Rules

## Environment Setup

IMPORTANT: Always activate the cursor_tools conda environment before using or developing tools:

```bash
conda activate cursor_tools
```

If you encounter import errors, this is likely because the environment is not activated.

IMPORTANT: Never modify the base environment under any circumstances. If you find yourself in the base environment, always activate the correct environment instead of installing packages in base.

IMPORTANT: Never install packages directly using pip or conda. Instead:

- Add Python package dependencies to pyproject.toml
- Add development/data science dependencies to environment.yml
- Then reinstall the project using `pip install -e .`

The environment.yml file is mostly for developer and data science dependencies.  The pyproject.toml file is for the package dependencies.
Prefer adding the dependencies to the pyproject.toml file.

The package is installed in editable mode (`pip install -e .`), so any changes to the code will be immediately reflected without reinstallation.

## Output and Logging

IMPORTANT: Tools must follow these output and logging guidelines:

- Never use print() statements. Use click.echo() for command output
- Use the logging module for all debug/info/warning/error messages
- Tools should only output their results on stdout so they can be composed in command pipelines
- Verbose logging must be explicitly enabled before tools can emit logging messages
- Keep stdout clean and predictable for command composition
- Use stderr for warnings and errors
- Never log sensitive data (API keys, tokens) in plaintext
- Use structured logging format for better debugging
- Include timestamp, logger name, and log level in log format

## Cross-Platform Compatibility

IMPORTANT: Tools must work across different platforms:

- Handle SSL/certificate verification properly (especially on Windows)
- Use certifi for SSL certificate verification
- Create proper SSL contexts when needed
- Handle filesystem paths correctly
- Test on all target platforms
- Document platform-specific requirements

## Error Handling

IMPORTANT: Implement proper error handling:

- Create custom exception hierarchies for better error handling
- Handle errors from most specific to most generic
- Provide clear error messages to users
- Log detailed error information for debugging
- Always set timeouts for external operations
- Implement proper input validation
- Handle API errors gracefully
- Use appropriate exit codes

## Agent Workspace

Agents have access to a local `scratchpad/` directory for maintaining state and notes about:

- Current goals and tasks
- Observations and learnings
- Progress tracking
- Any other persistent information needed across sessions

This directory is ignored by git (via .gitignore) since it contains agent-specific working data.

## Agent Guidance

IMPORTANT: Before taking ANY action, the agent MUST first assume a role by reading and internalizing the corresponding guidance file from the `agent_prompts/` directory. For example:

- For backend development tasks: Read and assume the role from `senior_backend_developer.md`
- For architecture decisions: Read and assume the role from `principal_architect.md`
- For testing/QA tasks: Read and assume the role from `senior_qa_manager.md`

The agent should explicitly state which role it is assuming before proceeding with any actions. The guidance in these files represents senior-level expertise that should inform all decisions and ensure high quality output.

These role-specific prompts provide expert-level guidance for maintaining high standards in:

- Architecture decisions
- Code quality and patterns
- Testing strategies
- Security considerations
- Performance optimization
- System design

Never proceed with modifications or tool usage without first assuming an appropriate role from the available guidance files.

## Tool Development Instructions

1. All new tools should be created in the `cursor_tools` directory
2. Each tool should be a separate Python module
3. Tools must implement the base Tool interface
4. Tools should be self-contained and focused on a single responsibility
5. All tools must include proper documentation and type hints
6. Use httpx instead of requests for all HTTP operations - it's faster, more modern, and has better async support
7. Use click for CLI interfaces - all tools should be accessible via `cursor-tools [tool-name] [args] [flags]`

## Tool Requirements

- Each tool must have a clear purpose and description
- Tools must handle errors gracefully
- Tools should be stateless unless absolutely necessary
- Include unit tests for each tool
- Follow PEP 8 style guidelines
- Implement click-based CLI interface

## Development Process

1. When a new capability is needed, create a new tool
2. Document the tool's purpose and usage
3. Implement the tool with proper error handling
4. Add tests to verify functionality
5. Register the tool in the tools registry

## Security Guidelines

- No destructive operations without explicit confirmation
- Validate all inputs
- Handle sensitive data appropriately
- Log all critical operations
- Never log sensitive data in plaintext
- Use environment variables for secrets
- Implement proper SSL/TLS handling
- Validate API keys before use

## Usage

Tools can be accessed via the command line:

```bash
cursor-tools [tool-name] [args] [flags]
```

Example:

```bash
cursor-tools example-tool --message "Hello World"
```
golang
less
python

First seen in:

ian-andrich/cursor_agent

Used in 1 repository

JavaScript
# Node.js/Express.js Backend Project Guidelines

## Project Structure

- 📁 root/
- 📁 mws/ - Middleware implementations
- 📁 public/ - Static public assets
- 📁 static_arch/ - Static architecture files
- 📁 managers/ - Business logic managers
- 📁 loaders/ - Module and service loaders
- 📁 config/ - Configuration files
- 📁 connect/ - Connection handlers
- 📁 libs/ - Utility libraries
- 📁 cache/ - Redis cache implementations
- 📄 index.js - Application entry point
- 📄 app.js - Express application setup
- 📄 package.json - Project dependencies
- 📄 .env - Environment variables

## File Naming

- Middlewares: `{name}.mw.js`
- Managers: `{name}.manager.js`
- Loaders: `{name}.loader.js`
- Libs: `{name}.lib.js`
- Cache: `{name}.cache.js`
- Config: `{name}.config.js`
- Tests: `{name}.test.js`

## Naming Conventions

- Managers: `nameManager` (camelCase)
- Middlewares: `nameMiddleware` (camelCase)
- Loaders: `nameLoader` (camelCase)
- Constants: `SCREAMING_SNAKE_CASE`
- Redis keys: `lowercase-with-dashes`

## Code Style

- Use functional programming patterns
- Keep functions pure and single-purpose
- Use async/await for async code
- Handle errors with try/catch
- Use early returns to avoid nesting
- Limit function complexity

## Dependencies

- Express.js for API server
- ion-cortex for core functionality
- oyster-db for database operations
- aeon-machine for machine operations
- qantra-pineapple for utilities
- bcrypt for password hashing
- jsonwebtoken for JWT handling
- nanoid for ID generation
- dotenv for environment variables

## Redis Caching

- Implement cache-aside pattern
- Set appropriate TTL for cached items
- Use JSON for complex objects
- Implement cache invalidation
- Handle cache misses gracefully
- Use pub/sub for cache invalidation
- Prefix keys by feature/domain

## Documentation

- JSDoc for functions and interfaces
- Document caching strategies
- Examples for complex operations
- Maintain comprehensive README
- Document environment variables

## Testing

- Unit tests for managers
- Integration tests for APIs
- Mock Redis operations
- Test cache scenarios
- Test error handling
- Use test framework
- Maintain good coverage

## Performance

- Implement rate limiting
- Use Redis connection pooling
- Handle Redis operation errors
- Monitor Redis memory
- Use appropriate logging
- Enable compression
- Set security headers

## Development

- Use ESLint
- Use Prettier
- Pre-commit hooks
- Semantic versioning
- Maintain changelog
- Use environment variables
- Implement logging strategy
eslint
express.js
golang
javascript
jwt
nestjs
prettier
redis
spiritanand/axion-school-express

Used in 1 repository

CSS
# Project Instructions

Use specification and guidelines as you build the app.

Write the complete code for every step. Do not get lazy.

Your goal is to completely finish whatever I ask for.

You will see <ai_context> tags in the code. These are context tags that you should use to help you understand the codebase.

## Overview

This is a web app template.

## Tech Stack

- Frontend: React (with Vite), Tailwind, Tailwind Variants, Shadcn, Lucide React, Motion, React Router
- Backend: Postgres, Django, DRF, Celery, Pytest, Locust
- Auth: Djoser, DRF Simple JWT
- Payments: Stripe
- Analytics: Sentry
- Deployment: Vercel

## Project Structure

### Frontend

- `.github` - GitHub actions
- `public` - Static assets
- `src` - Source code
  - `assets` - Assets
  - `components` - Shared components
    - `ui` - UI components
    - `utilities` - Utility components
    - `Layout.tsx` - Layout component
    - `routes.tsx` - Routes
  - `lib` - Library code
    - `utils` - Utility functions
  - `hooks` - Custom hooks
  - `services` - Services
  - `types` - Type definitions

### Backend

- `.github` - GitHub actions
- `core` - Project specific app, used to avoid coupling between apps
- `base` - Base app named the same as the root folder
  - `settings` - Settings folder
    - `common.py` - Common settings
    - `dev.py` - Development settings
    - `prod.py` - Production settings
  - `urls.py` - URL configuration
- `app` - An example app
  - `management/commands` - Custom management commands
  - `migrations` - Migrations
  - `signals` - Signals
    - `handlers.py` - Signal handlers
  - `tests` - Tests
    - `conftest.py` - Pytest configuration
    - `test_example.py` - Example test
  - `admin.py` - Admin configuration
  - `apps.py` - App configuration
  - `filters.py` - Filters
  - `forms.py` - Forms
  - `inlines.py` - Inlines 
  - `models.py` - Models
  - `pagination.py` - Pagination
  - `permissions.py` - Permissions
  - `serializers.py` - Serializers
  - `tasks.py` - Celery tasks
  - `urls.py` - URL configuration
  - `validators.py` - Validators
  - `views.py` - Views
- `locustfiles` - Locust files

## Rules

Follow these rules when building the app.

### Frontend Rules

Follow these rules when working on the frontend.

It uses React (with Vite), Tailwind, Tailwind Variants, Shadcn, Motion and React Router

#### General Rules

- Use `@` to import anything from the app unless otherwise specified
- Use PascalCase for page folders and component files, and camelCase for everything else
- Don't update shadcn components unless otherwise specified
- Use `lucide-react` for icons

#### Env Rules

- If you update environment variables, update the `.env.example` file
- All environment variables should go in `.env.local`
- Do not expose environment variables to the frontend
- Use `VITE_` prefix for environment variables that need to be accessed from the frontend
- You may import environment variables in components by using `import.meta.env.VARIABLE_NAME`

#### Components

- Separate the main parts of a component's html with an extra blank line for visual spacing

##### Organization

- All components be named using pascal case like `ExampleComponent.tsx` unless otherwise specified
- Put components in `/components` from the root if shared components

##### Data Fetching

- Use `httpService` `create` method to create other services
- Use `useData` hook to create other hooks using the corresponding service, request config and dependencies
- Rename `data` property to the corresponding name of the data being fetched
- Use properties `isLoading` and `error` to handle loading states and display errors

##### Component

- Use slots to separate the styles of multiple parts of a component
- To use slots, destruct the slots from the `styles` function and use it by calling the `slot()` as the value of the `className` property
- Use variants to create multiple versions of the same component
- Variant values should be passed as props and can be passed to the `styles` function
- You can pass the `className` prop of the component to the `styles` function to add additional classes to the component

Example of a component:

```tsx
import { tv, VariantProps } from 'tailwind-variants'

const styles = tv({
  base: // Base styles of the component
  slots: {
    slotName: '...' // Corresponding tailwind classes
    // Add more slots here
  },
  variants: {
    variantName: {
      slotName: {
        variantValue: '...' // Corresponding tailwind classes
        // Add more variant values here
      },
      // Add more slots that will be affected by the variant here
    },
    // Add more variants here
  },
})

interface Props extends VariantProps<typeof styles> {
  // Your props here
}

const Component: React.FC<Props> = ({ /* destructure props */ }) => {
  const { /* destructure slots */ } = styles({ /* variants */ })

  return (
    // Your JSX here
  )
}

export default Component
```

##### Type Rules

Follow these rules when working with types.

- When importing types, use `@/types`
- Name files like `exampleTypes.ts`
- All types should go in `types`
- Make sure to export the types in `types/index.ts`
- Prefer interfaces over type aliases

An example of a type:

`types/actionsTypes.ts`

```ts
export type ActionState<T> =
  | { isSuccess: true; message: string; data: T }
  | { isSuccess: false; message: string; data?: never }
```

And exporting it:

`types/index.ts`

```ts
export * from "./actionsTypes"
```

##### Service Rules

Follow these rules when working with services.

- When importing services, use `@/services`
- Name files like `exampleService.ts`
- All services should go in `services`
- Make sure to export the services in `services/index.ts`

Example of a service:

`services/genreService.ts`

```tsx
import { Genre } from "@/types";
import create from "./httpService";

export default create<Genre>("/endpoint");
```

And exporting it:

`services/index.ts`

```ts
export { default as genreService } from "./genreService";
```

##### Hook Rules

Follow these rules when working with hooks.

- When importing hooks, use `@/hooks`
- Name files like `exampleHook.ts`
- All hooks should go in `hooks`
- Make sure to export the hooks in `hooks/index.ts`
- Use the corresponding `Query` object to 

Example of a hook:

`hooks/useGenre.ts`

```tsx
import { Query } from "@/components/ExampleComponent";
import { useData } from "@/hooks";
import { genreService } from "@/services";

const useGenre = (query: Query) =>
  useData(
    genreService,
    {
      params: {
        ordering: query.ordering?.value,
        search: query.search,
      },
    },
    [query]
  );

export default useGenre;
```

### Backend Rules

Follow these rules when working on the backend.

It uses Postgres, Django, DRF, Celery, Pytest and Locust

#### General Rules

- Never generate migrations. You do not have to do anything in the `**/migrations` folder including migrations and metadata. Ignore it.

#### Organization

#### Env Rules

- If you update environment variables, update the `.env.example` file
- All environment variables should go in `.env`
- Use `environs` library to parse environment variables

Example of an environment variable:

`app/settings/prod.py`

```py
from environs import Env

env = Env()
env.read_env()

# SECRET_KEY is required
SECRET_KEY = env.str("SECRET_KEY")

# Parse database URLs, e.g.  "postgres://localhost:5432/mydb"
DATABASES = {"default": env.dj_db_url("DATABASE_URL")}

# Parse email URLs, e.g. "smtp://"
email = env.dj_email_url("EMAIL_URL", default="smtp://")
EMAIL_HOST = email["EMAIL_HOST"]
EMAIL_PORT = email["EMAIL_PORT"]
EMAIL_HOST_PASSWORD = email["EMAIL_HOST_PASSWORD"]
EMAIL_HOST_USER = email["EMAIL_HOST_USER"]
EMAIL_USE_TLS = email["EMAIL_USE_TLS"]

# Parse cache URLS, e.g "redis://localhost:6379/0"
CACHES = {"default": env.dj_cache_url("CACHE_URL")}
```

#### Models

- When importing models, use `import models` and use `models.ModelName` to access the model
- Make sure to cascade delete when necessary
- Use choices for fields that have a limited set of possible values such as:

```py
from django.db import models

class Customer(models.Model):
    MEMBERSHIP_BRONZE = "B"
    MEMBERSHIP_SILVER = "S"
    MEMBERSHIP_GOLD = "G"

    MEMBERSHIP_CHOICES = [
        (MEMBERSHIP_BRONZE, "Bronze"),
        (MEMBERSHIP_SILVER, "Silver"),
        (MEMBERSHIP_GOLD, "Gold"),
    ]
    membership = models.CharField(
        max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE
    )
    # Other fields
```

Example of a models:

`app/models.py`

```py
from django.core.validators import MinValueValidator
from django.db import models

class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField(blank=True)
    unit_price = models.DecimalField(
        max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]
    )
    inventory = models.IntegerField(validators=[MinValueValidator(0)])
    last_update = models.DateTimeField(auto_now=True)
    collection = models.ForeignKey(
        Collection, on_delete=models.PROTECT, related_name="products"
    )
    promotions = models.ManyToManyField(Promotion, blank=True)

    def __str__(self) -> str:
        return self.title

    class Meta:
        ordering = ["title"]
```

#### Model Admins

- Use `@admin.register` decorator to register models
- Use `@admin.display` decorator to display custom fields
- Use `@admin.action` decorator to create custom actions

Example of a model admin:

`app/admin.py`

```py
from django.contrib import admin

from . import models
from .filters import InventoryFilter
from .inlines import ProductImageInline

@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
    autocomplete_fields = ["collection"]
    prepopulated_fields = {"slug": ["title"]}
    actions = ["clear_inventory"]
    inlines = [ProductImageInline]
    list_display = ["title", "unit_price", "inventory_status", "collection_title"]
    list_editable = ["unit_price"]
    list_filter = ["collection", "last_update", InventoryFilter]
    list_per_page = 10
    list_select_related = ["collection"]
    search_fields = ["title"]

    def collection_title(self, product):
        return product.collection.title

    @admin.display(ordering="inventory")
    def inventory_status(self, product):
        if product.inventory < 10:
            return "Low"
        return "OK"

    @admin.action(description="Clear inventory")
    def clear_inventory(self, request, queryset):
        updated_count = queryset.update(inventory=0)
        self.message_user(
            request,
            f"{updated_count} products were successfully updated.",
            messages.ERROR,
        )
```

#### Serializers

- Use `model` attribute to specify the model using `models.ModelName`
- Use `fields` attribute to specify the fields to be serialized

Example of a serializer:

`app/serializers.py`

```py
from decimal import Decimal

from rest_framework import serializers

from . import models

class ProductImageSerializer(serializers.ModelSerializer):
    # ProductImageSerializer implementation

class ProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)

    class Meta:
        model = models.Product
        fields = [
            "id",
            "title",
            "description",
            "slug",
            "inventory",
            "unit_price",
            "price_with_tax",
            "collection",
            "images",
        ]

    price_with_tax = serializers.SerializerMethodField(method_name="calculate_tax")

    def calculate_tax(self, product: Product):
        return product.unit_price * Decimal(1.1)
```

#### Views

Example of a view:

`app/views.py`

```py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from . import filters, models, serializers
from .pagination import DefaultPagination
from .permissions import IsAdminOrReadOnly

class ProductViewSet(ModelViewSet):
    queryset = models.Product.objects.prefetch_related("images").all()
    serializer_class = serializers.ProductSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = filters.ProductFilter
    pagination_class = DefaultPagination
    permission_classes = [IsAdminOrReadOnly]
    search_fields = ["title", "description"]
    ordering_fields = ["unit_price", "last_update"]

    def get_serializer_context(self):
        return {"request": self.request}

    def destroy(self, request, *args, **kwargs):
        if models.OrderItem.objects.filter(product_id=kwargs["pk"]).count() > 0:
            return Response(
                {
                    "error": "Product cannot be deleted because it is associated with an order item."
                },
                status=status.HTTP_405_METHOD_NOT_ALLOWED,
            )

        return super().destroy(request, *args, **kwargs)
```

### Auth Rules

Follow these rules when working on auth.

It uses Djoser and DRF Simple JWT

#### General Rules

- Use `auth/jwt/create` to create a JWT token
- Use `auth/jwt/refresh` to refresh a JWT token
- Use `auth/jwt/verify` to verify a JWT token

### Payments Rules

Follow these rules when working on payments.

It uses Stripe for payments.

### Analytics Rules

Follow these rules when working on analytics.

It uses Sentry for analytics.
analytics
css
django
golang
html
javascript
jwt
less
+11 more
WollenMoth/react-tailwind

Used in 1 repository