🎉 init: 小龙的工作空间
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
.env
|
||||
*.db
|
||||
*.db-journal
|
||||
*.db-wal
|
||||
@@ -0,0 +1,118 @@
|
||||
# MyProject — Backend API
|
||||
|
||||
> 一款根据用户需求定制的应用。
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Runtime**: Node.js
|
||||
- **Framework**: Fastify 5
|
||||
- **Language**: TypeScript
|
||||
- **Database**: SQLite (better-sqlite3)
|
||||
- **Auth**: JWT + bcrypt
|
||||
|
||||
## Getting Started
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Development (hot reload)
|
||||
npm run dev
|
||||
|
||||
# Build
|
||||
npm run build
|
||||
|
||||
# Production start
|
||||
npm run start
|
||||
|
||||
# Run tests
|
||||
npm test
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── index.ts # Server entry point
|
||||
├── db/
|
||||
│ ├── schema.ts # SQLite schema
|
||||
│ └── client.ts # Database client
|
||||
├── routes/
|
||||
│ ├── auth.ts # Auth routes (register/login/me)
|
||||
│ └── *.ts # CRUD routes
|
||||
├── services/
|
||||
│ └── *.ts # Business logic
|
||||
├── middleware/
|
||||
│ └── auth.ts # JWT middleware
|
||||
├── types/
|
||||
│ └── index.ts # TypeScript types
|
||||
└── __tests__/
|
||||
└── *.test.ts # Tests
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Auth
|
||||
- `POST /api/auth/register` — Register
|
||||
- `POST /api/auth/login` — Login
|
||||
- `GET /api/auth/me` — Current user (auth required)
|
||||
|
||||
### Resources
|
||||
#### contracts
|
||||
- `GET /api/contracts` — List all
|
||||
- `GET /api/contracts/:id` — Get by ID
|
||||
- `POST /api/contracts` — Create
|
||||
- `PUT /api/contracts/:id` — Update
|
||||
- `DELETE /api/contracts/:id` — Delete
|
||||
|
||||
#### approvals
|
||||
- `GET /api/approvals` — List all
|
||||
- `GET /api/approvals/:id` — Get by ID
|
||||
- `POST /api/approvals` — Create
|
||||
- `PUT /api/approvals/:id` — Update
|
||||
- `DELETE /api/approvals/:id` — Delete
|
||||
|
||||
#### customers
|
||||
- `GET /api/customers` — List all
|
||||
- `GET /api/customers/:id` — Get by ID
|
||||
- `POST /api/customers` — Create
|
||||
- `PUT /api/customers/:id` — Update
|
||||
- `DELETE /api/customers/:id` — Delete
|
||||
|
||||
#### reminders
|
||||
- `GET /api/reminders` — List all
|
||||
- `GET /api/reminders/:id` — Get by ID
|
||||
- `POST /api/reminders` — Create
|
||||
- `PUT /api/reminders/:id` — Update
|
||||
- `DELETE /api/reminders/:id` — Delete
|
||||
|
||||
#### services
|
||||
- `GET /api/services` — List all
|
||||
- `GET /api/services/:id` — Get by ID
|
||||
- `POST /api/services` — Create
|
||||
- `PUT /api/services/:id` — Update
|
||||
- `DELETE /api/services/:id` — Delete
|
||||
|
||||
#### appointments
|
||||
- `GET /api/appointments` — List all
|
||||
- `GET /api/appointments/:id` — Get by ID
|
||||
- `POST /api/appointments` — Create
|
||||
- `PUT /api/appointments/:id` — Update
|
||||
- `DELETE /api/appointments/:id` — Delete
|
||||
|
||||
#### clients
|
||||
- `GET /api/clients` — List all
|
||||
- `GET /api/clients/:id` — Get by ID
|
||||
- `POST /api/clients` — Create
|
||||
- `PUT /api/clients/:id` — Update
|
||||
- `DELETE /api/clients/:id` — Delete
|
||||
|
||||
#### stats
|
||||
- `GET /api/stats` — List all
|
||||
- `GET /api/stats/:id` — Get by ID
|
||||
- `POST /api/stats` — Create
|
||||
- `PUT /api/stats/:id` — Update
|
||||
- `DELETE /api/stats/:id` — Delete
|
||||
|
||||
### System
|
||||
- `GET /api/health` — Health check
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "myproject",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"test": "node --import tsx --test src/__tests__/*.test.ts",
|
||||
"test:watch": "node --import tsx --test --watch src/__tests__/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.0.0",
|
||||
"@fastify/cors": "^10.0.0",
|
||||
"@fastify/jwt": "^9.0.0",
|
||||
"sql.js": "^1.12.0",
|
||||
"bcrypt": "^5.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"typescript": "^5.6.0",
|
||||
"tsx": "^4.0.0",
|
||||
"pino-pretty": "^11.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Appointments CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"clientId": "sample-clientid",
|
||||
"serviceId": "sample-serviceid",
|
||||
"startTime": "sample-starttime",
|
||||
"endTime": "sample-endtime",
|
||||
"notes": "sample-notes"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/appointments", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/appointments",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/appointments", () => {
|
||||
it("creates a appointment", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/appointments",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/appointments/:id", () => {
|
||||
it("returns the created appointment", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/appointments/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/appointments/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/appointments/:id", () => {
|
||||
it("updates the appointment", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/appointments/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/appointments/:id", () => {
|
||||
it("deletes the appointment", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/appointments/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/appointments/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
// Approval CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"entityType": "sample-entitytype",
|
||||
"entityId": "sample-entityid",
|
||||
"applicantId": regRes.json().user.id,
|
||||
"status": "sample-status",
|
||||
"formData": "sample-formdata"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/approvals", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/approvals",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/approvals", () => {
|
||||
it("creates a approval", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/approvals",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/approvals/:id", () => {
|
||||
it("returns the created approval", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/approvals/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/approvals/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/approvals/:id", () => {
|
||||
it("updates the approval", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/approvals/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/approvals/:id", () => {
|
||||
it("deletes the approval", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/approvals/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/approvals/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// Auth routes test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/register", () => {
|
||||
it("registers a new user", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: "testuser", password: "password123" },
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.token);
|
||||
assert.equal(body.user.username, "testuser");
|
||||
token = body.token;
|
||||
});
|
||||
|
||||
it("rejects duplicate username", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: "testuser", password: "password123" },
|
||||
});
|
||||
assert.equal(res.statusCode, 409);
|
||||
});
|
||||
|
||||
it("rejects short password", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: "user2", password: "123" },
|
||||
});
|
||||
assert.equal(res.statusCode, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/login", () => {
|
||||
it("logs in with correct credentials", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "testuser", password: "password123" },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(body.token);
|
||||
token = body.token;
|
||||
});
|
||||
|
||||
it("rejects wrong password", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "testuser", password: "wrongpassword" },
|
||||
});
|
||||
assert.equal(res.statusCode, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/auth/me", () => {
|
||||
it("returns current user with valid token", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/me",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.username, "testuser");
|
||||
});
|
||||
|
||||
it("rejects without token", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/auth/me",
|
||||
});
|
||||
assert.equal(res.statusCode, 401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
// Clients CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"title": "sample-title",
|
||||
"description": "sample-description",
|
||||
"data": "sample-data"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/clients", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/clients",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/clients", () => {
|
||||
it("creates a client", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/clients",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/clients/:id", () => {
|
||||
it("returns the created client", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/clients/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/clients/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/clients/:id", () => {
|
||||
it("updates the client", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/clients/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/clients/:id", () => {
|
||||
it("deletes the client", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/clients/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/clients/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
// Contract CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"title": "sample-title",
|
||||
"partyA": "sample-partya",
|
||||
"partyB": "sample-partyb",
|
||||
"amount": 1,
|
||||
"signedAt": "sample-signedat",
|
||||
"expiresAt": "sample-expiresat",
|
||||
"status": "sample-status",
|
||||
"fileUrl": "sample-fileurl"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/contracts", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/contracts",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/contracts", () => {
|
||||
it("creates a contract", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/contracts",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/contracts/:id", () => {
|
||||
it("returns the created contract", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/contracts/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/contracts/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/contracts/:id", () => {
|
||||
it("updates the contract", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/contracts/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/contracts/:id", () => {
|
||||
it("deletes the contract", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/contracts/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/contracts/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
// Customer CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"name": "sample-name",
|
||||
"email": "sample-email",
|
||||
"phone": "sample-phone",
|
||||
"company": "sample-company",
|
||||
"source": "sample-source",
|
||||
"tags": "sample-tags"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/customers", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/customers",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/customers", () => {
|
||||
it("creates a customer", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/customers",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/customers/:id", () => {
|
||||
it("returns the created customer", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/customers/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/customers/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/customers/:id", () => {
|
||||
it("updates the customer", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/customers/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/customers/:id", () => {
|
||||
it("deletes the customer", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/customers/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/customers/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// Item CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/items", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/items",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/items", () => {
|
||||
it("creates a item", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/items",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
"userId": "00000000-0000-0000-0000-000000000001",
|
||||
"title": "sample-title",
|
||||
"data": "sample-data"
|
||||
},
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/items/:id", () => {
|
||||
it("returns the created item", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/items/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/items/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/items/:id", () => {
|
||||
it("updates the item", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/items/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
"userId": "00000000-0000-0000-0000-000000000001",
|
||||
"title": "sample-title",
|
||||
"data": "sample-data"
|
||||
},
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/items/:id", () => {
|
||||
it("deletes the item", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/items/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/items/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
// Reminder CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"entityType": "sample-entitytype",
|
||||
"entityId": "sample-entityid",
|
||||
"remindAt": "sample-remindat",
|
||||
"message": "sample-message",
|
||||
"sent": true
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/reminders", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/reminders",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/reminders", () => {
|
||||
it("creates a reminder", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/reminders",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/reminders/:id", () => {
|
||||
it("returns the created reminder", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/reminders/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/reminders/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/reminders/:id", () => {
|
||||
it("updates the reminder", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/reminders/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/reminders/:id", () => {
|
||||
it("deletes the reminder", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/reminders/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/reminders/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
// Services CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"name": "sample-name",
|
||||
"description": "sample-description",
|
||||
"durationMin": 1,
|
||||
"price": 1
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/services", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/services",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/services", () => {
|
||||
it("creates a service", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/services",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/services/:id", () => {
|
||||
it("returns the created service", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/services/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/services/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/services/:id", () => {
|
||||
it("updates the service", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/services/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/services/:id", () => {
|
||||
it("deletes the service", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/services/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/services/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
// Stats CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
let payload: Record<string, unknown>;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
|
||||
// Resolve user FK references with the registered user's real ID
|
||||
payload = {
|
||||
"userId": regRes.json().user.id,
|
||||
"clientId": "sample-clientid",
|
||||
"serviceId": "sample-serviceid",
|
||||
"startTime": "sample-starttime",
|
||||
"endTime": "sample-endtime",
|
||||
"notes": "sample-notes"
|
||||
};
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/stats", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/stats",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/stats", () => {
|
||||
it("creates a stat", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/stats",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/stats/:id", () => {
|
||||
it("returns the created stat", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/stats/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/stats/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/stats/:id", () => {
|
||||
it("updates the stat", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/stats/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/stats/:id", () => {
|
||||
it("deletes the stat", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/stats/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/stats/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// User CRUD test
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildApp } from "../index.js";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
let app: FastifyInstance;
|
||||
let token: string;
|
||||
let createdId: string;
|
||||
|
||||
before(async () => {
|
||||
process.env.JWT_SECRET = "test-secret";
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Register and login to get a token
|
||||
const regRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
payload: { username: `test_${Date.now()}`, password: "password123" },
|
||||
});
|
||||
token = regRes.json().token;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/users", () => {
|
||||
it("returns empty list", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/users",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.ok(Array.isArray(body.data));
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/users", () => {
|
||||
it("creates a user", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/users",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
"phone": "sample-phone",
|
||||
"nickname": "sample-nickname",
|
||||
"avatarUrl": "sample-avatarurl"
|
||||
},
|
||||
});
|
||||
assert.equal(res.statusCode, 201);
|
||||
const body = res.json();
|
||||
assert.ok(body.data.id);
|
||||
createdId = body.data.id;
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/users/:id", () => {
|
||||
it("returns the created user", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/users/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
const body = res.json();
|
||||
assert.equal(body.data.id, createdId);
|
||||
});
|
||||
|
||||
it("returns 404 for nonexistent id", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/users/nonexistent`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/users/:id", () => {
|
||||
it("updates the user", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/users/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
"phone": "sample-phone",
|
||||
"nickname": "sample-nickname",
|
||||
"avatarUrl": "sample-avatarurl"
|
||||
},
|
||||
});
|
||||
assert.equal(res.statusCode, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/users/:id", () => {
|
||||
it("deletes the user", async () => {
|
||||
const res = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/users/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 204);
|
||||
});
|
||||
|
||||
it("returns 404 after delete", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/users/${createdId}`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(res.statusCode, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
// SQLite database client (sql.js — pure WASM, no native deps)
|
||||
import initSqlJs, { type Database, type BindParams } from "sql.js";
|
||||
import { createTables } from "./schema.js";
|
||||
|
||||
let db: Database | null = null;
|
||||
let initPromise: Promise<Database> | null = null;
|
||||
|
||||
/** Initialize the database (call once at startup). */
|
||||
export async function initDb(dbPath?: string): Promise<Database> {
|
||||
if (db) return db;
|
||||
if (initPromise) return initPromise;
|
||||
|
||||
initPromise = (async () => {
|
||||
const SQL = await initSqlJs();
|
||||
const path = dbPath || process.env.DATABASE_URL || ":memory:";
|
||||
|
||||
// Try to load existing database from file
|
||||
let buffer: ArrayLike<number> | undefined;
|
||||
if (path !== ":memory:") {
|
||||
try {
|
||||
const fs = await import("node:fs/promises");
|
||||
const data = await fs.readFile(path);
|
||||
buffer = new Uint8Array(data);
|
||||
} catch {
|
||||
// File doesn't exist yet — start fresh
|
||||
}
|
||||
}
|
||||
|
||||
db = new SQL.Database(buffer);
|
||||
db.run("PRAGMA foreign_keys = ON");
|
||||
createTables(db);
|
||||
return db;
|
||||
})();
|
||||
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
/** Get the initialized database (must call initDb first). */
|
||||
export function getDb(): Database {
|
||||
if (!db) throw new Error("Database not initialized. Call initDb() first.");
|
||||
return db;
|
||||
}
|
||||
|
||||
/** Save database to disk. */
|
||||
export async function saveDb(dbPath?: string): Promise<void> {
|
||||
if (!db) return;
|
||||
const path = dbPath || process.env.DATABASE_URL || "./data/app.db";
|
||||
if (path === ":memory:") return;
|
||||
const fs = await import("node:fs/promises");
|
||||
const { dirname } = await import("node:path");
|
||||
await fs.mkdir(dirname(path), { recursive: true });
|
||||
const data = db.export();
|
||||
await fs.writeFile(path, Buffer.from(data));
|
||||
}
|
||||
|
||||
export async function closeDb(): Promise<void> {
|
||||
if (db) {
|
||||
await saveDb();
|
||||
db.close();
|
||||
db = null;
|
||||
initPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: run a query and return all rows as objects
|
||||
export function queryAll<T = Record<string, unknown>>(sql: string, params: BindParams = []): T[] {
|
||||
const d = getDb();
|
||||
const stmt = d.prepare(sql);
|
||||
if (params) stmt.bind(params);
|
||||
const results: T[] = [];
|
||||
while (stmt.step()) {
|
||||
const row = stmt.getAsObject();
|
||||
results.push(row as unknown as T);
|
||||
}
|
||||
stmt.free();
|
||||
return results;
|
||||
}
|
||||
|
||||
// Helper: run a query and return the first row
|
||||
export function queryOne<T = Record<string, unknown>>(sql: string, params: BindParams = []): T | undefined {
|
||||
const rows = queryAll<T>(sql, params);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
// Helper: run a mutation and return { changes, lastInsertRowid }
|
||||
export function execute(sql: string, params: BindParams = []): { changes: number; lastInsertRowid: number } {
|
||||
const d = getDb();
|
||||
d.run(sql, params);
|
||||
return {
|
||||
changes: d.getRowsModified(),
|
||||
lastInsertRowid: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Auto-generated SQLite schema
|
||||
import type { Database } from "sql.js";
|
||||
|
||||
export function createTables(db: Database): void {
|
||||
const statements = [
|
||||
"CREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n username TEXT NOT NULL UNIQUE,\n password_hash TEXT NOT NULL,\n nickname TEXT,\n role TEXT DEFAULT 'user',\n phone TEXT,\n avatar_url TEXT,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS contracts (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL REFERENCES users(id),\n title TEXT NOT NULL,\n party_a TEXT,\n party_b TEXT,\n amount REAL,\n signed_at TEXT,\n expires_at TEXT,\n status TEXT DEFAULT 'draft',\n file_url TEXT,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS approvals (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL REFERENCES users(id),\n entity_type TEXT NOT NULL,\n entity_id TEXT,\n applicant_id TEXT NOT NULL REFERENCES users(id),\n status TEXT DEFAULT 'pending',\n form_data TEXT,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS customers (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL REFERENCES users(id),\n name TEXT NOT NULL,\n email TEXT,\n phone TEXT,\n company TEXT,\n source TEXT,\n tags TEXT DEFAULT '[]',\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS reminders (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL REFERENCES users(id),\n entity_type TEXT NOT NULL,\n entity_id TEXT,\n remind_at TEXT NOT NULL,\n message TEXT,\n sent INTEGER DEFAULT 'false',\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS services (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT REFERENCES users(id),\n name TEXT NOT NULL,\n description TEXT,\n duration_min INTEGER,\n price REAL,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS appointments (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT REFERENCES users(id),\n client_id TEXT REFERENCES clients(id),\n service_id TEXT REFERENCES services(id),\n start_time TEXT NOT NULL,\n end_time TEXT,\n status TEXT,\n notes TEXT,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS clients (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT REFERENCES users(id),\n title TEXT NOT NULL,\n description TEXT,\n status TEXT,\n data TEXT,\n created_at TEXT,\n updated_at TEXT\n);",
|
||||
"CREATE TABLE IF NOT EXISTS stats (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT REFERENCES users(id),\n client_id TEXT REFERENCES clients(id),\n service_id TEXT REFERENCES services(id),\n start_time TEXT NOT NULL,\n end_time TEXT,\n status TEXT,\n notes TEXT,\n created_at TEXT,\n updated_at TEXT\n);"
|
||||
];
|
||||
for (const sql of statements) {
|
||||
const trimmed = sql.trim();
|
||||
if (trimmed) db.run(trimmed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// MyProject — Fastify Backend Server
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import fjwt from "@fastify/jwt";
|
||||
import { initDb, closeDb } from "./db/client.js";
|
||||
import { authRoutes } from "./routes/auth.js";
|
||||
import { contractsRoutes } from "./routes/contracts.js";
|
||||
import { approvalsRoutes } from "./routes/approvals.js";
|
||||
import { customersRoutes } from "./routes/customers.js";
|
||||
import { remindersRoutes } from "./routes/reminders.js";
|
||||
import { servicesRoutes } from "./routes/services.js";
|
||||
import { appointmentsRoutes } from "./routes/appointments.js";
|
||||
import { clientsRoutes } from "./routes/clients.js";
|
||||
import { statsRoutes } from "./routes/stats.js";
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || "change-me-in-production-2d3e1114";
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
level: process.env.LOG_LEVEL || "info",
|
||||
transport: process.env.NODE_ENV !== "production"
|
||||
? { target: "pino-pretty", options: { colorize: true } }
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// Init database
|
||||
await initDb();
|
||||
|
||||
// Plugins
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN || "*",
|
||||
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
|
||||
});
|
||||
|
||||
await app.register(fjwt, { secret: JWT_SECRET });
|
||||
|
||||
// Routes
|
||||
await app.register(authRoutes, { prefix: "/api/auth" });
|
||||
await app.register(contractsRoutes, { prefix: "/api/contracts" });
|
||||
await app.register(approvalsRoutes, { prefix: "/api/approvals" });
|
||||
await app.register(customersRoutes, { prefix: "/api/customers" });
|
||||
await app.register(remindersRoutes, { prefix: "/api/reminders" });
|
||||
await app.register(servicesRoutes, { prefix: "/api/services" });
|
||||
await app.register(appointmentsRoutes, { prefix: "/api/appointments" });
|
||||
await app.register(clientsRoutes, { prefix: "/api/clients" });
|
||||
await app.register(statsRoutes, { prefix: "/api/stats" });
|
||||
|
||||
// Health check
|
||||
app.get("/api/health", async () => ({ status: "ok", timestamp: new Date().toISOString() }));
|
||||
|
||||
// Graceful shutdown
|
||||
app.addHook("onClose", async () => {
|
||||
closeDb();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
// Start server if called directly (not when imported by tests)
|
||||
const port = parseInt(process.env.PORT || "3001", 10);
|
||||
const host = process.env.HOST || "0.0.0.0";
|
||||
|
||||
async function main() {
|
||||
const app = await buildApp();
|
||||
try {
|
||||
await app.listen({ port, host });
|
||||
} catch (err) {
|
||||
app.log.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Guard: only run when executed directly, not when imported
|
||||
const isMain = process.argv[1] && (import.meta.url === `file://${process.argv[1]}` || import.meta.url.endsWith(process.argv[1]) || process.argv[1].endsWith("/src/index.ts") || process.argv[1].endsWith("/src/index.js"));
|
||||
if (isMain) {
|
||||
main();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// JWT Authentication Middleware
|
||||
import type { FastifyRequest, FastifyReply } from "fastify";
|
||||
import type { JwtPayload } from "../types/index.js";
|
||||
|
||||
/**
|
||||
* Verify JWT token and attach user to request.
|
||||
*/
|
||||
export async function authenticate(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch (err) {
|
||||
reply.status(401).send({ error: "Unauthorized", message: "Invalid or expired token", statusCode: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Helper to get typed user from request (after authenticate). */
|
||||
export function getUser(request: FastifyRequest): JwtPayload {
|
||||
return request.user as unknown as JwtPayload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Require admin role.
|
||||
* Must be used after authenticate.
|
||||
*/
|
||||
export async function requireAdmin(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const user = request.user as unknown as JwtPayload | undefined;
|
||||
if (!user || user.role !== "admin") {
|
||||
reply.status(403).send({ error: "Forbidden", message: "Admin access required", statusCode: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional auth: attach user if token present, but don't fail if missing.
|
||||
*/
|
||||
export async function optionalAuth(request: FastifyRequest): Promise<void> {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
// No token or invalid — continue without user
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Appointments routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { AppointmentsService } from "../services/appointment.js";
|
||||
import type { CreateAppointmentsInput, UpdateAppointmentsInput } from "../types/index.js";
|
||||
|
||||
const service = new AppointmentsService();
|
||||
|
||||
export async function appointmentsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/appointments — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/appointments/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Appointments not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/appointments — create
|
||||
app.post<{ Body: CreateAppointmentsInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/appointments/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateAppointmentsInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Appointments not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/appointments/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Appointments not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Approval routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ApprovalService } from "../services/approval.js";
|
||||
import type { CreateApprovalInput, UpdateApprovalInput } from "../types/index.js";
|
||||
|
||||
const service = new ApprovalService();
|
||||
|
||||
export async function approvalsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/approvals — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/approvals/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Approval not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/approvals — create
|
||||
app.post<{ Body: CreateApprovalInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/approvals/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateApprovalInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Approval not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/approvals/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Approval not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Authentication routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import bcrypt from "bcrypt";
|
||||
import { queryOne, execute } from "../db/client.js";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import type { User, RegisterInput, LoginInput, AuthResponse } from "../types/index.js";
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
// POST /api/auth/register
|
||||
app.post<{ Body: RegisterInput }>("/register", async (request, reply) => {
|
||||
const { username, password, nickname } = request.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return reply.status(400).send({
|
||||
error: "Bad Request",
|
||||
message: "Username and password are required",
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return reply.status(400).send({
|
||||
error: "Bad Request",
|
||||
message: "Password must be at least 6 characters",
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const existing = queryOne("SELECT id FROM users WHERE username = ?", [username]);
|
||||
if (existing) {
|
||||
return reply.status(409).send({
|
||||
error: "Conflict",
|
||||
message: "Username already exists",
|
||||
statusCode: 409,
|
||||
});
|
||||
}
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
|
||||
const now = new Date().toISOString();
|
||||
|
||||
execute(
|
||||
"INSERT INTO users (id, username, password_hash, nickname, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
[id, username, passwordHash, nickname || username, now, now]
|
||||
);
|
||||
|
||||
const user = queryOne<User>(
|
||||
"SELECT id, username, nickname, role, created_at, updated_at FROM users WHERE id = ?",
|
||||
[id]
|
||||
);
|
||||
if (!user) {
|
||||
return reply.status(500).send({ error: "Internal Error", message: "Failed to create user", statusCode: 500 });
|
||||
}
|
||||
|
||||
const token = app.jwt.sign({ userId: id, username, role: user.role });
|
||||
|
||||
return reply.status(201).send({ token, user } satisfies AuthResponse);
|
||||
});
|
||||
|
||||
// POST /api/auth/login
|
||||
app.post<{ Body: LoginInput }>("/login", async (request, reply) => {
|
||||
const { username, password } = request.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return reply.status(400).send({
|
||||
error: "Bad Request",
|
||||
message: "Username and password are required",
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const user = queryOne<User & { password_hash: string }>(
|
||||
"SELECT * FROM users WHERE username = ?",
|
||||
[username]
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
return reply.status(401).send({
|
||||
error: "Unauthorized",
|
||||
message: "Invalid username or password",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(password, user.password_hash);
|
||||
if (!valid) {
|
||||
return reply.status(401).send({
|
||||
error: "Unauthorized",
|
||||
message: "Invalid username or password",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const token = app.jwt.sign({ userId: user.id, username: user.username, role: user.role });
|
||||
|
||||
const { password_hash, ...safeUser } = user;
|
||||
|
||||
return { token, user: safeUser } satisfies AuthResponse;
|
||||
});
|
||||
|
||||
// GET /api/auth/me — current user info
|
||||
app.get("/me", { onRequest: [authenticate] }, async (request, reply) => {
|
||||
const jwtUser = request.user as unknown as { userId: string };
|
||||
const user = queryOne<User>(
|
||||
"SELECT id, username, nickname, role, created_at, updated_at FROM users WHERE id = ?",
|
||||
[jwtUser.userId]
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
return reply.status(404).send({
|
||||
error: "Not Found",
|
||||
message: "User not found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return { data: user };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Clients routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ClientsService } from "../services/client.js";
|
||||
import type { CreateClientsInput, UpdateClientsInput } from "../types/index.js";
|
||||
|
||||
const service = new ClientsService();
|
||||
|
||||
export async function clientsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/clients — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/clients/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Clients not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/clients — create
|
||||
app.post<{ Body: CreateClientsInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/clients/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateClientsInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Clients not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/clients/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Clients not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Contract routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ContractService } from "../services/contract.js";
|
||||
import type { CreateContractInput, UpdateContractInput } from "../types/index.js";
|
||||
|
||||
const service = new ContractService();
|
||||
|
||||
export async function contractsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/contracts — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/contracts/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Contract not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/contracts — create
|
||||
app.post<{ Body: CreateContractInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/contracts/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateContractInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Contract not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/contracts/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Contract not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Customer routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { CustomerService } from "../services/customer.js";
|
||||
import type { CreateCustomerInput, UpdateCustomerInput } from "../types/index.js";
|
||||
|
||||
const service = new CustomerService();
|
||||
|
||||
export async function customersRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/customers — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/customers/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Customer not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/customers — create
|
||||
app.post<{ Body: CreateCustomerInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/customers/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateCustomerInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Customer not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/customers/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Customer not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Item routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ItemService } from "../services/item.js";
|
||||
import type { CreateItemInput, UpdateItemInput } from "../types/index.js";
|
||||
|
||||
const service = new ItemService();
|
||||
|
||||
export async function itemsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/items — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/items/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Item not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/items — create
|
||||
app.post<{ Body: CreateItemInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/items/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateItemInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Item not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/items/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Item not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Reminder routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ReminderService } from "../services/reminder.js";
|
||||
import type { CreateReminderInput, UpdateReminderInput } from "../types/index.js";
|
||||
|
||||
const service = new ReminderService();
|
||||
|
||||
export async function remindersRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/reminders — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/reminders/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Reminder not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/reminders — create
|
||||
app.post<{ Body: CreateReminderInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/reminders/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateReminderInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Reminder not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/reminders/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Reminder not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Services routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { ServicesService } from "../services/service.js";
|
||||
import type { CreateServicesInput, UpdateServicesInput } from "../types/index.js";
|
||||
|
||||
const service = new ServicesService();
|
||||
|
||||
export async function servicesRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/services — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/services/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Services not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/services — create
|
||||
app.post<{ Body: CreateServicesInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/services/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateServicesInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Services not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/services/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Services not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated Stats routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { StatsService } from "../services/stat.js";
|
||||
import type { CreateStatsInput, UpdateStatsInput } from "../types/index.js";
|
||||
|
||||
const service = new StatsService();
|
||||
|
||||
export async function statsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/stats — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/stats/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Stats not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/stats — create
|
||||
app.post<{ Body: CreateStatsInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/stats/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateStatsInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Stats not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/stats/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "Stats not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Auto-generated User routes
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { authenticate } from "../middleware/auth.js";
|
||||
import { UserService } from "../services/user.js";
|
||||
import type { CreateUserInput, UpdateUserInput } from "../types/index.js";
|
||||
|
||||
const service = new UserService();
|
||||
|
||||
export async function usersRoutes(app: FastifyInstance): Promise<void> {
|
||||
// All routes require authentication
|
||||
app.addHook("onRequest", authenticate);
|
||||
|
||||
// GET /api/users — list
|
||||
app.get("/", async (request, reply) => {
|
||||
const items = service.list();
|
||||
return { data: items };
|
||||
});
|
||||
|
||||
// GET /api/users/:id — get by id
|
||||
app.get<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const item = service.getById(request.params.id);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// POST /api/users — create
|
||||
app.post<{ Body: CreateUserInput }>("/", async (request, reply) => {
|
||||
const item = service.create(request.body);
|
||||
return reply.status(201).send({ data: item });
|
||||
});
|
||||
|
||||
// PUT /api/users/:id — update
|
||||
app.put<{ Params: { id: string }; Body: UpdateUserInput }>("/:id", async (request, reply) => {
|
||||
const item = service.update(request.params.id, request.body);
|
||||
if (!item) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
|
||||
}
|
||||
return { data: item };
|
||||
});
|
||||
|
||||
// DELETE /api/users/:id — delete
|
||||
app.delete<{ Params: { id: string } }>("/:id", async (request, reply) => {
|
||||
const deleted = service.delete(request.params.id);
|
||||
if (!deleted) {
|
||||
return reply.status(404).send({ error: "Not Found", message: "User not found", statusCode: 404 });
|
||||
}
|
||||
return reply.status(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Auto-generated Appointments service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Appointments, CreateAppointmentsInput, UpdateAppointmentsInput } from "../types/index.js";
|
||||
|
||||
export class AppointmentsService {
|
||||
/** List all appointments */
|
||||
list(): Appointments[] {
|
||||
return queryAll<Appointments>("SELECT * FROM appointments ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Appointments | undefined {
|
||||
return queryOne<Appointments>("SELECT * FROM appointments WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateAppointmentsInput): Appointments {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "client_id", "service_id", "start_time", "end_time", "notes", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.clientId ?? null, input.serviceId ?? null, input.startTime ?? null, input.endTime ?? null, input.notes ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO appointments (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateAppointmentsInput): Appointments | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.clientId !== undefined) { sets.push("client_id = ?"); values.push(input.clientId); }
|
||||
if (input.serviceId !== undefined) { sets.push("service_id = ?"); values.push(input.serviceId); }
|
||||
if (input.startTime !== undefined) { sets.push("start_time = ?"); values.push(input.startTime); }
|
||||
if (input.endTime !== undefined) { sets.push("end_time = ?"); values.push(input.endTime); }
|
||||
if (input.notes !== undefined) { sets.push("notes = ?"); values.push(input.notes); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE appointments SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM appointments WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Auto-generated Approval service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Approval, CreateApprovalInput, UpdateApprovalInput } from "../types/index.js";
|
||||
|
||||
export class ApprovalService {
|
||||
/** List all approvals */
|
||||
list(): Approval[] {
|
||||
return queryAll<Approval>("SELECT * FROM approvals ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Approval | undefined {
|
||||
return queryOne<Approval>("SELECT * FROM approvals WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateApprovalInput): Approval {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "entity_type", "entity_id", "applicant_id", "status", "form_data", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.entityType ?? null, input.entityId ?? null, input.applicantId ?? null, input.status ?? null, input.formData ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO approvals (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateApprovalInput): Approval | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.entityType !== undefined) { sets.push("entity_type = ?"); values.push(input.entityType); }
|
||||
if (input.entityId !== undefined) { sets.push("entity_id = ?"); values.push(input.entityId); }
|
||||
if (input.applicantId !== undefined) { sets.push("applicant_id = ?"); values.push(input.applicantId); }
|
||||
if (input.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
|
||||
if (input.formData !== undefined) { sets.push("form_data = ?"); values.push(input.formData); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE approvals SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM approvals WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Auto-generated Clients service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Clients, CreateClientsInput, UpdateClientsInput } from "../types/index.js";
|
||||
|
||||
export class ClientsService {
|
||||
/** List all clients */
|
||||
list(): Clients[] {
|
||||
return queryAll<Clients>("SELECT * FROM clients ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Clients | undefined {
|
||||
return queryOne<Clients>("SELECT * FROM clients WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateClientsInput): Clients {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "title", "description", "data", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.title ?? null, input.description ?? null, input.data ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO clients (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateClientsInput): Clients | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
|
||||
if (input.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
|
||||
if (input.data !== undefined) { sets.push("data = ?"); values.push(input.data); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE clients SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM clients WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Auto-generated Contract service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Contract, CreateContractInput, UpdateContractInput } from "../types/index.js";
|
||||
|
||||
export class ContractService {
|
||||
/** List all contracts */
|
||||
list(): Contract[] {
|
||||
return queryAll<Contract>("SELECT * FROM contracts ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Contract | undefined {
|
||||
return queryOne<Contract>("SELECT * FROM contracts WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateContractInput): Contract {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "title", "party_a", "party_b", "amount", "signed_at", "expires_at", "status", "file_url", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.title ?? null, input.partyA ?? null, input.partyB ?? null, input.amount ?? null, input.signedAt ?? null, input.expiresAt ?? null, input.status ?? null, input.fileUrl ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO contracts (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateContractInput): Contract | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
|
||||
if (input.partyA !== undefined) { sets.push("party_a = ?"); values.push(input.partyA); }
|
||||
if (input.partyB !== undefined) { sets.push("party_b = ?"); values.push(input.partyB); }
|
||||
if (input.amount !== undefined) { sets.push("amount = ?"); values.push(input.amount); }
|
||||
if (input.signedAt !== undefined) { sets.push("signed_at = ?"); values.push(input.signedAt); }
|
||||
if (input.expiresAt !== undefined) { sets.push("expires_at = ?"); values.push(input.expiresAt); }
|
||||
if (input.status !== undefined) { sets.push("status = ?"); values.push(input.status); }
|
||||
if (input.fileUrl !== undefined) { sets.push("file_url = ?"); values.push(input.fileUrl); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE contracts SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM contracts WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Auto-generated Customer service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Customer, CreateCustomerInput, UpdateCustomerInput } from "../types/index.js";
|
||||
|
||||
export class CustomerService {
|
||||
/** List all customers */
|
||||
list(): Customer[] {
|
||||
return queryAll<Customer>("SELECT * FROM customers ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Customer | undefined {
|
||||
return queryOne<Customer>("SELECT * FROM customers WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateCustomerInput): Customer {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "name", "email", "phone", "company", "source", "tags", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.name ?? null, input.email ?? null, input.phone ?? null, input.company ?? null, input.source ?? null, input.tags ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO customers (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateCustomerInput): Customer | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
|
||||
if (input.email !== undefined) { sets.push("email = ?"); values.push(input.email); }
|
||||
if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
|
||||
if (input.company !== undefined) { sets.push("company = ?"); values.push(input.company); }
|
||||
if (input.source !== undefined) { sets.push("source = ?"); values.push(input.source); }
|
||||
if (input.tags !== undefined) { sets.push("tags = ?"); values.push(input.tags); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE customers SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM customers WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Auto-generated Item service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Item, CreateItemInput, UpdateItemInput } from "../types/index.js";
|
||||
|
||||
export class ItemService {
|
||||
/** List all items */
|
||||
list(): Item[] {
|
||||
return queryAll<Item>("SELECT * FROM items ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Item | undefined {
|
||||
return queryOne<Item>("SELECT * FROM items WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateItemInput): Item {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const hasCreatedAt = true;
|
||||
const hasUpdatedAt = false;
|
||||
const cols = ["id", "user_id", "title", "data", "created_at"];
|
||||
const placeholders = cols.map(() => "?").join(", ");
|
||||
const values = [id, input.userId ?? null, input.title ?? null, input.data ?? null, now];
|
||||
|
||||
execute(`INSERT INTO items (${cols.join(", ")}) VALUES (${placeholders})`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateItemInput): Item | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
|
||||
if (input.data !== undefined) { sets.push("data = ?"); values.push(input.data); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE items SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM items WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Auto-generated Reminder service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Reminder, CreateReminderInput, UpdateReminderInput } from "../types/index.js";
|
||||
|
||||
export class ReminderService {
|
||||
/** List all reminders */
|
||||
list(): Reminder[] {
|
||||
return queryAll<Reminder>("SELECT * FROM reminders ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Reminder | undefined {
|
||||
return queryOne<Reminder>("SELECT * FROM reminders WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateReminderInput): Reminder {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "entity_type", "entity_id", "remind_at", "message", "sent", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.entityType ?? null, input.entityId ?? null, input.remindAt ?? null, input.message ?? null, input.sent ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO reminders (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateReminderInput): Reminder | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.entityType !== undefined) { sets.push("entity_type = ?"); values.push(input.entityType); }
|
||||
if (input.entityId !== undefined) { sets.push("entity_id = ?"); values.push(input.entityId); }
|
||||
if (input.remindAt !== undefined) { sets.push("remind_at = ?"); values.push(input.remindAt); }
|
||||
if (input.message !== undefined) { sets.push("message = ?"); values.push(input.message); }
|
||||
if (input.sent !== undefined) { sets.push("sent = ?"); values.push(input.sent); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE reminders SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM reminders WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Auto-generated Services service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Services, CreateServicesInput, UpdateServicesInput } from "../types/index.js";
|
||||
|
||||
export class ServicesService {
|
||||
/** List all services */
|
||||
list(): Services[] {
|
||||
return queryAll<Services>("SELECT * FROM services ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Services | undefined {
|
||||
return queryOne<Services>("SELECT * FROM services WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateServicesInput): Services {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "name", "description", "duration_min", "price", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.name ?? null, input.description ?? null, input.durationMin ?? null, input.price ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO services (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateServicesInput): Services | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
|
||||
if (input.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
|
||||
if (input.durationMin !== undefined) { sets.push("duration_min = ?"); values.push(input.durationMin); }
|
||||
if (input.price !== undefined) { sets.push("price = ?"); values.push(input.price); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE services SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM services WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Auto-generated Stats service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { Stats, CreateStatsInput, UpdateStatsInput } from "../types/index.js";
|
||||
|
||||
export class StatsService {
|
||||
/** List all stats */
|
||||
list(): Stats[] {
|
||||
return queryAll<Stats>("SELECT * FROM stats ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): Stats | undefined {
|
||||
return queryOne<Stats>("SELECT * FROM stats WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateStatsInput): Stats {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const cols = ["id", "user_id", "client_id", "service_id", "start_time", "end_time", "notes", "created_at", "updated_at"];
|
||||
const values = [id, input.userId ?? null, input.clientId ?? null, input.serviceId ?? null, input.startTime ?? null, input.endTime ?? null, input.notes ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO stats (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateStatsInput): Stats | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
|
||||
if (input.clientId !== undefined) { sets.push("client_id = ?"); values.push(input.clientId); }
|
||||
if (input.serviceId !== undefined) { sets.push("service_id = ?"); values.push(input.serviceId); }
|
||||
if (input.startTime !== undefined) { sets.push("start_time = ?"); values.push(input.startTime); }
|
||||
if (input.endTime !== undefined) { sets.push("end_time = ?"); values.push(input.endTime); }
|
||||
if (input.notes !== undefined) { sets.push("notes = ?"); values.push(input.notes); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE stats SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM stats WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Auto-generated User service
|
||||
import { queryAll, queryOne, execute } from "../db/client.js";
|
||||
import type { User, CreateUserInput, UpdateUserInput } from "../types/index.js";
|
||||
|
||||
export class UserService {
|
||||
/** List all users */
|
||||
list(): User[] {
|
||||
return queryAll<User>("SELECT * FROM users ORDER BY created_at DESC");
|
||||
}
|
||||
|
||||
/** Get by ID */
|
||||
getById(id: string): User | undefined {
|
||||
return queryOne<User>("SELECT * FROM users WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
/** Create */
|
||||
create(input: CreateUserInput): User {
|
||||
const id = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const hasCreatedAt = true;
|
||||
const hasUpdatedAt = true;
|
||||
const cols = ["id", "phone", "nickname", "avatar_url", "created_at", "updated_at"];
|
||||
const placeholders = cols.map(() => "?").join(", ");
|
||||
const values = [id, input.phone ?? null, input.nickname ?? null, input.avatarUrl ?? null, now, now];
|
||||
|
||||
execute(`INSERT INTO users (${cols.join(", ")}) VALUES (${placeholders})`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Update */
|
||||
update(id: string, input: UpdateUserInput): User | undefined {
|
||||
const existing = this.getById(id);
|
||||
if (!existing) return undefined;
|
||||
|
||||
const sets: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
|
||||
if (input.nickname !== undefined) { sets.push("nickname = ?"); values.push(input.nickname); }
|
||||
if (input.avatarUrl !== undefined) { sets.push("avatar_url = ?"); values.push(input.avatarUrl); }
|
||||
|
||||
if (sets.length === 0) return existing;
|
||||
|
||||
sets.push("updated_at = ?");
|
||||
values.push(new Date().toISOString());
|
||||
|
||||
values.push(id);
|
||||
execute(`UPDATE users SET ${sets.join(", ")} WHERE id = ?`, values);
|
||||
return this.getById(id)!;
|
||||
}
|
||||
|
||||
/** Delete */
|
||||
delete(id: string): boolean {
|
||||
const result = execute("DELETE FROM users WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Augment Fastify request with JWT user
|
||||
import type { JwtPayload } from "./index.js";
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
user?: JwtPayload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
// Auto-generated types (from Model Contract)
|
||||
|
||||
export interface User {
|
||||
id?: string;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
nickname?: string;
|
||||
role?: string;
|
||||
phone?: string;
|
||||
avatarUrl?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Contract {
|
||||
id?: string;
|
||||
userId: string;
|
||||
title: string;
|
||||
partyA?: string;
|
||||
partyB?: string;
|
||||
amount?: number;
|
||||
signedAt?: string;
|
||||
expiresAt?: string;
|
||||
status?: string;
|
||||
fileUrl?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Approval {
|
||||
id?: string;
|
||||
userId: string;
|
||||
entityType: string;
|
||||
entityId?: string;
|
||||
applicantId: string;
|
||||
status?: string;
|
||||
formData?: Record<string, unknown>;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Customer {
|
||||
id?: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
company?: string;
|
||||
source?: string;
|
||||
tags?: Record<string, unknown>;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Reminder {
|
||||
id?: string;
|
||||
userId: string;
|
||||
entityType: string;
|
||||
entityId?: string;
|
||||
remindAt: string;
|
||||
message?: string;
|
||||
sent?: boolean;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Services {
|
||||
id: string;
|
||||
userId?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
durationMin?: number;
|
||||
price?: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Appointments {
|
||||
id: string;
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
status?: string;
|
||||
notes?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Clients {
|
||||
id: string;
|
||||
userId?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
data?: Record<string, unknown>;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Stats {
|
||||
id: string;
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
status?: string;
|
||||
notes?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateUserInput {
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
nickname?: string;
|
||||
role?: string;
|
||||
phone?: string;
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface CreateContractInput {
|
||||
userId: string;
|
||||
title: string;
|
||||
partyA?: string;
|
||||
partyB?: string;
|
||||
amount?: number;
|
||||
signedAt?: string;
|
||||
expiresAt?: string;
|
||||
status?: string;
|
||||
fileUrl?: string;
|
||||
}
|
||||
|
||||
export interface CreateApprovalInput {
|
||||
userId: string;
|
||||
entityType: string;
|
||||
entityId?: string;
|
||||
applicantId: string;
|
||||
status?: string;
|
||||
formData?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateCustomerInput {
|
||||
userId: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
company?: string;
|
||||
source?: string;
|
||||
tags?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateReminderInput {
|
||||
userId: string;
|
||||
entityType: string;
|
||||
entityId?: string;
|
||||
remindAt: string;
|
||||
message?: string;
|
||||
sent?: boolean;
|
||||
}
|
||||
|
||||
export interface CreateServicesInput {
|
||||
userId?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
durationMin?: number;
|
||||
price?: number;
|
||||
}
|
||||
|
||||
export interface CreateAppointmentsInput {
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface CreateClientsInput {
|
||||
userId?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateStatsInput {
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserInput {
|
||||
username?: string;
|
||||
passwordHash?: string;
|
||||
nickname?: string;
|
||||
role?: string;
|
||||
phone?: string;
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface UpdateContractInput {
|
||||
userId?: string;
|
||||
title?: string;
|
||||
partyA?: string;
|
||||
partyB?: string;
|
||||
amount?: number;
|
||||
signedAt?: string;
|
||||
expiresAt?: string;
|
||||
status?: string;
|
||||
fileUrl?: string;
|
||||
}
|
||||
|
||||
export interface UpdateApprovalInput {
|
||||
userId?: string;
|
||||
entityType?: string;
|
||||
entityId?: string;
|
||||
applicantId?: string;
|
||||
status?: string;
|
||||
formData?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UpdateCustomerInput {
|
||||
userId?: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
company?: string;
|
||||
source?: string;
|
||||
tags?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UpdateReminderInput {
|
||||
userId?: string;
|
||||
entityType?: string;
|
||||
entityId?: string;
|
||||
remindAt?: string;
|
||||
message?: string;
|
||||
sent?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateServicesInput {
|
||||
userId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
durationMin?: number;
|
||||
price?: number;
|
||||
}
|
||||
|
||||
export interface UpdateAppointmentsInput {
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface UpdateClientsInput {
|
||||
userId?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UpdateStatsInput {
|
||||
userId?: string;
|
||||
clientId?: string;
|
||||
serviceId?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
// ─── Auth ───────────────────────────────────────────
|
||||
export interface LoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterInput {
|
||||
username: string;
|
||||
password: string;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
token: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
// ─── API ────────────────────────────────────────────
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface ErrorResponse {
|
||||
error: string;
|
||||
message: string;
|
||||
statusCode: number;
|
||||
}
|
||||
|
||||
// ─── JWT ────────────────────────────────────────────
|
||||
export interface JwtPayload {
|
||||
userId: string;
|
||||
username: string;
|
||||
role: string;
|
||||
iat?: number;
|
||||
exp?: number;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Type declarations for sql.js (no native types package available)
|
||||
declare module "sql.js" {
|
||||
export interface Database {
|
||||
run(sql: string, params?: BindParams): void;
|
||||
exec(sql: string): void;
|
||||
prepare(sql: string): Statement;
|
||||
export(): Uint8Array;
|
||||
close(): void;
|
||||
getRowsModified(): number;
|
||||
}
|
||||
|
||||
export interface Statement {
|
||||
bind(params?: BindParams): boolean;
|
||||
step(): boolean;
|
||||
getAsObject<T = Record<string, unknown>>(): T;
|
||||
getColumnNames(): string[];
|
||||
free(): boolean;
|
||||
}
|
||||
|
||||
export type BindParams = unknown[] | Record<string, unknown>;
|
||||
|
||||
export interface SqlJsStatic {
|
||||
Database: new (data?: ArrayLike<number>) => Database;
|
||||
}
|
||||
|
||||
export default function initSqlJs(config?: Record<string, unknown>): Promise<SqlJsStatic>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2022"
|
||||
],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"src/__tests__"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user