Merge pull request #1 from killer-cf/feat-novo-botao
Ajuste de tela. Header, siderbar, criação de rodapé
This commit is contained in:
676
.cursor/rules/convex_rules.mdc
Normal file
676
.cursor/rules/convex_rules.mdc
Normal file
@@ -0,0 +1,676 @@
|
||||
---
|
||||
description: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples
|
||||
globs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx
|
||||
---
|
||||
|
||||
# Convex guidelines
|
||||
## Function guidelines
|
||||
### New function syntax
|
||||
- ALWAYS use the new function syntax for Convex functions. For example:
|
||||
```typescript
|
||||
import { query } from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
export const f = query({
|
||||
args: {},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
// Function body
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Http endpoint syntax
|
||||
- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:
|
||||
```typescript
|
||||
import { httpRouter } from "convex/server";
|
||||
import { httpAction } from "./_generated/server";
|
||||
const http = httpRouter();
|
||||
http.route({
|
||||
path: "/echo",
|
||||
method: "POST",
|
||||
handler: httpAction(async (ctx, req) => {
|
||||
const body = await req.bytes();
|
||||
return new Response(body, { status: 200 });
|
||||
}),
|
||||
});
|
||||
```
|
||||
- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.
|
||||
|
||||
### Validators
|
||||
- Below is an example of an array validator:
|
||||
```typescript
|
||||
import { mutation } from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default mutation({
|
||||
args: {
|
||||
simpleArray: v.array(v.union(v.string(), v.number())),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
//...
|
||||
},
|
||||
});
|
||||
```
|
||||
- Below is an example of a schema with validators that codify a discriminated union type:
|
||||
```typescript
|
||||
import { defineSchema, defineTable } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default defineSchema({
|
||||
results: defineTable(
|
||||
v.union(
|
||||
v.object({
|
||||
kind: v.literal("error"),
|
||||
errorMessage: v.string(),
|
||||
}),
|
||||
v.object({
|
||||
kind: v.literal("success"),
|
||||
value: v.number(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
});
|
||||
```
|
||||
- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:
|
||||
```typescript
|
||||
import { query } from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export const exampleQuery = query({
|
||||
args: {},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
console.log("This query returns a null value");
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
- Here are the valid Convex types along with their respective validators:
|
||||
Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes |
|
||||
| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Id | string | `doc._id` | `v.id(tableName)` | |
|
||||
| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. |
|
||||
| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. |
|
||||
| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. |
|
||||
| Boolean | boolean | `true` | `v.boolean()` |
|
||||
| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. |
|
||||
| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. |
|
||||
| Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. |
|
||||
| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". |
|
||||
| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". |
|
||||
|
||||
### Function registration
|
||||
- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.
|
||||
- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.
|
||||
- You CANNOT register a function through the `api` or `internal` objects.
|
||||
- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.
|
||||
- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.
|
||||
|
||||
### Function calling
|
||||
- Use `ctx.runQuery` to call a query from a query, mutation, or action.
|
||||
- Use `ctx.runMutation` to call a mutation from a mutation or action.
|
||||
- Use `ctx.runAction` to call an action from an action.
|
||||
- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.
|
||||
- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.
|
||||
- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.
|
||||
- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,
|
||||
```
|
||||
export const f = query({
|
||||
args: { name: v.string() },
|
||||
returns: v.string(),
|
||||
handler: async (ctx, args) => {
|
||||
return "Hello " + args.name;
|
||||
},
|
||||
});
|
||||
|
||||
export const g = query({
|
||||
args: {},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const result: string = await ctx.runQuery(api.example.f, { name: "Bob" });
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Function references
|
||||
- Function references are pointers to registered Convex functions.
|
||||
- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.
|
||||
- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.
|
||||
- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.
|
||||
- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.
|
||||
- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.
|
||||
|
||||
### Api design
|
||||
- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.
|
||||
- Use `query`, `mutation`, and `action` to define public functions.
|
||||
- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.
|
||||
|
||||
### Pagination
|
||||
- Paginated queries are queries that return a list of results in incremental pages.
|
||||
- You can define pagination using the following syntax:
|
||||
|
||||
```ts
|
||||
import { v } from "convex/values";
|
||||
import { query, mutation } from "./_generated/server";
|
||||
import { paginationOptsValidator } from "convex/server";
|
||||
export const listWithExtraArg = query({
|
||||
args: { paginationOpts: paginationOptsValidator, author: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db
|
||||
.query("messages")
|
||||
.filter((q) => q.eq(q.field("author"), args.author))
|
||||
.order("desc")
|
||||
.paginate(args.paginationOpts);
|
||||
},
|
||||
});
|
||||
```
|
||||
Note: `paginationOpts` is an object with the following properties:
|
||||
- `numItems`: the maximum number of documents to return (the validator is `v.number()`)
|
||||
- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)
|
||||
- A query that ends in `.paginate()` returns an object that has the following properties:
|
||||
- page (contains an array of documents that you fetches)
|
||||
- isDone (a boolean that represents whether or not this is the last page of documents)
|
||||
- continueCursor (a string that represents the cursor to use to fetch the next page of documents)
|
||||
|
||||
|
||||
## Validator guidelines
|
||||
- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.
|
||||
- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.
|
||||
|
||||
## Schema guidelines
|
||||
- Always define your schema in `convex/schema.ts`.
|
||||
- Always import the schema definition functions from `convex/server`:
|
||||
- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.
|
||||
- Always include all index fields in the index name. For example, if an index is defined as `["field1", "field2"]`, the index name should be "by_field1_and_field2".
|
||||
- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes.
|
||||
|
||||
## Typescript guidelines
|
||||
- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.
|
||||
- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:
|
||||
```ts
|
||||
import { query } from "./_generated/server";
|
||||
import { Doc, Id } from "./_generated/dataModel";
|
||||
|
||||
export const exampleQuery = query({
|
||||
args: { userIds: v.array(v.id("users")) },
|
||||
returns: v.record(v.id("users"), v.string()),
|
||||
handler: async (ctx, args) => {
|
||||
const idToUsername: Record<Id<"users">, string> = {};
|
||||
for (const userId of args.userIds) {
|
||||
const user = await ctx.db.get(userId);
|
||||
if (user) {
|
||||
idToUsername[user._id] = user.username;
|
||||
}
|
||||
}
|
||||
|
||||
return idToUsername;
|
||||
},
|
||||
});
|
||||
```
|
||||
- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.
|
||||
- Always use `as const` for string literals in discriminated union types.
|
||||
- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`
|
||||
- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`
|
||||
- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.
|
||||
|
||||
## Full text search guidelines
|
||||
- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like:
|
||||
|
||||
const messages = await ctx.db
|
||||
.query("messages")
|
||||
.withSearchIndex("search_body", (q) =>
|
||||
q.search("body", "hello hi").eq("channel", "#general"),
|
||||
)
|
||||
.take(10);
|
||||
|
||||
## Query guidelines
|
||||
- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.
|
||||
- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.
|
||||
- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.
|
||||
- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.
|
||||
### Ordering
|
||||
- By default Convex always returns documents in ascending `_creationTime` order.
|
||||
- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.
|
||||
- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.
|
||||
|
||||
|
||||
## Mutation guidelines
|
||||
- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist.
|
||||
- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist.
|
||||
|
||||
## Action guidelines
|
||||
- Always add `"use node";` to the top of files containing actions that use Node.js built-in modules.
|
||||
- Never use `ctx.db` inside of an action. Actions don't have access to the database.
|
||||
- Below is an example of the syntax for an action:
|
||||
```ts
|
||||
import { action } from "./_generated/server";
|
||||
|
||||
export const exampleAction = action({
|
||||
args: {},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
console.log("This action does not return anything");
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Scheduling guidelines
|
||||
### Cron guidelines
|
||||
- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.
|
||||
- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.
|
||||
- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,
|
||||
```ts
|
||||
import { cronJobs } from "convex/server";
|
||||
import { internal } from "./_generated/api";
|
||||
import { internalAction } from "./_generated/server";
|
||||
|
||||
const empty = internalAction({
|
||||
args: {},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
console.log("empty");
|
||||
},
|
||||
});
|
||||
|
||||
const crons = cronJobs();
|
||||
|
||||
// Run `internal.crons.empty` every two hours.
|
||||
crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {});
|
||||
|
||||
export default crons;
|
||||
```
|
||||
- You can register Convex functions within `crons.ts` just like any other file.
|
||||
- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file.
|
||||
|
||||
|
||||
## File storage guidelines
|
||||
- Convex includes file storage for large files like images, videos, and PDFs.
|
||||
- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.
|
||||
- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.
|
||||
|
||||
Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`.
|
||||
```
|
||||
import { query } from "./_generated/server";
|
||||
import { Id } from "./_generated/dataModel";
|
||||
|
||||
type FileMetadata = {
|
||||
_id: Id<"_storage">;
|
||||
_creationTime: number;
|
||||
contentType?: string;
|
||||
sha256: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export const exampleQuery = query({
|
||||
args: { fileId: v.id("_storage") },
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const metadata: FileMetadata | null = await ctx.db.system.get(args.fileId);
|
||||
console.log(metadata);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.
|
||||
|
||||
|
||||
# Examples:
|
||||
## Example: chat-app
|
||||
|
||||
### Task
|
||||
```
|
||||
Create a real-time chat application backend with AI responses. The app should:
|
||||
- Allow creating users with names
|
||||
- Support multiple chat channels
|
||||
- Enable users to send messages to channels
|
||||
- Automatically generate AI responses to user messages
|
||||
- Show recent message history
|
||||
|
||||
The backend should provide APIs for:
|
||||
1. User management (creation)
|
||||
2. Channel management (creation)
|
||||
3. Message operations (sending, listing)
|
||||
4. AI response generation using OpenAI's GPT-4
|
||||
|
||||
Messages should be stored with their channel, author, and content. The system should maintain message order
|
||||
and limit history display to the 10 most recent messages per channel.
|
||||
|
||||
```
|
||||
|
||||
### Analysis
|
||||
1. Task Requirements Summary:
|
||||
- Build a real-time chat backend with AI integration
|
||||
- Support user creation
|
||||
- Enable channel-based conversations
|
||||
- Store and retrieve messages with proper ordering
|
||||
- Generate AI responses automatically
|
||||
|
||||
2. Main Components Needed:
|
||||
- Database tables: users, channels, messages
|
||||
- Public APIs for user/channel management
|
||||
- Message handling functions
|
||||
- Internal AI response generation system
|
||||
- Context loading for AI responses
|
||||
|
||||
3. Public API and Internal Functions Design:
|
||||
Public Mutations:
|
||||
- createUser:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {name: v.string()}
|
||||
- returns: v.object({userId: v.id("users")})
|
||||
- purpose: Create a new user with a given name
|
||||
- createChannel:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {name: v.string()}
|
||||
- returns: v.object({channelId: v.id("channels")})
|
||||
- purpose: Create a new channel with a given name
|
||||
- sendMessage:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {channelId: v.id("channels"), authorId: v.id("users"), content: v.string()}
|
||||
- returns: v.null()
|
||||
- purpose: Send a message to a channel and schedule a response from the AI
|
||||
|
||||
Public Queries:
|
||||
- listMessages:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {channelId: v.id("channels")}
|
||||
- returns: v.array(v.object({
|
||||
_id: v.id("messages"),
|
||||
_creationTime: v.number(),
|
||||
channelId: v.id("channels"),
|
||||
authorId: v.optional(v.id("users")),
|
||||
content: v.string(),
|
||||
}))
|
||||
- purpose: List the 10 most recent messages from a channel in descending creation order
|
||||
|
||||
Internal Functions:
|
||||
- generateResponse:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {channelId: v.id("channels")}
|
||||
- returns: v.null()
|
||||
- purpose: Generate a response from the AI for a given channel
|
||||
- loadContext:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {channelId: v.id("channels")}
|
||||
- returns: v.array(v.object({
|
||||
_id: v.id("messages"),
|
||||
_creationTime: v.number(),
|
||||
channelId: v.id("channels"),
|
||||
authorId: v.optional(v.id("users")),
|
||||
content: v.string(),
|
||||
}))
|
||||
- writeAgentResponse:
|
||||
- file path: convex/index.ts
|
||||
- arguments: {channelId: v.id("channels"), content: v.string()}
|
||||
- returns: v.null()
|
||||
- purpose: Write an AI response to a given channel
|
||||
|
||||
4. Schema Design:
|
||||
- users
|
||||
- validator: { name: v.string() }
|
||||
- indexes: <none>
|
||||
- channels
|
||||
- validator: { name: v.string() }
|
||||
- indexes: <none>
|
||||
- messages
|
||||
- validator: { channelId: v.id("channels"), authorId: v.optional(v.id("users")), content: v.string() }
|
||||
- indexes
|
||||
- by_channel: ["channelId"]
|
||||
|
||||
5. Background Processing:
|
||||
- AI response generation runs asynchronously after each user message
|
||||
- Uses OpenAI's GPT-4 to generate contextual responses
|
||||
- Maintains conversation context using recent message history
|
||||
|
||||
|
||||
### Implementation
|
||||
|
||||
#### package.json
|
||||
```typescript
|
||||
{
|
||||
"name": "chat-app",
|
||||
"description": "This example shows how to build a chat app without authentication.",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"convex": "^1.17.4",
|
||||
"openai": "^4.79.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### tsconfig.json
|
||||
```typescript
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"skipLibCheck": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"exclude": ["convex"],
|
||||
"include": ["**/src/**/*.tsx", "**/src/**/*.ts", "vite.config.ts"]
|
||||
}
|
||||
```
|
||||
|
||||
#### convex/index.ts
|
||||
```typescript
|
||||
import {
|
||||
query,
|
||||
mutation,
|
||||
internalQuery,
|
||||
internalMutation,
|
||||
internalAction,
|
||||
} from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
import OpenAI from "openai";
|
||||
import { internal } from "./_generated/api";
|
||||
|
||||
/**
|
||||
* Create a user with a given name.
|
||||
*/
|
||||
export const createUser = mutation({
|
||||
args: {
|
||||
name: v.string(),
|
||||
},
|
||||
returns: v.id("users"),
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.insert("users", { name: args.name });
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Create a channel with a given name.
|
||||
*/
|
||||
export const createChannel = mutation({
|
||||
args: {
|
||||
name: v.string(),
|
||||
},
|
||||
returns: v.id("channels"),
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.insert("channels", { name: args.name });
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* List the 10 most recent messages from a channel in descending creation order.
|
||||
*/
|
||||
export const listMessages = query({
|
||||
args: {
|
||||
channelId: v.id("channels"),
|
||||
},
|
||||
returns: v.array(
|
||||
v.object({
|
||||
_id: v.id("messages"),
|
||||
_creationTime: v.number(),
|
||||
channelId: v.id("channels"),
|
||||
authorId: v.optional(v.id("users")),
|
||||
content: v.string(),
|
||||
}),
|
||||
),
|
||||
handler: async (ctx, args) => {
|
||||
const messages = await ctx.db
|
||||
.query("messages")
|
||||
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
|
||||
.order("desc")
|
||||
.take(10);
|
||||
return messages;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Send a message to a channel and schedule a response from the AI.
|
||||
*/
|
||||
export const sendMessage = mutation({
|
||||
args: {
|
||||
channelId: v.id("channels"),
|
||||
authorId: v.id("users"),
|
||||
content: v.string(),
|
||||
},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const channel = await ctx.db.get(args.channelId);
|
||||
if (!channel) {
|
||||
throw new Error("Channel not found");
|
||||
}
|
||||
const user = await ctx.db.get(args.authorId);
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
await ctx.db.insert("messages", {
|
||||
channelId: args.channelId,
|
||||
authorId: args.authorId,
|
||||
content: args.content,
|
||||
});
|
||||
await ctx.scheduler.runAfter(0, internal.index.generateResponse, {
|
||||
channelId: args.channelId,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
const openai = new OpenAI();
|
||||
|
||||
export const generateResponse = internalAction({
|
||||
args: {
|
||||
channelId: v.id("channels"),
|
||||
},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const context = await ctx.runQuery(internal.index.loadContext, {
|
||||
channelId: args.channelId,
|
||||
});
|
||||
const response = await openai.chat.completions.create({
|
||||
model: "gpt-4o",
|
||||
messages: context,
|
||||
});
|
||||
const content = response.choices[0].message.content;
|
||||
if (!content) {
|
||||
throw new Error("No content in response");
|
||||
}
|
||||
await ctx.runMutation(internal.index.writeAgentResponse, {
|
||||
channelId: args.channelId,
|
||||
content,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
export const loadContext = internalQuery({
|
||||
args: {
|
||||
channelId: v.id("channels"),
|
||||
},
|
||||
returns: v.array(
|
||||
v.object({
|
||||
role: v.union(v.literal("user"), v.literal("assistant")),
|
||||
content: v.string(),
|
||||
}),
|
||||
),
|
||||
handler: async (ctx, args) => {
|
||||
const channel = await ctx.db.get(args.channelId);
|
||||
if (!channel) {
|
||||
throw new Error("Channel not found");
|
||||
}
|
||||
const messages = await ctx.db
|
||||
.query("messages")
|
||||
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
|
||||
.order("desc")
|
||||
.take(10);
|
||||
|
||||
const result = [];
|
||||
for (const message of messages) {
|
||||
if (message.authorId) {
|
||||
const user = await ctx.db.get(message.authorId);
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
result.push({
|
||||
role: "user" as const,
|
||||
content: `${user.name}: ${message.content}`,
|
||||
});
|
||||
} else {
|
||||
result.push({ role: "assistant" as const, content: message.content });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
export const writeAgentResponse = internalMutation({
|
||||
args: {
|
||||
channelId: v.id("channels"),
|
||||
content: v.string(),
|
||||
},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
await ctx.db.insert("messages", {
|
||||
channelId: args.channelId,
|
||||
content: args.content,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### convex/schema.ts
|
||||
```typescript
|
||||
import { defineSchema, defineTable } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default defineSchema({
|
||||
channels: defineTable({
|
||||
name: v.string(),
|
||||
}),
|
||||
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
}),
|
||||
|
||||
messages: defineTable({
|
||||
channelId: v.id("channels"),
|
||||
authorId: v.optional(v.id("users")),
|
||||
content: v.string(),
|
||||
}).index("by_channel", ["channelId"]),
|
||||
});
|
||||
```
|
||||
|
||||
#### src/App.tsx
|
||||
```typescript
|
||||
export default function App() {
|
||||
return <div>Hello World</div>;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -22,43 +22,120 @@
|
||||
];
|
||||
</script>
|
||||
|
||||
<div class="drawer lg:drawer-open">
|
||||
<input id="my-drawer-3" type="checkbox" class="drawer-toggle" />
|
||||
<div class="drawer-content flex flex-col items-center">
|
||||
<!-- Page content here -->
|
||||
{@render children?.()}
|
||||
|
||||
<label for="my-drawer-3" class="btn drawer-button lg:hidden">
|
||||
Open drawer
|
||||
<!-- Header Fixo acima de tudo -->
|
||||
<div class="navbar bg-base-200 shadow-md px-6 lg:px-8 fixed top-0 left-0 right-0 z-50 min-h-20">
|
||||
<div class="flex-none lg:hidden">
|
||||
<label for="my-drawer-3" class="btn btn-square btn-ghost">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
class="inline-block w-6 h-6 stroke-current"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M4 6h16M4 12h16M4 18h16"
|
||||
></path>
|
||||
</svg>
|
||||
</label>
|
||||
</div>
|
||||
<div class="drawer-side">
|
||||
<label for="my-drawer-3" aria-label="close sidebar" class="drawer-overlay"
|
||||
></label>
|
||||
<ul class="menu bg-base-200 min-h-full w-76 p-4 gap-4">
|
||||
<img src={logo} alt="Logo" class="" />
|
||||
<!-- Sidebar content here -->
|
||||
<li class="bg-primary rounded-2xl mt-4">
|
||||
<a href="/">
|
||||
<span>Dashboard</span>
|
||||
</a>
|
||||
</li>
|
||||
{#each setores as s}
|
||||
<li class="bg-primary rounded-2xl">
|
||||
<a
|
||||
href={s.link}
|
||||
class:active={page.url.pathname === s.link}
|
||||
aria-current={page.url.pathname === s.link ? "page" : undefined}
|
||||
>
|
||||
<span>{s.nome}</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
<li class="bg-primary rounded-2xl">
|
||||
<a href="/">
|
||||
<span>Solicitar acesso</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="flex-1 flex items-center gap-4">
|
||||
<img src={logo} alt="Logo do Governo de PE" class="h-14 lg:h-16 w-auto hidden lg:block" />
|
||||
<div class="flex flex-col">
|
||||
<h1 class="text-xl lg:text-3xl font-bold text-primary">SGSE</h1>
|
||||
<p class="text-sm lg:text-base text-base-content/70 hidden sm:block font-medium">
|
||||
Sistema de Gerenciamento da Secretaria de Esportes
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="drawer lg:drawer-open" style="margin-top: 80px;">
|
||||
<input id="my-drawer-3" type="checkbox" class="drawer-toggle" />
|
||||
<div class="drawer-content flex flex-col lg:ml-72" style="min-height: calc(100vh - 80px);">
|
||||
<!-- Page content -->
|
||||
<div class="flex-1">
|
||||
{@render children?.()}
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="footer footer-center bg-base-200 text-base-content p-6 border-t border-base-300 mt-auto">
|
||||
<div class="grid grid-flow-col gap-4">
|
||||
<a href="/" class="link link-hover text-sm">Sobre</a>
|
||||
<a href="/" class="link link-hover text-sm">Contato</a>
|
||||
<a href="/" class="link link-hover text-sm">Suporte</a>
|
||||
<a href="/" class="link link-hover text-sm">Política de Privacidade</a>
|
||||
</div>
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<img src={logo} alt="Logo" class="h-8 w-auto" />
|
||||
<span class="font-semibold">Governo do Estado de Pernambuco</span>
|
||||
</div>
|
||||
<p class="text-sm text-base-content/70">
|
||||
Secretaria de Esportes © {new Date().getFullYear()} - Todos os direitos reservados
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
<div class="drawer-side z-40 fixed" style="margin-top: 80px;">
|
||||
<label for="my-drawer-3" aria-label="close sidebar" class="drawer-overlay"
|
||||
></label>
|
||||
<div class="menu bg-base-200 w-72 p-4 flex flex-col gap-2 h-[calc(100vh-80px)] overflow-y-auto">
|
||||
<!-- Sidebar menu items -->
|
||||
<ul class="flex flex-col gap-2">
|
||||
<li class="bg-primary rounded-xl">
|
||||
<a href="/" class="font-medium">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
|
||||
/>
|
||||
</svg>
|
||||
<span>Dashboard</span>
|
||||
</a>
|
||||
</li>
|
||||
{#each setores as s}
|
||||
<li class="bg-primary rounded-xl">
|
||||
<a
|
||||
href={s.link}
|
||||
class:active={page.url.pathname.startsWith(s.link)}
|
||||
aria-current={page.url.pathname.startsWith(s.link) ? "page" : undefined}
|
||||
class="font-medium"
|
||||
>
|
||||
<span>{s.nome}</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
<li class="bg-primary rounded-xl mt-auto">
|
||||
<a href="/" class="font-medium">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
|
||||
/>
|
||||
</svg>
|
||||
<span>Solicitar acesso</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
const { children } = $props();
|
||||
</script>
|
||||
|
||||
<div class="max-w-[1600px w-full">
|
||||
<div class="w-full">
|
||||
<main
|
||||
id="container-central"
|
||||
class="m-3 rounded-xl shadow-sm overflow-y-auto p-4"
|
||||
class="container mx-auto p-4 lg:p-6 max-w-7xl"
|
||||
>
|
||||
{@render children()}
|
||||
</main>
|
||||
|
||||
@@ -1,21 +1,247 @@
|
||||
<script lang="ts">
|
||||
import { useQuery } from "convex-svelte";
|
||||
import { useQuery, useConvexClient } from "convex-svelte";
|
||||
import { api } from "@sgse-app/backend/convex/_generated/api";
|
||||
import type { Id } from "@sgse-app/backend/convex/_generated/dataModel";
|
||||
|
||||
const client = useConvexClient();
|
||||
const simbolosQuery = useQuery(api.simbolos.getAll, {});
|
||||
|
||||
let deletingId: Id<"simbolos"> | null = null;
|
||||
let simboloToDelete: { id: Id<"simbolos">; nome: string } | null = null;
|
||||
|
||||
function openDeleteModal(id: Id<"simbolos">, nome: string) {
|
||||
simboloToDelete = { id, nome };
|
||||
(document.getElementById("delete_modal") as HTMLDialogElement)?.showModal();
|
||||
}
|
||||
|
||||
function closeDeleteModal() {
|
||||
simboloToDelete = null;
|
||||
(document.getElementById("delete_modal") as HTMLDialogElement)?.close();
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!simboloToDelete) return;
|
||||
|
||||
try {
|
||||
deletingId = simboloToDelete.id;
|
||||
await client.mutation(api.simbolos.remove, { id: simboloToDelete.id });
|
||||
closeDeleteModal();
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir símbolo:", error);
|
||||
alert("Erro ao excluir símbolo. Tente novamente.");
|
||||
} finally {
|
||||
deletingId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatMoney(value: string) {
|
||||
const num = parseFloat(value);
|
||||
if (isNaN(num)) return "R$ 0,00";
|
||||
return `R$ ${num.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
}
|
||||
|
||||
function getTipoLabel(tipo: string) {
|
||||
return tipo === "cargo_comissionado" ? "Cargo Comissionado" : "Função Gratificada";
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
<h2 class="text-3xl font-bold text-brand-dark">Simbolos</h2>
|
||||
<div class="space-y-6 pb-32">
|
||||
<div class="flex justify-between items-center">
|
||||
<h2 class="text-3xl font-bold text-brand-dark">Símbolos</h2>
|
||||
<a href="/recursos-humanos/simbolos/cadastro" class="btn btn-primary">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
Novo Símbolo
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{#each simbolosQuery.data as simbolo}
|
||||
<div class="p-4 rounded-xl border hover:shadow bgbase-100">
|
||||
<h3 class="text-lg font-bold text-brand-dark">{simbolo.nome}</h3>
|
||||
<p class="text-sm text-gray-500">{simbolo.vencValor}</p>
|
||||
<p class="text-sm text-gray-500">{simbolo.repValor}</p>
|
||||
<p class="text-sm text-gray-500">{simbolo.descricao}</p>
|
||||
{#if simbolosQuery.isLoading}
|
||||
<div class="flex justify-center items-center py-12">
|
||||
<span class="loading loading-spinner loading-lg"></span>
|
||||
</div>
|
||||
{:else if simbolosQuery.data && simbolosQuery.data.length > 0}
|
||||
<div class="overflow-x-auto bg-base-100 rounded-lg shadow-sm mb-8">
|
||||
<table class="table table-zebra">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nome</th>
|
||||
<th>Tipo</th>
|
||||
<th>Valor Referência</th>
|
||||
<th>Valor Vencimento</th>
|
||||
<th>Valor Total</th>
|
||||
<th>Descrição</th>
|
||||
<th class="text-right">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each simbolosQuery.data as simbolo}
|
||||
<tr class="hover">
|
||||
<td class="font-medium">{simbolo.nome}</td>
|
||||
<td>
|
||||
<span
|
||||
class="badge"
|
||||
class:badge-primary={simbolo.tipo === "cargo_comissionado"}
|
||||
class:badge-secondary={simbolo.tipo === "funcao_gratificada"}
|
||||
>
|
||||
{getTipoLabel(simbolo.tipo)}
|
||||
</span>
|
||||
</td>
|
||||
<td>{simbolo.repValor ? formatMoney(simbolo.repValor) : "—"}</td>
|
||||
<td>{simbolo.vencValor ? formatMoney(simbolo.vencValor) : "—"}</td>
|
||||
<td class="font-semibold">{formatMoney(simbolo.valor)}</td>
|
||||
<td class="max-w-xs truncate">{simbolo.descricao}</td>
|
||||
<td class="text-right">
|
||||
<div class="dropdown dropdown-end">
|
||||
<div tabindex="0" role="button" class="btn btn-ghost btn-sm">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<ul
|
||||
tabindex="0"
|
||||
class="dropdown-content menu bg-base-100 rounded-box z-10 w-52 p-2 shadow-lg border border-base-300"
|
||||
>
|
||||
<li>
|
||||
<a href="/recursos-humanos/simbolos/{simbolo._id}/editar">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-4 w-4"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"
|
||||
/>
|
||||
</svg>
|
||||
Editar
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
on:click={() => openDeleteModal(simbolo._id, simbolo.nome)}
|
||||
class="text-error"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-4 w-4"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
Excluir
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{:else}
|
||||
<p>Nenhum simbolo encontrado</p>
|
||||
{/each}
|
||||
<div class="alert">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
class="stroke-info shrink-0 w-6 h-6"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
></path>
|
||||
</svg>
|
||||
<span>Nenhum símbolo encontrado. Crie um novo para começar.</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Modal de Confirmação de Exclusão -->
|
||||
<dialog id="delete_modal" class="modal">
|
||||
<div class="modal-box">
|
||||
<h3 class="font-bold text-lg mb-4">Confirmar Exclusão</h3>
|
||||
<div class="alert alert-warning mb-4">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="stroke-current shrink-0 h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
|
||||
/>
|
||||
</svg>
|
||||
<span>Esta ação não pode ser desfeita!</span>
|
||||
</div>
|
||||
{#if simboloToDelete}
|
||||
<p class="py-2">
|
||||
Tem certeza que deseja excluir o símbolo <strong class="text-error"
|
||||
>{simboloToDelete.nome}</strong
|
||||
>?
|
||||
</p>
|
||||
{/if}
|
||||
<div class="modal-action">
|
||||
<form method="dialog" class="flex gap-2">
|
||||
<button class="btn btn-ghost" on:click={closeDeleteModal} type="button">
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-error"
|
||||
on:click={confirmDelete}
|
||||
disabled={deletingId !== null}
|
||||
type="button"
|
||||
>
|
||||
{#if deletingId}
|
||||
<span class="loading loading-spinner loading-sm"></span>
|
||||
Excluindo...
|
||||
{:else}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
Confirmar Exclusão
|
||||
{/if}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<form method="dialog" class="modal-backdrop">
|
||||
<button>close</button>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
<script lang="ts">
|
||||
import { useQuery, useConvexClient } from "convex-svelte";
|
||||
import { api } from "@sgse-app/backend/convex/_generated/api";
|
||||
import { createForm } from "@tanstack/svelte-form";
|
||||
import z from "zod";
|
||||
import { Save } from "lucide-svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { page } from "$app/stores";
|
||||
import type { SimboloTipo } from "@sgse-app/backend/convex/schema";
|
||||
import type { Id } from "@sgse-app/backend/convex/_generated/dataModel";
|
||||
|
||||
const client = useConvexClient();
|
||||
const simboloId = $page.params.simboloId as Id<"simbolos">;
|
||||
|
||||
const simboloQuery = useQuery(api.simbolos.getById, { id: simboloId });
|
||||
|
||||
let tipo = $state<SimboloTipo>("cargo_comissionado");
|
||||
let isFormInitialized = $state(false);
|
||||
|
||||
const schema = z.object({
|
||||
nome: z.string().min(1),
|
||||
refValor: z.string().optional(),
|
||||
vencValor: z.string().optional(),
|
||||
descricao: z.string().min(1),
|
||||
tipo: z.enum(["cargo_comissionado", "funcao_gratificada"]),
|
||||
valor: z.string().optional(),
|
||||
});
|
||||
|
||||
function formatCurrencyBR(raw: string): string {
|
||||
const digits = (raw || "").replace(/\D/g, "");
|
||||
if (!digits) return "";
|
||||
const number = parseInt(digits, 10);
|
||||
const cents = (number / 100).toFixed(2);
|
||||
const [intPart, decPart] = cents.split(".");
|
||||
const intWithThousands = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
|
||||
return `${intWithThousands},${decPart}`;
|
||||
}
|
||||
|
||||
function unmaskCurrencyToDotDecimal(masked: string): string {
|
||||
if (!masked) return "";
|
||||
const digits = masked.replace(/\D/g, "");
|
||||
if (!digits) return "";
|
||||
const value = (parseInt(digits, 10) / 100).toFixed(2);
|
||||
return value;
|
||||
}
|
||||
|
||||
function formatDotDecimalToBR(value: string): string {
|
||||
if (!value) return "";
|
||||
const [intPart, decRaw] = value.split(".");
|
||||
const intDigits = (intPart || "0").replace(/\D/g, "");
|
||||
const intWithThousands = intDigits.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
|
||||
const decPart = (decRaw ?? "00").padEnd(2, "0").slice(0, 2);
|
||||
return `${intWithThousands},${decPart}`;
|
||||
}
|
||||
|
||||
let notice = $state<{ kind: "success" | "error"; text: string } | null>(null);
|
||||
|
||||
function getTotalPreview(): string {
|
||||
if (tipo !== "cargo_comissionado") return "";
|
||||
const r = unmaskCurrencyToDotDecimal(form.getFieldValue("refValor"));
|
||||
const v = unmaskCurrencyToDotDecimal(form.getFieldValue("vencValor"));
|
||||
if (!r || !v) return "";
|
||||
const sum = (Number(r) + Number(v)).toFixed(2);
|
||||
return formatDotDecimalToBR(sum);
|
||||
}
|
||||
|
||||
const form = createForm(() => ({
|
||||
onSubmit: async ({ value }) => {
|
||||
const isCargo = value.tipo === "cargo_comissionado";
|
||||
const payload = {
|
||||
id: simboloId,
|
||||
nome: value.nome,
|
||||
refValor: isCargo ? unmaskCurrencyToDotDecimal(value.refValor) : "",
|
||||
vencValor: isCargo ? unmaskCurrencyToDotDecimal(value.vencValor) : "",
|
||||
descricao: value.descricao,
|
||||
tipo: value.tipo as SimboloTipo,
|
||||
valor: !isCargo ? unmaskCurrencyToDotDecimal(value.valor) : undefined,
|
||||
};
|
||||
|
||||
try {
|
||||
await client.mutation(api.simbolos.update, payload);
|
||||
notice = { kind: "success", text: "Símbolo atualizado com sucesso." };
|
||||
setTimeout(() => goto("/recursos-humanos/simbolos"), 600);
|
||||
} catch (error) {
|
||||
console.error("erro ao atualizar símbolo", error);
|
||||
notice = { kind: "error", text: "Erro ao atualizar símbolo." };
|
||||
}
|
||||
},
|
||||
defaultValues: {
|
||||
nome: "",
|
||||
refValor: "",
|
||||
vencValor: "",
|
||||
descricao: "",
|
||||
tipo: "cargo_comissionado",
|
||||
valor: "",
|
||||
},
|
||||
}));
|
||||
|
||||
// Inicializar o formulário quando os dados estiverem disponíveis
|
||||
$effect(() => {
|
||||
if (simboloQuery.data && !isFormInitialized) {
|
||||
const simbolo = simboloQuery.data;
|
||||
|
||||
tipo = simbolo.tipo;
|
||||
|
||||
form.setFieldValue("nome", simbolo.nome);
|
||||
form.setFieldValue("descricao", simbolo.descricao);
|
||||
form.setFieldValue("tipo", simbolo.tipo);
|
||||
|
||||
if (simbolo.tipo === "cargo_comissionado") {
|
||||
form.setFieldValue("refValor", formatDotDecimalToBR(simbolo.repValor));
|
||||
form.setFieldValue("vencValor", formatDotDecimalToBR(simbolo.vencValor));
|
||||
} else {
|
||||
form.setFieldValue("valor", formatDotDecimalToBR(simbolo.valor));
|
||||
}
|
||||
|
||||
isFormInitialized = true;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if simboloQuery.isLoading}
|
||||
<div class="flex justify-center items-center py-12">
|
||||
<span class="loading loading-spinner loading-lg"></span>
|
||||
</div>
|
||||
{:else if !simboloQuery.data}
|
||||
<div class="alert alert-error max-w-3xl mx-auto m-4">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="stroke-current shrink-0 h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
<span>Símbolo não encontrado.</span>
|
||||
</div>
|
||||
{:else}
|
||||
<form
|
||||
class="max-w-3xl mx-auto p-4"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
form.handleSubmit();
|
||||
}}
|
||||
>
|
||||
<div class="card bg-base-100 shadow-xl">
|
||||
<div class="card-body space-y-6">
|
||||
{#if notice}
|
||||
<div
|
||||
class="alert"
|
||||
class:alert-success={notice.kind === "success"}
|
||||
class:alert-error={notice.kind === "error"}
|
||||
>
|
||||
<span>{notice.text}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<div>
|
||||
<h2 class="card-title text-3xl">Editar Símbolo</h2>
|
||||
<p class="opacity-70">
|
||||
Atualize os campos abaixo para editar o símbolo.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form.Field name="nome" validators={{ onChange: schema.shape.nome }}>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="nome">
|
||||
<span class="label-text font-medium"
|
||||
>Símbolo <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<input
|
||||
{name}
|
||||
value={state.value}
|
||||
placeholder="Ex.: DAS-1"
|
||||
class="input input-bordered w-full"
|
||||
autocomplete="off"
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const value = target.value;
|
||||
handleChange(value);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
/>
|
||||
<div class="label">
|
||||
<span class="label-text-alt opacity-60"
|
||||
>Informe o nome identificador do símbolo.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
|
||||
<form.Field
|
||||
name="descricao"
|
||||
validators={{ onChange: schema.shape.descricao }}
|
||||
>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="descricao">
|
||||
<span class="label-text font-medium"
|
||||
>Descrição <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<input
|
||||
{name}
|
||||
value={state.value}
|
||||
placeholder="Ex.: Cargo de Apoio 1"
|
||||
class="input input-bordered w-full"
|
||||
autocomplete="off"
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const value = target.value;
|
||||
handleChange(value);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
/>
|
||||
<div class="label">
|
||||
<span class="label-text-alt opacity-60"
|
||||
>Descreva brevemente o símbolo.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
|
||||
<form.Field
|
||||
name="tipo"
|
||||
validators={{
|
||||
onChange: ({ value }) => (value ? undefined : "Obrigatório"),
|
||||
}}
|
||||
>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="tipo">
|
||||
<span class="label-text font-medium"
|
||||
>Tipo <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<select
|
||||
{name}
|
||||
class="select select-bordered w-full"
|
||||
bind:value={tipo}
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLSelectElement;
|
||||
const value = target.value;
|
||||
handleChange(value);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
>
|
||||
<option value="cargo_comissionado">Cargo comissionado</option>
|
||||
<option value="funcao_gratificada">Função gratificada</option>
|
||||
</select>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
|
||||
{#if tipo === "cargo_comissionado"}
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<form.Field
|
||||
name="vencValor"
|
||||
validators={{
|
||||
onChange: ({ value }) =>
|
||||
form.getFieldValue("tipo") === "cargo_comissionado" && !value
|
||||
? "Obrigatório"
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="vencValor">
|
||||
<span class="label-text font-medium"
|
||||
>Valor de Vencimento <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<input
|
||||
{name}
|
||||
value={state.value}
|
||||
placeholder="Ex.: 1200,00"
|
||||
class="input input-bordered w-full"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const formatted = formatCurrencyBR(target.value);
|
||||
target.value = formatted;
|
||||
handleChange(formatted);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
/>
|
||||
<div class="label">
|
||||
<span class="label-text-alt opacity-60"
|
||||
>Valor efetivo de vencimento.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
|
||||
<form.Field
|
||||
name="refValor"
|
||||
validators={{
|
||||
onChange: ({ value }) =>
|
||||
form.getFieldValue("tipo") === "cargo_comissionado" && !value
|
||||
? "Obrigatório"
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="refValor">
|
||||
<span class="label-text font-medium"
|
||||
>Valor de Referência <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<input
|
||||
{name}
|
||||
value={state.value}
|
||||
placeholder="Ex.: 1000,00"
|
||||
class="input input-bordered w-full"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const formatted = formatCurrencyBR(target.value);
|
||||
target.value = formatted;
|
||||
handleChange(formatted);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
/>
|
||||
<div class="label">
|
||||
<span class="label-text-alt opacity-60"
|
||||
>Valor base de referência.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
</div>
|
||||
{#if getTotalPreview()}
|
||||
<div class="alert bg-base-200">
|
||||
<span>Total previsto: R$ {getTotalPreview()}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<form.Field
|
||||
name="valor"
|
||||
validators={{
|
||||
onChange: ({ value }) =>
|
||||
form.getFieldValue("tipo") === "funcao_gratificada" && !value
|
||||
? "Obrigatório"
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
{#snippet children({ name, state, handleChange })}
|
||||
<div class="form-control">
|
||||
<label class="label" for="valor">
|
||||
<span class="label-text font-medium"
|
||||
>Valor <span class="text-error">*</span></span
|
||||
>
|
||||
</label>
|
||||
<input
|
||||
{name}
|
||||
value={state.value}
|
||||
placeholder="Ex.: 1.500,00"
|
||||
class="input input-bordered w-full"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
oninput={(e) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const formatted = formatCurrencyBR(target.value);
|
||||
target.value = formatted;
|
||||
handleChange(formatted);
|
||||
}}
|
||||
required
|
||||
aria-required="true"
|
||||
/>
|
||||
<div class="label">
|
||||
<span class="label-text-alt opacity-60"
|
||||
>Informe o valor da função gratificada.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Field>
|
||||
{/if}
|
||||
|
||||
<form.Subscribe
|
||||
selector={(state) => ({
|
||||
canSubmit: state.canSubmit,
|
||||
isSubmitting: state.isSubmitting,
|
||||
})}
|
||||
>
|
||||
{#snippet children({ canSubmit, isSubmitting })}
|
||||
<div class="card-actions justify-end pt-2">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost"
|
||||
disabled={isSubmitting}
|
||||
onclick={() => goto("/recursos-humanos/simbolos")}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary"
|
||||
class:loading={isSubmitting}
|
||||
disabled={isSubmitting || !canSubmit}
|
||||
>
|
||||
<Save class="h-5 w-5" />
|
||||
<span>Salvar Alterações</span>
|
||||
</button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</form.Subscribe>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{/if}
|
||||
|
||||
@@ -3,11 +3,46 @@ import { query, mutation } from "./_generated/server";
|
||||
import { simboloTipo } from "./schema";
|
||||
|
||||
export const getAll = query({
|
||||
args: {},
|
||||
returns: v.array(
|
||||
v.object({
|
||||
_id: v.id("simbolos"),
|
||||
_creationTime: v.number(),
|
||||
nome: v.string(),
|
||||
tipo: simboloTipo,
|
||||
descricao: v.string(),
|
||||
vencValor: v.string(),
|
||||
repValor: v.string(),
|
||||
valor: v.string(),
|
||||
})
|
||||
),
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("simbolos").collect();
|
||||
},
|
||||
});
|
||||
|
||||
export const getById = query({
|
||||
args: {
|
||||
id: v.id("simbolos"),
|
||||
},
|
||||
returns: v.union(
|
||||
v.object({
|
||||
_id: v.id("simbolos"),
|
||||
_creationTime: v.number(),
|
||||
nome: v.string(),
|
||||
tipo: simboloTipo,
|
||||
descricao: v.string(),
|
||||
vencValor: v.string(),
|
||||
repValor: v.string(),
|
||||
valor: v.string(),
|
||||
}),
|
||||
v.null()
|
||||
),
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.get(args.id);
|
||||
},
|
||||
});
|
||||
|
||||
export const create = mutation({
|
||||
args: {
|
||||
nome: v.string(),
|
||||
@@ -48,3 +83,58 @@ export const create = mutation({
|
||||
return await ctx.db.get(novoSimboloId);
|
||||
},
|
||||
});
|
||||
|
||||
export const remove = mutation({
|
||||
args: {
|
||||
id: v.id("simbolos"),
|
||||
},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
await ctx.db.delete(args.id);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
export const update = mutation({
|
||||
args: {
|
||||
id: v.id("simbolos"),
|
||||
nome: v.string(),
|
||||
tipo: simboloTipo,
|
||||
refValor: v.string(),
|
||||
vencValor: v.string(),
|
||||
descricao: v.string(),
|
||||
valor: v.optional(v.string()),
|
||||
},
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
let refValor = args.refValor;
|
||||
let vencValor = args.vencValor;
|
||||
let valor = args.valor ?? "";
|
||||
|
||||
if (args.tipo === "cargo_comissionado") {
|
||||
if (!refValor || !vencValor) {
|
||||
throw new Error(
|
||||
"Valor de referência e valor de vencimento são obrigatórios para cargo comissionado"
|
||||
);
|
||||
}
|
||||
valor = (Number(refValor) + Number(vencValor)).toFixed(2);
|
||||
} else {
|
||||
if (!args.valor) {
|
||||
throw new Error("Valor é obrigatório para função gratificada");
|
||||
}
|
||||
refValor = "";
|
||||
vencValor = "";
|
||||
valor = args.valor;
|
||||
}
|
||||
|
||||
await ctx.db.patch(args.id, {
|
||||
nome: args.nome,
|
||||
descricao: args.descricao,
|
||||
repValor: refValor,
|
||||
vencValor: vencValor,
|
||||
tipo: args.tipo,
|
||||
valor,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user