Compare commits

..

55 Commits

Author SHA1 Message Date
HoloPanio a048e1e824 feat: add CW callback route and optimize cache refresh workflows 2026-03-03 19:46:48 -06:00
HoloPanio 6d935e7180 feat: Redis opportunity cache, CW API retry/logging, adaptive TTLs
- Add Redis-backed opportunity cache with background refresh (30s interval)
- Fix concurrency bug: use lazy thunks instead of eager promises for batching
- Add withCwRetry utility with exponential backoff for transient CW errors
- Add adaptive TTL algorithms (primary, sub-resource, products) based on opportunity activity
- Add include query param on GET /sales/opportunities/:id (notes,contacts,products)
- Add opt-in CW API logger (LOG_CW_API env var) with timestamped files in cw-api-logs/
- Add debug-scripts/analyze-cw-calls.py for API call analysis
- Add computeSubResourceCacheTTL and computeProductsCacheTTL algorithms with tests
- Increase CW API timeout from 15s to 30s
- Unblock cache refresh from startup chain (remove await)
- Prioritize recently updated opportunities in refresh cycle
- Add CACHING.md documentation
- Update API_ROUTES.md with caching details and include param
- Update copilot instructions to require CACHING.md sync
- Add dev:log script for CW API call logging during development
2026-03-02 23:23:24 -06:00
HoloPanio fe71248e88 perf: cache-only strategy for list views, cache-then-cw for single fetch
- Add data-source hierarchy to opportunity manager (cache-only, cache-then-cw, cw-first)
- fetchPages/search/fetchByCompany use cache-only: Redis → DB (no CW calls)
- fetchItem uses cache-then-cw by default, cw-first when fresh=true
- Add idleTimeout: 255 to Bun.serve to prevent request timeouts
- Map CW status 57 (04. Confirmed Quote) to Active equivalency
- Add computeCacheTTL algorithm and opportunityCache module
2026-03-02 21:12:44 -06:00
HoloPanio 7411310083 fix: add migration for missing columns (cwIdentifier, catalog categories, productSequence) 2026-03-01 18:28:05 -06:00
HoloPanio 30b408e0db feat: add product to opportunity route, local product sequencing
- Add POST /v1/sales/opportunities/:identifier/products with field-level permission gating
- Add CWForecastItemCreate type for forecast item creation
- Store product display order locally (productSequence Int[] on Opportunity)
- Rewrite resequenceProducts to be local-only (no CW PUT, stable IDs)
- Remove reorderProducts CW util (PUT regenerated IDs & broke procurement)
- Update fetchProducts to apply local ordering with CW sequenceNumber fallback
- Add productSequence to OpportunityController.toJson()
- Update API_ROUTES.md, PERMISSIONS.md, PermissionNodes.ts
2026-03-01 18:01:02 -06:00
HoloPanio d7b374f8ab feat: sales activities, forecast products, catalog categories, member cache, procurement filters, and comprehensive tests
New features:
- ActivityController and manager for CW sales activities (CRUD)
- ForecastProductController for opportunity forecast/product lines
- CW member cache with dual-layer (in-memory + Redis) resolution
- Catalog category/subcategory/ecosystem taxonomy module
- Quote statuses type definitions with CW mapping
- User-defined fields (UDF) module with cache and event refresh
- Company sites CW module with serialization
- Procurement manager filters (category, ecosystem, manufacturer, price, stock)
- Opportunity notes CRUD and product line management via CW API
- Opportunity type definitions endpoint

Updates:
- OpportunityController: CW refresh, company hydration, activities, custom fields
- UserController: cwIdentifier field for CW member linking
- CatalogItemController: category/subcategory fields from CW
- PermissionNodes: sales note/product CRUD nodes, subCategories, collectPermissions
- API routes: procurement categories/filters, sales notes/products, opportunity types
- Global events: UDF and member refresh intervals on startup

Tests (414 passing):
- ActivityController, ForecastProductController, OpportunityController unit tests
- UserController cwIdentifier tests
- catalogCategories, companySites, memberCache, procurement module tests
- activityTypes, opportunityTypes, quoteStatuses type tests
- permissionNodes subCategories and getAllPermissionNodes tests
- Updated test setup with redis mock, API method mocks, and builder helpers
2026-03-01 13:19:00 -06:00
HoloPanio 883b648d5e fix: add identifier column migration and fix entrypoint resolve logic
- Add explicit migration for CatalogItem.identifier column
- Fix entrypoint script: resolve only migrations on 'Failed' lines (not all)
- Remove auto-diff generation (use committed migration files instead)
- Remove 2>/dev/null that swallowed migration errors
2026-02-27 17:44:08 -06:00
HoloPanio b787120461 fix: start HTTP server before background init to prevent bad gateway 2026-02-27 17:06:36 -06:00
HoloPanio 1326725995 fix: resolve failed migrations before deploying 2026-02-27 16:26:31 -06:00
HoloPanio 508fa39835 fix: crash loop recovery, auto-migrations, CI test pipeline
- Wrap startup syncs in safeStartup() to prevent crash on external service failure
- Add migrate-entrypoint.sh for auto-generating migrations from schema diff
- Update Dockerfile migration stage to use entrypoint script
- Add test job to build-and-publish workflow (runs before build)
- Add tests.yaml workflow to run tests on every push
- Fix test setup to use real RSA key pair instead of plain strings
- Add test script to package.json
2026-02-27 16:11:28 -06:00
HoloPanio b1f6462ac3 Fix UserController permission serialization and include current updates 2026-02-27 14:38:22 -06:00
HoloPanio 51eb36f4a6 fix: resolve type errors across test suite 2026-02-26 12:49:04 -06:00
HoloPanio 827b018f25 auto-create admin role on startup, use API_BASE_URL for auth redirects 2026-02-25 23:00:51 -06:00
HoloPanio 5852bd7819 remove migration drift check 2026-02-25 22:34:16 -06:00
HoloPanio 4c21245044 add shadow db service for migration drift check 2026-02-25 22:32:40 -06:00
HoloPanio ce456257ea fix prisma migrate diff flag 2026-02-25 22:30:28 -06:00
HoloPanio 8949819396 add CatalogItem migration and CI schema drift check 2026-02-25 22:28:07 -06:00
HoloPanio 49faf97c9b switch to PKCS#8 key format for Bun compatibility 2026-02-25 22:14:19 -06:00
HoloPanio 05bab2c90f convert PKCS#1 keys to PKCS#8 at load time 2026-02-25 21:56:09 -06:00
HoloPanio 29b5c986cd convert PKCS#1 keys to PKCS#8 at load time 2026-02-25 21:55:09 -06:00
HoloPanio 3d7db8b132 add ingress to CI deploy 2026-02-25 21:48:47 -06:00
HoloPanio cf16c8af49 pkcs1 err 2026-02-25 21:40:35 -06:00
HoloPanio f8639c9eee node env prod 2026-02-25 21:25:25 -06:00
HoloPanio 3779cdc379 fix tls and key secrets 2026-02-25 21:17:00 -06:00
HoloPanio 97b6c45bc0 we are all doomed 2026-02-25 21:02:33 -06:00
HoloPanio 2f2d95a510 outdated k8s flag 2026-02-25 20:59:06 -06:00
HoloPanio 21abf1a9bd fix env secret reference 2026-02-25 20:53:35 -06:00
HoloPanio 13e7d2e6ae update dockerfile 2026-02-25 20:09:59 -06:00
HoloPanio 075074456b update dockerfile 2026-02-25 20:08:09 -06:00
HoloPanio 9b0ce047a6 update dockerfile 2026-02-25 20:04:59 -06:00
HoloPanio d531e1ca83 dryrun 2026-02-24 18:47:27 -06:00
HoloPanio db9b722929 release workflow 2026-02-24 18:30:45 -06:00
HoloPanio 06e021f8a1 Version 2026-02-24 17:53:43 -06:00
HoloPanio da6e0311d8 update gitignore 2026-02-24 16:22:17 -06:00
HoloPanio 3c89f24189 setup unifi wlans 2026-02-22 19:12:34 -06:00
HoloPanio 70284bc14e a lot of things 2026-02-20 11:46:30 -06:00
HoloPanio 987a1c8a6a roles 2026-02-17 21:53:14 -06:00
HoloPanio 6d951e426d MAKING CREDENTIALS WORKS 2026-02-15 16:38:04 -06:00
HoloPanio cdae4d47a4 CREDENTIAL TYPE MANAGEMENT WORKS 2026-02-14 15:15:49 -06:00
HoloPanio b7637334a6 update gitignore 2026-02-14 13:51:43 -06:00
HoloPanio 3bdf562e44 update gitignore 2026-02-14 13:39:06 -06:00
HoloPanio 3ab443790c Lots of updates and cleaning up. 2026-02-14 12:08:23 -06:00
HoloPanio 7466bbdeac Something changed idk 2026-02-13 18:02:52 -06:00
HoloPanio 628dc35dea Companies are now listing properly 2026-02-13 17:02:03 -06:00
HoloPanio 24d0c066fd Setup fetch and wip fetchall route for getting companies. 2026-01-26 18:14:28 -06:00
HoloPanio 7748e6171b Added Connectwise Compnay Syncing 2026-01-26 17:09:18 -06:00
HoloPanio 4524c0258a Working User Authorization Flow 2026-01-26 15:56:10 -06:00
HoloPanio 8ee7dc15e5 Got Authorization flow working (Untested) 2026-01-25 16:53:18 -06:00
HoloPanio d96f18e6cf Fixed UserController errors 2026-01-25 15:09:55 -06:00
HoloPanio e76caa68f1 User Authentication Flow Works 2026-01-25 15:03:17 -06:00
HoloPanio 1bf0acdf39 Do not include dev pgsql nor redis data. 2026-01-25 15:01:13 -06:00
HoloPanio 4be36e6ca0 untested WIP 2026-01-24 16:59:50 -06:00
HoloPanio 935c7296f6 Update gitIgnore 2026-01-24 13:47:52 -06:00
HoloPanio 916e5a7ada bun init 2026-01-24 11:00:35 -06:00
Jackson 573afbaeca Initial commit 2026-01-24 10:54:03 -06:00
413 changed files with 56225 additions and 33633 deletions
+37
View File
@@ -0,0 +1,37 @@
version: "3"
services:
pgsql:
image: postgres:17
restart: unless-stopped
environment:
POSTGRES_USER: optima
POSTGRES_PASSWORD: 123web123
POSTGRES_DB: optima
volumes:
- ./postgres:/var/lib/postgresql/data
ports:
- 5432:5432
redis:
image: redis:6.2-alpine
restart: always
ports:
- "6379:6379"
command: redis-server --save 20 1 --loglevel warning --requirepass iamatotallysecurepassworddonttestmebrox
volumes:
- ./redis:/data
adminer:
image: adminer
restart: unless-stopped
ports:
- 8080:8080
depends_on:
- pgsql
redisinsight:
image: redis/redisinsight:latest
container_name: redisinsight
ports:
- "5540:5540"
restart: unless-stopped
-16
View File
@@ -1,16 +0,0 @@
node_modules
.svelte-kit
build
out
.vite
.env
.env.*
*.dmg
*.zip
e2e
electron
forge.config.ts
forge.env.d.ts
vite.main.config.ts
vite.preload.config.ts
playwright.config.ts
+6
View File
@@ -0,0 +1,6 @@
{
"action": "created",
"release": {
"tag_name": "v0.0.0-test"
}
}
+183 -113
View File
@@ -1,157 +1,227 @@
# Copilot Instructions for ttscm-ui
# Copilot / AI Agent Instructions for optima-api
## Project Overview
Purpose: make AI coding agents immediately productive in this repository by describing architecture, conventions, workflows, and helpful code pointers.
**ttscm-ui** is an Electron desktop application built with **SvelteKit**, TypeScript, and Vite. It connects to the Optima API for credential and company management. The app uses standard SvelteKit routing for single-page navigation and bun for package management with patches applied to SvelteKit.
---
## Architecture Layers
## Big picture
### Electron Architecture
This is a TypeScript API service (runs on **Bun**) using the **Hono** framework. The HTTP surface is implemented in `src/api` where small route-handler files are mounted on a versioned router in `src/api/server.ts` (see the `/v1` mount). The typical request flow is:
- **`electron/main.ts`**: Main process—creates/manages windows, handles file system access. Loads preload script and serves the renderer.
- **`electron/preload.ts`**: Currently empty bridge between main and renderer processes. Extend here to expose secure IPC handlers if needed.
- **`forge.config.ts`**: Electron Forge configuration with Vite plugin for building main, preload, and renderer targets.
### Frontend (SvelteKit)
- **`src/routes/`**: SvelteKit file-based routing with standard pathname router.
- `(auth)` group: Authentication pages (login)
- `(secure)` group: Protected pages requiring auth
- **`src/lib/`**: Reusable modules
- `optima-api/`: API client abstraction with modular endpoints (auth, companies, credentials, etc.)
- `axios.ts`: Base axios instance with `PUBLIC_API_URL` env variable
- **`src/components/`**: Reusable Svelte components (modals, spinners, error boundaries)
### API Communication
The `$lib/index.ts` exports `optima` object aggregating all API modules. Example:
```typescript
export const optima = {
auth: (await import("./optima-api/modules/auth")).auth,
company: (await import("./optima-api/modules/companies")).company,
// etc.
};
```
server.ts → routers/<domain>Router.ts → api/<domain>/*.ts (route handlers) → managers/<domain>.ts → controllers (domain models) / modules / generated/prisma
```
Each module (e.g., `auth.ts`) exports functions that call the API using a custom axios instance.
Keep each layer focused:
## Key Conventions
- **Route handler files** (`src/api/<domain>/*.ts`) — define individual endpoints using the `createRoute()` utility, handle request validation with Zod, call managers, and return `apiResponse.*` results.
- **Routers** (`src/api/routers/*`) — aggregate route handler files from a domain's `index.ts` and re-mount them under a single prefix. Mounted in `src/api/server.ts`.
- **Managers** (`src/managers/*`) — thin domain/persistence layers that wrap `generated/prisma` calls and other I/O. Managers instantiate and return **controller** instances as domain objects.
- **Controllers** (`src/controllers/*`) — **domain model classes** (e.g., `CompanyController`, `CredentialController`, `UserController`) that encapsulate entity state and domain methods. They are NOT request handlers. Managers create and return controller instances.
- **Modules** (`src/modules/*`) — shared utilities, external API clients (ConnectWise, UniFi, Microsoft), credential helpers, permission utilities, and tools.
### Routing
---
- **Use standard SvelteKit routing with `/` prefix** (e.g., `href="/credentials"`)
- Routes in `src/routes/` map to `/path` at runtime
- Do NOT use hash-based routing (`#/` routes)
## Runtime / tooling
### API Module Pattern
The project runs on **Bun** exclusively — **always use `bun` commands, never `npm`, `npx`, or `yarn`**. DB tooling uses **Prisma**; the generated client lives under `generated/prisma` (do NOT edit generated files). Test preloads are configured in `bunfig.toml` so bare `bun test` works. Key scripts in `package.json`:
Create API modules in `src/lib/optima-api/modules/` following this pattern:
- `dev``NODE_ENV=development bun --watch src/index.ts` (start dev server with hot reload)
- `test``bun test` (runs all tests with preload from `bunfig.toml`)
- `db:gen``prisma generate`
- `db:push``prisma migrate dev --skip-generate`
- `utils:dev``docker compose -f .docker/docker-compose.yml up --build`
- `utils:gen_private_keys``bun ./utils/genPrivateKeys`
- `utils:create_admin_role``bun ./utils/createAdminRole`
- `utils:assign_user_role``bun ./utils/assignUserRole`
```typescript
// Example: credentials.ts
export const credential = {
async fetchCredentials(api: AxiosInstance) {
// Implementation
},
};
## Data layer
Prisma schema is at `prisma/schema.prisma`. The app imports the generated Prisma client from `generated/prisma/client.ts` (or `generated/prisma/browser.ts` for browser type contexts). The shared `prisma` instance is exported from `src/constants.ts`. Always run `bun run db:gen` after updating `schema.prisma`.
## Shared constants (`src/constants.ts`)
This file exports critical shared instances used across the codebase:
- `prisma` — the PrismaClient instance (via `@prisma/adapter-pg`)
- `PORT`, session/token durations, private/public keys for JWT signing
- `msalClient` — Microsoft MSAL client for OAuth
- `connectWiseApi` — Axios instance for ConnectWise API
- `unifi``UnifiClient` instance for UniFi controller interaction
---
## Route handler pattern (`createRoute`)
Every route handler file uses the `createRoute()` utility from `src/modules/api-utils/createRoute.ts`. It creates a self-contained Hono sub-app for a single endpoint:
```ts
export default createRoute(
"get", // HTTP method
["/companies"], // path(s)
async (c) => {
/* handler */
}, // request handler
authMiddleware({ permissions: ["company.fetch.many"] }), // middleware (spread)
);
```
Export as a named object, then import/aggregate in `src/lib/index.ts`.
Route files live in `src/api/<domain>/*.ts`. Each domain folder has an `index.ts` that re-exports all route modules. Router files (`src/api/routers/<domain>Router.ts`) import from the domain's index and auto-mount all routes:
### Environment Variables
- `PUBLIC_API_URL`: API base URL, used in `src/lib/optima-api/axios.ts`
- Prefixed with `PUBLIC_` to be accessible in client code
### File Organization
- Components go in `src/components/` (e.g., modals, spinners)
- Page-specific logic in `src/routes/[route]/+page.svelte` and `+page.server.ts`
- Styles in `src/styles/` with Tailwind CSS + TailwindCSS vite plugin
- Tests colocated: `*.spec.ts` or `*.test.ts` next to source files
## Development Workflow
### Installation & Setup
```bash
bun install
```ts
import * as companyRoutes from "../companies";
const companyRouter = new Hono();
Object.values(companyRoutes).map((r) => companyRouter.route("/", r));
export default companyRouter;
```
Uses bun with SvelteKit patches (see `patches/` directory).
`src/api/server.ts` then mounts each router under `/v1`:
### Running in Development
```bash
bun start
```ts
v1.route("/company", require("./routers/companyRouter").default);
```
Electron Forge + Vite handles dev server and hot module replacement (HMR). Dev tools open automatically. Main window loads `/login` first.
## Routing & domain organization
### Building & Packaging
The `server.ts` file mounts these routers under `/v1`:
- **Build for production**: `bun run package` → outputs to `out/` directory
- **Create distributable**: `bun run make` → creates installers (configure in `forge.config.ts`)
- **Check types & lint**: `bun run check` (runs svelte-kit sync + svelte-check)
- `/teapot` — health check
- `/auth` — Microsoft OAuth flow (`src/api/auth/*`)
- `/user` — user routes (`src/api/user/*`) including `@me` sub-routes
- `/company` — company routes (`src/api/companies/*`)
- `/credential` — credential routes (`src/api/credentials/*`)
- `/credential-type` — credential type routes (`src/api/credential-types/*`)
- `/role` — role management (`src/api/roles/*`)
- `/permissions` — permission node queries (`src/api/permissions/*`)
- `/unifi` — UniFi integration (`src/api/unifi/*` with `sites/` and `site/` sub-folders)
### Testing
---
#### Unit Tests (Vitest)
## API layout & conventions (how to add a new endpoint)
```bash
bun run test:unit
```
1. **Add route handler files**: Create `src/api/<domain>/<action>.ts` files, each exporting a default `createRoute(...)` call. Validate input with Zod inside the handler, call managers for business logic, and return responses via `apiResponse.*`.
2. **Add domain index**: Create `src/api/<domain>/index.ts` that re-exports all route modules from the folder.
3. **Add router**: Create `src/api/routers/<domain>Router.ts` that imports all routes from the domain's index and mounts them. Mount it in `src/api/server.ts` under `v1`.
4. **Add manager**: Create `src/managers/<domains>.ts` (plural filename) for persistence/domain logic. Use the `prisma` instance from `src/constants.ts`; do not import Prisma directly in route handlers. Managers should instantiate and return controller instances when the domain warrants it.
5. **Add controller** (if needed): Create `src/controllers/<Domain>Controller.ts` (singular filename) as a **class** that encapsulates entity state, domain methods, and a `toJson()` serializer. Controllers are domain model objects — they do NOT handle HTTP requests.
6. **Add modules/types**: If needed, add helpers to `src/modules/*` and runtime types to `src/types/*`.
7. **Middleware & auth**: Use `authMiddleware()` from `src/api/middleware/authorization.ts` as the last argument to `createRoute()`. It accepts `{ permissions?: string[], scopes?: string[], forbiddenAuthTypes?: string[] }`. Follow existing token/session patterns from `src/controllers/SessionController.ts` and `src/Errors/*`.
8. **Error handling**: Throw repository-specific errors from `src/Errors/*` (include `status`, `name`, `message`, optional `cause`) and let `src/api/server.ts` map them via `apiResponse.error`.
9. **Naming conventions**: plural manager filenames (`companies.ts`), singular controller class names (`CompanyController.ts`), descriptive route handler filenames (`fetchAll.ts`, `create.ts`, `update.ts`).
- Client tests: `src/**/*.svelte.{test,spec}.{js,ts}` (jsdom environment)
- Server tests: `src/**/*.{test,spec}.{js,ts}` excluding svelte tests (node environment)
- Setup: `vitest-setup-client.ts` mocks `window.matchMedia` for Svelte 5 + jsdom compatibility
---
#### E2E Tests (Playwright)
## Examples & notable files
```bash
bun run test:e2e
```
- `src/api/server.ts` — mounts `v1`, registers `cors`, central `onError` handler and `notFound` response.
- `src/api/companies/fetchAll.ts` — canonical example of a route handler file using `createRoute()`, `authMiddleware()`, managers, and `apiResponse`.
- `src/api/credentials/create.ts` — example of Zod validation inside a route handler.
- `src/api/routers/companyRouter.ts` — canonical router that auto-mounts all route modules from a domain folder.
- `src/api/user/@me/*` — nested sub-route example (user's own profile endpoints).
- `src/controllers/CompanyController.ts` — example domain model class with methods like `refreshFromCW()`, `fetchCwData()`, and `toJson()`.
- `src/controllers/CredentialController.ts` — example of a richer domain model class with field validation, secure value handling, and sub-credential support.
- `src/managers/companies.ts` — example manager calling Prisma and returning `CompanyController` instances.
- `src/modules/api-utils/createRoute.ts` — the `createRoute()` utility used by every route handler.
- `src/modules/cw-utils/*` — external ConnectWise API integrations; keep interfaces stable and return domain objects consumed by managers.
- `src/modules/unifi-api/UnifiClient.ts` — UniFi controller API client class with methods for sites, WLANs, devices, networks, etc.
- `src/modules/credentials/*` — credential field validation, secure value encryption/decryption, and type definitions.
- `src/constants.ts` — shared instances (`prisma`, API clients, keys, durations).
- Tests in `e2e/` directory
- Config: `playwright.config.ts` (builds and previews before testing)
---
#### Run All Tests
## Validation & errors
```bash
bun run test
```
Zod is used for input validation **inside route handler files** (not controllers). Zod errors are handled centrally in `src/api/server.ts` via `apiResponse.zodError`. Application errors use custom error classes in `src/Errors/*` (e.g., `AuthenticationError.ts`, `GenericError.ts`, `AuthorizationError.ts`, `InsufficientPermission.ts`). When creating errors, follow the shape used in existing errors (include `status`, `name`, `message`, and optional `cause`).
Runs unit tests first, then e2e.
## Response pattern
## Critical Integration Points
Use the `apiResponse` helpers in `src/modules/api-utils/apiResponse.ts` for formatting all HTTP responses:
### IPC (Electron Main ↔ Renderer)
- `apiResponse.successful(message, data?, meta?)` — 200
- `apiResponse.created(message, data?)` — 201
- `apiResponse.error(err)` — reads `status` from the error
- `apiResponse.internalError()` — 500
- `apiResponse.zodError(err)` — 400
**Status**: Preload script is currently empty. If file system access is needed, define IPC handlers in `electron/main.ts` and expose them via `electron/preload.ts` to renderer process.
## Auth & external integrations
### API Authentication
Microsoft OAuth flow is under `src/api/auth/*` and `src/modules/fetchMicrosoftUser.ts`. If touching authentication, follow existing redirect/refresh patterns in `src/api/auth` and preserve token-refresh semantics.
- Auth flow starts in `src/lib/optima-api/modules/auth.ts` with `fetchAuthRedirectUri()`
- TODO: Enforce auth checks on every page change (see `src/lib/index.ts` comment)
## ConnectWise integration
### Build Artifacts
Utilities for ConnectWise interactions live in `src/modules/cw-utils/*` (e.g., `configurations/fetchCompanyConfigurations.ts`, `fetchCompany.ts`, `fetchAllCompanies.ts`). These modules call external APIs via the `connectWiseApi` Axios instance from `src/constants.ts` and return domain data; preserve the module contracts (input types and returned shapes) when refactoring.
- **Dev server URL**: `MAIN_WINDOW_VITE_DEV_SERVER_URL` (injected by Electron Forge)
- **Output**: Rendered app built to `.vite/renderer/main_window/` (configured in `svelte.config.js`)
## UniFi integration
## Common Patterns & Gotchas
The `UnifiClient` class in `src/modules/unifi-api/UnifiClient.ts` wraps all UniFi controller API interactions (login, sites, WLANs, devices, networks, AP groups, WLAN groups, speed profiles, PPSKs). The shared instance is exported from `src/constants.ts` as `unifi`. UniFi route handlers live in `src/api/unifi/` with `sites/` (multi-site operations) and `site/` (single-site operations) sub-folders.
1. **Standard Routing**: Use standard SvelteKit routing with `/` prefix (e.g., `href="/credentials"`) — do NOT use hash-based routing
2. **SvelteKit Patches**: Project patches SvelteKit in `patches/` to work around issues. When updating SvelteKit, verify patches still apply.
3. **Async Components**: Svelte 5 has `experimental.async: true` enabled; be aware of async component patterns.
4. **Tailwind**: Uses `@tailwindcss/vite` plugin; configure utilities in tailwind config if needed.
5. **API Error Handling**: API modules throw errors with descriptive messages. Use `$lib/errorHandler.ts` for consistent error formatting.
## Generated files and CI
## Useful Entry Points for Navigation
`generated/` is a build artifact. Do not modify. When updating Prisma models, run `npm run db:gen` and commit changes to `generated/prisma` only if that's the established workflow.
- **Frontend Layout**: [src/routes/+layout.svelte](src/routes/+layout.svelte) (main shell, sidebar, header)
- **API Abstraction**: [src/lib/optima-api/axios.ts](src/lib/optima-api/axios.ts) (base client)
- **API Modules**: [src/lib/optima-api/modules/](src/lib/optima-api/modules/) (auth, companies, credentials, etc.)
- **App Entry**: [src/app.html](src/app.html)
- **Electron Main**: [electron/main.ts](electron/main.ts)
---
## Coding conventions & patterns specific to this repo
- Prefer the existing layered architecture: route handlers → managers → controllers (domain models) / modules.
- Use the `createRoute()` utility for all route handler files.
- Use the `apiResponse` helpers for all HTTP responses.
- Throw or propagate repository-specific custom errors (from `src/Errors/*`) rather than returning bare objects.
- Keep TypeScript types in `src/types/*` and use Zod for runtime checks inside route handlers.
- **Avoid `else` statements** — prefer ternary operators, early returns, or other control flow patterns. Only use `else` if there is absolutely no other way.
- ES module syntax (`export default`, `import`) is used throughout. The `require()` calls in `server.ts` are for lazy loading but all modules use `export default`.
---
## Local dev / quick checks
- Start dev server: `bun run dev`
- Run tests: `bun test`
- Regenerate Prisma client: `bun run db:gen`
- Apply DB migrations locally: `bun run db:push`
- Docker dev utilities: `bun run utils:dev`
- Generate private keys: `bun run utils:gen_private_keys`
- Create admin role: `bun run utils:create_admin_role`
- Assign user role: `bun run utils:assign_user_role`
## When editing generated or infra files
If you need to change `generated/prisma/*` (rare), explain why in the PR and show commands used to regenerate.
---
## Documentation sync (IMPORTANT)
Whenever you add, remove, or modify API routes or permission nodes, you **must** update all three of the following files to keep them in sync:
1. `src/types/PermissionNodes.ts` — the single source of truth for all permission node definitions, categories, descriptions, and `usedIn` references.
2. `PERMISSIONS.md` — human-readable documentation of all permission nodes; must strictly reflect the data in `PermissionNodes.ts`.
3. `API_ROUTES.md` — comprehensive documentation of all API routes, including method, path, auth requirements, permissions, request/response examples.
Additionally, whenever you add, remove, or modify **caching logic** (TTL algorithms, cache key patterns, background refresh mechanics, retry settings, or invalidation behavior), you **must** update:
4. `CACHING.md` — comprehensive documentation of the Redis-backed opportunity cache, TTL algorithms, background refresh mechanics, retry logic, and debugging tools.
Always verify that new routes have their required permissions listed in `PermissionNodes.ts`, that `PERMISSIONS.md` tables match the TS file exactly, that `API_ROUTES.md` includes full documentation for every mounted route, and that `CACHING.md` accurately reflects any caching changes. Run through all relevant files at the end of any route, permission, or caching change to catch discrepancies.
---
## Field-level permission gating (`processObjectValuePerms`)
Some routes use `processObjectValuePerms` from `src/modules/permission-utils/processObjectPermissions.ts` to filter response objects on a per-field basis. When this pattern is used, every key of the response object becomes a permission node in the form `<scope>.<field>` (e.g., `unifi.site.wifi.read.passphrase`). Only fields whose corresponding permission the user holds are included in the response.
There is also `processObjectPermMap` in the same file, which returns a `Record<key, boolean>` indicating which fields the user has permission for (useful for UI gating).
**When documenting a route that uses field-level gating, you must:**
1. Note in `API_ROUTES.md` that the route uses field-level gating, explain the behaviour, and list every `<scope>.<field>` permission node in a collapsible table.
2. Add a `unifi.site.wifi.read`-style parent permission node in `PermissionNodes.ts` with a `fieldLevelPermissions` array listing every `<scope>.<field>` node.
3. Add matching rows/notes to `PERMISSIONS.md` including the full list of field-level nodes.
**Current routes using field-level gating:**
- `GET /v1/unifi/site/:id/wifi` — scope `unifi.site.wifi.read`, gates every field on the `WlanConf` object.
---
If anything here is unclear or you'd like more examples (e.g., a walk-through adding a route handler + manager + controller), tell me which area to expand and I'll iterate.
+56 -70
View File
@@ -5,8 +5,28 @@ on:
types: [created]
jobs:
build-server:
name: Build Server Image
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Generate Prisma client
run: DATABASE_URL="postgresql://dummy:dummy@localhost:5432/dummy" bunx prisma generate
- name: Run tests
run: bun test --preload ./tests/setup.ts
build:
name: Build
needs: [test]
runs-on: ubuntu-latest
permissions:
contents: read
@@ -22,88 +42,54 @@ jobs:
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Checkout source code
uses: actions/checkout@v4
- name: Build and push the Docker image
uses: docker/build-push-action@v6
with:
context: .
push: true
build-args: |
PUBLIC_API_URL=https://opt-api.osdci.net
target: runtime
tags: |
ghcr.io/project-optima/ttscm-ui:latest
ghcr.io/project-optima/ttscm-ui:${{ github.event.release.tag_name }}
ghcr.io/project-optima/ttscm-api:latest
ghcr.io/project-optima/ttscm-api:${{ github.event.release.tag_name }}
build-desktop-macos:
name: Build Desktop (macOS)
runs-on: macos-latest
permissions:
contents: write
- name: Build and push the migration image
uses: docker/build-push-action@v6
with:
push: true
target: migration
tags: |
ghcr.io/project-optima/ttscm-api-migrate:latest
ghcr.io/project-optima/ttscm-api-migrate:${{ github.event.release.tag_name }}
migrate:
name: Run Migrations
needs: [build]
runs-on: ubuntu-latest
steps:
- name: Set the Kubernetes context
uses: azure/k8s-set-context@v2
with:
method: kubeconfig
kubeconfig: ${{ secrets.KUBECONFIG }}
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Delete previous migration job if exists
run: kubectl delete job -n optima -l app=prisma-migrate --ignore-not-found
- name: Install bun
uses: oven-sh/setup-bun@v2
- name: Apply migration job
run: |
TAG=${{ github.event.release.tag_name }}
sed "s/RELEASE_TAG/${TAG}/g" kubernetes/migration-job.yaml | kubectl apply -f -
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Rebuild native modules
run: npm rebuild
- name: Build macOS distributables
run: bun run make:macos
env:
PUBLIC_API_URL: https://opt-api.osdci.net
- name: Upload macOS artifacts to release
uses: softprops/action-gh-release@v2
with:
files: |
out/make/**/*.dmg
out/make/**/*.zip
build-desktop-windows:
name: Build Desktop (Windows)
runs-on: windows-latest
permissions:
contents: write
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install dependencies
run: npm install
- name: Build Windows distributables
run: npm run make -- --platform win32
env:
PUBLIC_API_URL: https://opt-api.osdci.net
- name: Upload Windows artifacts to release
uses: softprops/action-gh-release@v2
with:
files: |
out/make/**/*.exe
out/make/**/*.nupkg
out/make/**/*.msi
- name: Wait for migration to complete
run: |
TAG=${{ github.event.release.tag_name }}
kubectl wait --for=condition=complete --timeout=120s -n optima job/prisma-migrate-${TAG}
deploy:
name: Deploy
needs: [build-server]
needs: [migrate]
runs-on: ubuntu-latest
steps:
- name: Set the Kubernetes context
@@ -134,4 +120,4 @@ jobs:
kubernetes/deployment.yaml
kubernetes/ingress.yaml
images: |
ghcr.io/project-optima/ttscm-ui:${{ github.event.release.tag_name }}
ghcr.io/project-optima/ttscm-api:${{ github.event.release.tag_name }}
+25
View File
@@ -0,0 +1,25 @@
name: Tests
on:
push:
branches: ["**"]
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Generate Prisma client
run: DATABASE_URL="postgresql://dummy:dummy@localhost:5432/dummy" bunx prisma generate
- name: Run tests
run: bun test --preload ./tests/setup.ts
+144 -19
View File
@@ -1,29 +1,154 @@
test-results
node_modules
# Logs
logs
*.log
*.jsonl
cw-api-logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# OS
.DS_Store
Thumbs.db
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Env
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.*
!.env.example
!.env.test
# Vite
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Sveltekit cache directory
.svelte-kit/
# vitepress build output
**/.vitepress/dist
# vitepress cache directory
**/.vitepress/cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# Firebase cache directory
.firebase/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v3
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Vite logs files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vite
out
tailwindcss-*.log
pnpm-lock.yaml
.permissions.key
.refreshToken.key
.secureValues.key
.accessToken.key
public-keys/
production-keys/
microsoft-oauth.json
.docker/postgres
.docker/redis
-2
View File
@@ -1,2 +0,0 @@
engine-strict=true
node-linker=hoisted
+5
View File
@@ -0,0 +1,5 @@
{
"chat.tools.terminal.autoApprove": {
"bun": true
}
}
+4868
View File
File diff suppressed because it is too large Load Diff
+348
View File
@@ -0,0 +1,348 @@
# Caching Architecture
This document describes the caching layer used in the Optima API, covering the Redis-backed opportunity cache, TTL algorithms, background refresh mechanics, retry logic, and debugging tools.
---
## Overview
The API caches expensive ConnectWise (CW) API responses in **Redis** to reduce latency and avoid CW rate limits. The primary cache layer is the **opportunity cache** (`src/modules/cache/opportunityCache.ts`), which proactively warms data for all non-closed opportunities on a background interval.
### Key design principles
- **Adaptive TTLs** — cache durations are computed dynamically based on how "hot" an opportunity is (recently updated = shorter TTL = fresher data).
- **Background refresh** — a 20-minute interval scans all open opportunities and re-fetches only expired cache keys.
- **Bounded concurrency** — CW API calls are throttled via thunk-based batching to prevent overwhelming the upstream API.
- **Graceful degradation** — transient CW errors (timeouts, network failures) are caught, logged, and retried on the next cycle rather than crashing the process.
- **Priority ordering** — most recently updated opportunities are refreshed first so active deals get fresh data before stale ones.
---
## What is cached
Each non-closed opportunity can have up to 7 cached payloads in Redis:
| Cache Key Pattern | Data | Source |
| ----------------------------------- | ------------------------------------ | --------------------------------------------------------------------- |
| `opp:cw-data:{cwOpportunityId}` | Raw CW opportunity response | `GET /sales/opportunities/:id` |
| `opp:activities:{cwOpportunityId}` | CW activities array | `GET /sales/activities?conditions=opportunity/id=:id` |
| `opp:notes:{cwOpportunityId}` | CW notes array | `GET /sales/opportunities/:id/notes` |
| `opp:contacts:{cwOpportunityId}` | CW contacts array | `GET /sales/opportunities/:id/contacts` |
| `opp:products:{cwOpportunityId}` | Forecast + procurement products blob | `GET /sales/opportunities/:id/forecast` + `GET /procurement/products` |
| `opp:company-cw:{cw_CompanyId}` | Hydrated company + contacts blob | `GET /company/companies/:id` + contacts endpoints |
| `opp:site:{cwCompanyId}:{cwSiteId}` | Company site data | `GET /company/companies/:id/sites/:siteId` |
Inventory-adjustment-driven catalog sync adds a targeted product cache:
| Cache Key Pattern | Data | Source |
| ------------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `catalog:item:cw:{cwId}` | Full CW catalog item + computed `onHand` + DB row snapshot | `GET /procurement/adjustments` + `GET /procurement/catalog/:id` + catalog inventory endpoint |
---
## TTL Algorithms
Three algorithms compute cache TTLs. All share the same input signals:
- `closedFlag` — whether the opportunity is closed
- `closedDate` — when it was closed
- `expectedCloseDate` — projected close date (forward-looking signal)
- `lastUpdated` — last CW modification date (backward-looking signal)
### Primary TTL (`computeCacheTTL`)
**File:** `src/modules/algorithms/computeCacheTTL.ts`
Used for: opportunity CW data, activities, company CW data.
| # | Condition | TTL | Human |
| --- | ------------------------------------------------------- | ---------- | ------------ |
| 1a | Closed > 30 days ago | `null` | Do not cache |
| 1b | Closed within 30 days | 900,000 ms | 15 minutes |
| 2 | `expectedCloseDate` or `lastUpdated` within **5 days** | 30,000 ms | 30 seconds |
| 3 | `expectedCloseDate` or `lastUpdated` within **14 days** | 60,000 ms | 60 seconds |
| 4 | Everything else | 900,000 ms | 15 minutes |
Rules are evaluated top-to-bottom; first match wins.
### Sub-Resource TTL (`computeSubResourceCacheTTL`)
**File:** `src/modules/algorithms/computeSubResourceCacheTTL.ts`
Used for: notes, contacts.
| # | Condition | TTL | Human |
| --- | --------------------- | ---------- | ------------ |
| 1a | Closed > 30 days ago | `null` | Do not cache |
| 1b | Closed within 30 days | 300,000 ms | 5 minutes |
| 2 | Within **5 days** | 60,000 ms | 60 seconds |
| 3 | Within **14 days** | 120,000 ms | 2 minutes |
| 4 | Everything else | 300,000 ms | 5 minutes |
### Products TTL (`computeProductsCacheTTL`)
**File:** `src/modules/algorithms/computeProductsCacheTTL.ts`
Used for: forecast + procurement products.
| # | Condition | TTL | Human |
| --- | ------------------------------------------- | ------------ | ---------- |
| 1 | Status is Won/Lost/Pending Won/Pending Lost | `null` | No cache |
| 2 | Main cache TTL is `null` | `null` | No cache |
| 3 | `lastUpdated` within **3 days** | 15,000 ms | 15 seconds |
| 4 | Everything else | 1,200,000 ms | 20 minutes |
Products on terminal-status opportunities are never proactively cached. Non-hot products use a **lazy on-demand** cache — they're fetched when requested and cached for 20 minutes.
### Site TTL
Sites use a fixed TTL of **20 minutes** (1,200,000 ms). Site/address data rarely changes. Sites are **not** proactively warmed by the background refresh — they are populated lazily on the first detail-view request.
---
## Background Refresh
**Function:** `refreshOpportunityCache()` in `src/modules/cache/opportunityCache.ts`
**Interval:** Every 20 minutes, triggered from `src/index.ts`.
### Refresh cycle
1. **Query DB** — fetch all non-closed opportunities + recently closed (within 30 days), ordered by `cwLastUpdated DESC` (most recently active first).
2. **Batch EXISTS check** — use a single Redis pipeline to check which cache keys already exist (5 EXISTS commands per opportunity: oppCwData, activities, notes, contacts, products).
3. **Build thunk list** — for each opportunity with missing keys, push a **thunk** (lazy function) into the task list. No HTTP requests fire at this point.
4. **Execute with bounded concurrency** — process thunks in batches of `CONCURRENCY` (currently **6**), with a `BATCH_DELAY_MS` (currently **250ms**) pause between batches. Each thunk is only invoked inside the batch loop.
5. **Emit events**`cache:opportunities:refresh:started` and `cache:opportunities:refresh:completed` events are emitted for the event debugger.
### Inventory-adjustment listener cycle
**Function:** `listenInventoryAdjustments()` in `src/modules/cw-utils/procurement/listenInventoryAdjustments.ts`
**Interval:** Every 60 seconds, triggered from `src/index.ts`.
1. Fetch `GET /procurement/adjustments?pageSize=1000`.
2. Build a normalized snapshot of tracked inventory rows (`cwCatalogId`, `onHand`, `inventory`) per adjustment.
3. Compare to previous snapshot; extract only changed product IDs.
4. For each changed product ID, fetch fresh CW catalog item + current on-hand.
5. Upsert `CatalogItem` in Postgres and write Redis key `catalog:item:cw:{cwId}` with a 20-minute TTL.
Guardrails to prevent request storms:
- Diffing is computed at **product state** level (grouped by `cwCatalogId`), not raw adjustment-row churn.
- Per-cycle syncs are capped (`CW_ADJUSTMENT_SYNC_MAX_PER_CYCLE`, default `50`).
- Product resync cooldown is enforced (`CW_ADJUSTMENT_SYNC_COOLDOWN_MS`, default `600000` ms / 10 min).
This avoids full-catalog sweeps for small inventory movements and updates only the products implicated by adjustments.
### Full procurement catalog refresh
**Function:** `refreshCatalog()` in `src/modules/cw-utils/procurement/refreshCatalog.ts`
**Interval:** Every 30 minutes, triggered from `src/index.ts`.
The full catalog cache/DB sync uses the same slow-parallel thunk strategy as opportunity cache refreshes:
- Build arrays of thunk tasks (`() => Promise<void>`) for CW item fetches, inventory fetches, and DB upserts.
- Execute with bounded concurrency (`CONCURRENCY=6`).
- Pause between batches (`BATCH_DELAY_MS=250`) to avoid CW burst pressure.
- Log task failures and retry naturally on the next cycle.
This keeps full-catalog refresh conservative while inventory-adjustment listener handles near-real-time targeted updates.
### Full inventory sweep fallback
`refreshInventory()` remains as a safety net but is intentionally infrequent:
- Runs every **6 hours** from `src/index.ts` (no startup-time full sweep).
- Uses the same slow-parallel pattern (`CONCURRENCY=6`, `BATCH_DELAY_MS=250`) to avoid burst traffic.
Most on-hand freshness now comes from the 60-second adjustment listener plus 30-minute full catalog refresh.
### Concurrency control
The thunk pattern is critical. Previously, tasks were pushed as already-executing promises (`refreshTasks.push(fetchAndCache(...))`), which meant all HTTP requests fired simultaneously regardless of the batching loop. The fix was changing the array type from `Promise<void>[]` to `(() => Promise<void>)[]` so requests only start when explicitly invoked: `batch.map((fn) => fn())`.
### Current tuning
| Parameter | Value | Effect |
| ---------------- | ---------- | ------------------------------------------ |
| `CONCURRENCY` | 6 | Max simultaneous CW API requests per batch |
| `BATCH_DELAY_MS` | 250 | Milliseconds between batches |
| Refresh interval | 20 minutes | How often the full sweep runs |
At these settings, a full sweep of ~500 expired keys completes in ~1-2 minutes with zero CW errors and ~230ms median latency.
---
## Retry Logic (`withCwRetry`)
**File:** `src/modules/cw-utils/withCwRetry.ts`
Wraps CW API calls with exponential backoff retry on transient errors.
### Retryable errors
- `ECONNABORTED` (timeout)
- `ECONNRESET`
- `ETIMEDOUT`
- `ECONNREFUSED`
- `ERR_NETWORK`
- `ENETUNREACH`
- HTTP 5xx server errors
### Default configuration
| Parameter | Default | Description |
| ------------- | ------- | ----------------------------------------------------------- |
| `maxAttempts` | 3 | Total attempts including the first |
| `baseDelayMs` | 1,000 | Delay before first retry (doubles each retry: 1s → 2s → 4s) |
| `label` | — | Optional tag for log messages |
### Usage
```ts
import { withCwRetry } from "./withCwRetry";
const response = await withCwRetry(
() => connectWiseApi.get(`/company/companies/${id}`),
{ label: `fetchCompany#${id}`, maxAttempts: 3, baseDelayMs: 1_500 },
);
```
Non-transient errors (404, 400, etc.) are re-thrown immediately without retry.
---
## CW API Logger
**File:** `src/modules/cw-utils/cwApiLogger.ts`
Axios interceptor that logs every CW API call to a JSONL file. Logging is **opt-in** — set the `LOG_CW_API` environment variable to enable it. Each process start creates a new timestamped file in the `cw-api-logs/` directory (e.g., `cw-api-logs/2026-03-02T14-30-05.123Z.jsonl`).
### Enabling logging
```bash
# Via the dev:log shorthand script
bun run dev:log
# Or manually with any command
LOG_CW_API=1 bun run dev
```
### Log entry fields
| Field | Type | Description |
| ------------ | ----------------- | ----------------------------------- |
| `timestamp` | string (ISO-8601) | When the request completed |
| `method` | string | HTTP method |
| `url` | string | Request URL (relative or absolute) |
| `baseURL` | string | Axios baseURL |
| `status` | number \| null | HTTP status (null on network error) |
| `durationMs` | number | Wall-clock time in milliseconds |
| `error` | string \| null | Error code + message, if any |
| `timeout` | number | Configured timeout in ms |
### Analysis
Run the analyzer script to analyze the most recent log file:
```bash
bun run utils:analyze_cw
```
Or specify a particular file:
```bash
python3 debug-scripts/analyze-cw-calls.py cw-api-logs/2026-03-02T14-30-05.123Z.jsonl
```
This executes `debug-scripts/analyze-cw-calls.py` which produces:
- Overview (total calls, error rate, time span)
- Duration statistics (min, max, mean, p50, p90, p95, p99, distribution histogram)
- Error breakdown by type and endpoint
- Top 20 slowest calls
- Per-endpoint stats (count, errors, mean, p50, p95, max, total time)
- Timeline (per-minute throughput and errors)
- Concurrency hotspot detection
- Summary with recommendations
To clear all logs:
```bash
rm -rf cw-api-logs/
```
---
## Cache Invalidation
Mutation endpoints invalidate the relevant cache keys so the next read fetches fresh data from CW:
| Mutation | Cache invalidated |
| ------------------------------ | ---------------------------------------------------------------- |
| Create/update/delete note | `opp:notes:{cwOpportunityId}` via `invalidateNotesCache()` |
| Create/update/delete contact | `opp:contacts:{cwOpportunityId}` via `invalidateContactsCache()` |
| Add/update/resequence products | `opp:products:{cwOpportunityId}` via `invalidateProductsCache()` |
| Refresh opportunity | All keys for that opportunity (via re-fetch) |
---
## ConnectWise API Configuration
The shared Axios instance (`connectWiseApi`) is configured in `src/constants.ts`:
| Setting | Value | Purpose |
| --------- | ---------------------------------------------------- | ------------------------------ |
| `baseURL` | `https://ttscw.totaltech.net/v4_6_release/apis/3.0/` | CW API base |
| `timeout` | 30,000 ms (30s) | Per-request timeout |
| Logger | `attachCwApiLogger()` | Writes to `cw-api-calls.jsonl` |
---
## Architecture diagram
```
src/index.ts
├─ setInterval(refreshOpportunityCache, 20m)
└─► src/modules/cache/opportunityCache.ts
├─ prisma.opportunity.findMany(orderBy: cwLastUpdated DESC)
├─ redis.pipeline().exists(...) ← batch key check
├─ Build thunk list (lazy functions)
└─ Execute thunks with CONCURRENCY=6, DELAY=250ms
├─► fetchAndCacheOppCwData() ─► opportunityCw.fetch()
├─► fetchAndCacheActivities() ─► activityCw.fetchByOpportunityDirect()
├─► fetchAndCacheNotes() ─► opportunityCw.fetchNotes()
├─► fetchAndCacheContacts() ─► opportunityCw.fetchContacts()
├─► fetchAndCacheProducts() ─► opportunityCw.fetchProducts() + fetchProcurementProducts()
├─► fetchAndCacheCompanyCwData() ─► fetchCwCompanyById() + contacts
└─► fetchAndCacheSite() ─► fetchCompanySite() (lazy only)
└─► connectWiseApi.get(...) ← withCwRetry + cwApiLogger interceptors
└─► Redis SET with computed TTL
```
---
## File reference
| File | Purpose |
| ---------------------------------------------------------------- | ------------------------------------------------------------- |
| `src/modules/cache/opportunityCache.ts` | Cache read/write helpers, background refresh logic |
| `src/modules/algorithms/computeCacheTTL.ts` | Primary adaptive TTL algorithm |
| `src/modules/algorithms/computeSubResourceCacheTTL.ts` | Sub-resource (notes, contacts) TTL algorithm |
| `src/modules/algorithms/computeProductsCacheTTL.ts` | Products TTL algorithm |
| `src/modules/cw-utils/withCwRetry.ts` | Retry wrapper with exponential backoff |
| `src/modules/cw-utils/cwApiLogger.ts` | Axios interceptor for JSONL call logging |
| `src/modules/cw-utils/fetchCompany.ts` | Company fetch with retry |
| `src/modules/cw-utils/procurement/listenInventoryAdjustments.ts` | Adjustment listener for targeted catalog-item cache + DB sync |
| `src/constants.ts` | CW Axios instance config (timeout, logger) |
| `src/index.ts` | Refresh interval registration |
| `debug-scripts/analyze-cw-calls.py` | CW API call analysis script |
+57 -16
View File
@@ -1,32 +1,73 @@
FROM oven/bun:latest AS base
# ---- Stage 1: Install dependencies ----
FROM oven/bun:1 AS deps
WORKDIR /app
# Install dependencies
COPY package.json bun.lock ./
COPY patches ./patches
RUN bun install --frozen-lockfile --production
# ---- Stage 2: Build ----
FROM oven/bun:1 AS build
WORKDIR /app
# Copy dependency manifests and install all deps (including dev)
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
# Build the SvelteKit app with adapter-node
COPY . .
# Copy source code and supporting files
COPY src/ src/
COPY prisma/ prisma/
COPY prisma.config.ts tsconfig.json ./
ARG PUBLIC_API_URL=https://opt-api.osdci.net
ENV PUBLIC_API_URL=$PUBLIC_API_URL
# Generate Prisma client (dummy URL — generate only needs the schema, not a real DB)
RUN DATABASE_URL="postgresql://dummy:dummy@localhost:5432/dummy" bunx prisma generate
RUN bun run build:server
# Compile to a standalone executable
RUN NODE_ENV=production bun build src/index.ts \
--compile \
--minify \
--target=bun-linux-x64 \
--outfile=server
# Production image
FROM node:22-alpine AS production
# ---- Stage 3: Production image ----
FROM ubuntu:22.04 AS runtime
WORKDIR /app
COPY --from=base /app/build ./build
COPY --from=base /app/package.json ./
# Install minimal runtime dependencies (CA certs for HTTPS calls)
RUN apt-get update && \
apt-get install -y --no-install-recommends ca-certificates && \
rm -rf /var/lib/apt/lists/*
# Copy the compiled binary from the build stage
COPY --from=build /app/server ./server
# Copy Prisma artifacts needed at runtime
COPY --from=build /app/generated/ ./generated/
COPY --from=build /app/prisma/ ./prisma/
COPY --from=build /app/prisma.config.ts ./prisma.config.ts
# Copy production node_modules (Prisma adapter needs native bindings)
COPY --from=deps /app/node_modules/ ./node_modules/
ENV NODE_ENV=production
ENV PORT=3000
ENV ORIGIN=https://optima.osdci.net
EXPOSE 3000
CMD ["node", "build/index.js"]
CMD ["./server"]
# ---- Stage 4: Migration runner ----
FROM oven/bun:1 AS migration
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY prisma/ prisma/
COPY prisma.config.ts ./
COPY prisma/migrate-entrypoint.sh ./prisma/migrate-entrypoint.sh
RUN chmod +x prisma/migrate-entrypoint.sh
CMD ["sh", "prisma/migrate-entrypoint.sh"]
+148
View File
@@ -0,0 +1,148 @@
setInternalReview - The quote is ready to be review before it is ready to be sent.
setInternalApproved - The quote has been approved and is ready to be sent out.
setQuoteSent - The Quote has been sent to the customer.
setQuoteConfirmed - The quote has been recieved by the customer.
setRevisionNeeded - The quote needs to be revised and is set to stage revision
setFinalized - This locks any non-admins from modifying the quote saying that is the final iteration of the quote.
convert - This converts the quote to a ticket. It will also update all the necessary fields.
addTime(activityId, user: string)
fetchProducts
updateProduct
addProduct
fetchNotes
addNotes(note: string, user: string)
# Cat/SubCat/Bucket
## Ecosystems vs Categories
## Ecosystem Tree
- Networking
- Manufacturer: Ubiquiti
- Category: Technology
- Subcategory: Network-\*
- Manufacturer: TP-Link
- Category: Technology
- Subcategory: Network-\*
- Video Surveillance
- Manufacturer: Uniview
- Category: Field
- Subcategory: Surveillance-\*
- Manufacturer: Hikvision
- Category: Field
- Subcategory: Surveillance-\*
- Manufacturer: Alarm.com
- Category: Field
- Subcategory: Surveillance-\*
- Burg/Alarm
- Manufacturer: Qolsys
- Category: Field
- Subcategory: AlarmBurg-\*
- DSC
- Category: Field
- Subcategory: AlarmBurg-\*
## Category Tree
- Technology
- GeneralEquip
- Home Entertainment
- Monitor
- Printers
- Storage
- Network
- Network-Other
- Network-Router
- Network-Switch
- Network-Wireless
- Computer
- Computer-Components
- Computer-Desktop
- Computer-Laptop
- Recurring
- Recurring - Online
- Recurring - Other
- Recurring - Protection
- Recurring - Telephone
- Telephone
- Tele-HSet-Digital
- Tele-HSet-IP
- Tele-HSet-SLT
- Tele-Misc
- Tele-Paging
- Tele-SystemCards
- Tele-Systems
- General
- Batteries
- Battery Backups
- BulkWire
- Cables
- Cables-Adapters
- Cables-HDMI
- Cables-Network
- Cables-Other
- Cables-USB
- Cables-VGA
- Elec Cords & Adapters
- Enclosures
- PowerSupply
- RackEquip
- RackEquip-Rack
- RackEquip-Shelves
- Field
- Conduit
- Electric
- GateControl
- Locksets
- Other
- Relays
- AccessControl
- AccessControl-Controllers
- AccessControl-Credential
- AccessControl-LockDevices
- AccessControl-Other
- AccessControl-Readers
- AccessControl-VideoEntry
- AlarmBurg
- AlarmBurg-Communicators
- AlarmBurg-Keypads
- AlarmBurg-Modules
- AlarmBurg-Other
- AlarmBurg-Panels
- AlarmBurg-Sensors
- AlarmBurg-Sensors-Wireless
- AlarmBurg-Sensors-Wired
- AlarmBurg-Siren
- AlarmFire
- AlarmFire-Communicators
- AlarmFire-Devices
- AlarmFire-Modules
- AlarmFire-Other
- AlarmFire-Panels
- AlarmFire-Sensors
- Automation
- Automation-General
- Automation-HVAC
- Automation-Lights
- Automation-Locks
- Automation-Thermostat
- AV
- AV-Adapters&Cables
- AV-Components
- AV-Mounts
- AV-Other
- AV-Speakers
- AV-Television
- StrCbl?
- StrCbl-Jacks
- StrCbl-PatchPanel
- StrCbl-Plates
- Surveillance
- Surveillance-Accs
- Surveillance-CamerasAnalog
- Surveillance-CamerasIP
- Surveillance-NVR
+425
View File
@@ -0,0 +1,425 @@
# Permission Nodes
This document lists all known permission nodes in the optima-api application, categorized by resource type.
## Permission System Overview
The permission system uses a dot-notation format: `resource.action[.modifier]`
### Special Tokens
The permission validator supports special tokens for flexible permission management:
- **Asterisk (\*)**: Matches the token and all following tokens (e.g., `credential.*` grants all credential permissions)
- **Question Mark (?)**: Matches only the specific token (single character wildcard)
- **Inclusive List ([a,b,c])**: Matches only the tokens in the list
- **Exclusive List (<a,b,c>)**: Matches all tokens except those in the list
### Global Permissions
- `*` - Full access to all resources and actions (typically assigned to administrator role)
## Permission Nodes by Resource
### Company Permissions
| Permission Node | Description | Used In |
| ------------------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `company.fetch` | Fetch a single company | [src/api/companies/[id]/fetch.ts](src/api/companies/[id]/fetch.ts) |
| `company.fetch.address` | View company address information (requires `company.fetch` as well) | [src/api/companies/[id]/fetch.ts](src/api/companies/[id]/fetch.ts) |
| `company.fetch.contacts` | View all company contacts (requires `company.fetch` as well) | [src/api/companies/[id]/fetch.ts](src/api/companies/[id]/fetch.ts) |
| `company.fetch.many` | Fetch multiple companies | [src/api/companies/fetchAll.ts](src/api/companies/fetchAll.ts) |
| `company.fetch.configurations` | Fetch company configurations (requires `company.fetch` as well) | [src/api/companies/[id]/configurations.ts](src/api/companies/[id]/configurations.ts) |
### Credential Permissions
| Permission Node | Description | Used In |
| ----------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `credential.create` | Create a new credential | [src/api/credentials/create.ts](src/api/credentials/create.ts) |
| `credential.fetch` | Fetch a single credential | [src/api/credentials/fetch.ts](src/api/credentials/fetch.ts) |
| `credential.fetch.many` | Fetch multiple credentials | [src/api/credentials/fetchByCompany.ts](src/api/credentials/fetchByCompany.ts) |
| `credential.update` | Update a credential | [src/api/credentials/update.ts](src/api/credentials/update.ts) |
| `credential.delete` | Delete a credential | [src/api/credentials/delete.ts](src/api/credentials/delete.ts) |
| `credential.fields.fetch` | Fetch credential fields (requires `credential.fetch` as well) | [src/api/credentials/fetchFields.ts](src/api/credentials/fetchFields.ts) |
| `credential.fields.update` | Update credential fields (requires `credential.update` as well) | [src/api/credentials/updateFields.ts](src/api/credentials/updateFields.ts) |
| `credential.secure_values.read` | Read secure values of a credential (requires `credential.fetch` as well) | [src/api/credentials/readSecureValues.ts](src/api/credentials/readSecureValues.ts), [src/api/credentials/readSecureValue.ts](src/api/credentials/readSecureValue.ts) |
| `credential.sub_credentials.fetch` | Fetch sub-credentials of a parent credential (requires `credential.fetch` as well) | [src/api/credentials/fetchSubCredentials.ts](src/api/credentials/fetchSubCredentials.ts) |
| `credential.sub_credentials.create` | Create a sub-credential on a parent credential (requires `credential.fetch` as well) | [src/api/credentials/addSubCredential.ts](src/api/credentials/addSubCredential.ts) |
| `credential.sub_credentials.delete` | Remove a sub-credential from a parent credential (requires `credential.fetch` as well) | [src/api/credentials/removeSubCredential.ts](src/api/credentials/removeSubCredential.ts) |
### Credential Type Permissions
| Permission Node | Description | Used In |
| ---------------------------- | ------------------------------- | ---------------------------------------------------------------------------- |
| `credential_type.create` | Create a new credential type | [src/api/credential-types/create.ts](src/api/credential-types/create.ts) |
| `credential_type.fetch` | Fetch a single credential type | [src/api/credential-types/fetch.ts](src/api/credential-types/fetch.ts) |
| `credential_type.fetch.many` | Fetch multiple credential types | [src/api/credential-types/fetchAll.ts](src/api/credential-types/fetchAll.ts) |
| `credential_type.update` | Update a credential type | [src/api/credential-types/update.ts](src/api/credential-types/update.ts) |
| `credential_type.delete` | Delete a credential type | [src/api/credential-types/delete.ts](src/api/credential-types/delete.ts) |
### Role Permissions
| Permission Node | Description | Used In | Dependencies |
| --------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------ |
| `role.create` | Create a new role | [src/api/roles/create.ts](src/api/roles/create.ts) | |
| `role.read` | Fetch a single role or view role information | [src/api/roles/fetch.ts](src/api/roles/fetch.ts) | |
| `role.list` | Fetch all roles | [src/api/roles/fetchAll.ts](src/api/roles/fetchAll.ts) | `role.read` |
| `role.modify` | Update role properties or manage role permissions | [src/api/roles/update.ts](src/api/roles/update.ts), [src/api/roles/addPermissions.ts](src/api/roles/addPermissions.ts), [src/api/roles/removePermissions.ts](src/api/roles/removePermissions.ts) | |
| `role.delete` | Delete a role | [src/api/roles/delete.ts](src/api/roles/delete.ts) | |
| `user.read` | View users assigned to a role | [src/api/roles/getUsers.ts](src/api/roles/getUsers.ts) | `role.read` |
### User Permissions
| Permission Node | Description | Used In | Dependencies |
| ------------------------ | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `user.read` | Read user information | [src/api/user/@me/fetch.ts](src/api/user/@me/fetch.ts) | |
| `user.write` | Update user information | [src/api/user/@me/update.ts](src/api/user/@me/update.ts) | |
| `user.read.other` | Read other users' information | [src/api/user/fetch.ts](src/api/user/fetch.ts), [src/api/user/fetchRoles.ts](src/api/user/fetchRoles.ts), [src/api/user/checkPermission.ts](src/api/user/checkPermission.ts) | |
| `user.list.other` | List all users | [src/api/user/fetchAll.ts](src/api/user/fetchAll.ts) | `user.read.other` |
| `user.write.other` | Update other users' information | [src/api/user/update.ts](src/api/user/update.ts) | |
| `user.roles.other` | Modify roles assigned to other users | [src/api/user/update.ts](src/api/user/update.ts) | `user.write.other` |
| `user.permissions.other` | Modify direct permissions assigned to other users | [src/api/user/update.ts](src/api/user/update.ts) | `user.write.other` |
| `user.delete.other` | Delete other users | [src/api/user/delete.ts](src/api/user/delete.ts) | |
### Permission Routes
Permissions required for accessing the permission node definitions API.
| Permission Node | Description | Used In |
| --------------- | ------------------------------------------------ | -------------------------------------------------------------------------------- |
| `role.read` | Fetch all permission nodes organized by category | [src/api/permissions/fetchAll.ts](src/api/permissions/fetchAll.ts) |
| `role.read` | Fetch a flat list of all permission nodes | [src/api/permissions/fetchNodes.ts](src/api/permissions/fetchNodes.ts) |
| `role.read` | Fetch permission nodes by category | [src/api/permissions/fetchByCategory.ts](src/api/permissions/fetchByCategory.ts) |
### UI Navigation Permissions
Permissions for controlling navigation visibility on the frontend.
| Permission Node | Description | Usage Pattern |
| ---------------------- | -------------------------------------------------------------------- | ------------------------------------------------- |
| `ui.navigation.*.view` | View specific navigation sections (e.g., `ui.navigation.admin.view`) | Control which navigation menu items are displayed |
### Admin UI Permissions
Admin-specific UI permissions that control visibility and data loading for admin sub-tabs.
| Permission Node | Description | Usage Pattern |
| ----------------------------- | ------------------------------------------------ | ------------------------------------------ |
| `admin.users.view` | Show the Users tab and load user data | Show/hide users tab, allow user list fetch |
| `admin.roles.view` | Show the Roles tab and load role data | Show/hide roles tab, allow role list fetch |
| `admin.credential-types.view` | Show the Credential Types tab and load type data | Show/hide types tab, allow type list fetch |
#### Notes on UI Permissions
- **Client-side validation is not secure**: Always enforce permissions on the API level. UI permissions only control visibility and user experience.
- **Combine with API permissions**: A user with an admin UI permission should also have the corresponding API permission (e.g., `role.list`) to actually load data.
- **Use wildcards for flexibility**: Grant `ui.navigation.*.view` to allow all navigation sections.
### Procurement Permissions
| Permission Node | Description | Used In | Dependencies |
| --------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
| `procurement.catalog.fetch` | Fetch a single catalog item | [src/api/procurement/[id]/fetch.ts](src/api/procurement/[id]/fetch.ts) | |
| `procurement.catalog.fetch.many` | Fetch multiple catalog items, count, categories/ecosystems, or filter values | [src/api/procurement/fetchAll.ts](src/api/procurement/fetchAll.ts), [src/api/procurement/count.ts](src/api/procurement/count.ts), [src/api/procurement/categories.ts](src/api/procurement/categories.ts), [src/api/procurement/filters.ts](src/api/procurement/filters.ts) | |
| `procurement.catalog.inventory.refresh` | Refresh on-hand inventory for a catalog item from ConnectWise | [src/api/procurement/[id]/refreshInventory.ts](src/api/procurement/[id]/refreshInventory.ts) | `procurement.catalog.fetch` |
| `procurement.catalog.link` | Link or unlink catalog items to each other | [src/api/procurement/[id]/link.ts](src/api/procurement/[id]/link.ts), [src/api/procurement/[id]/unlink.ts](src/api/procurement/[id]/unlink.ts) | `procurement.catalog.fetch` |
### ConnectWise Callback Routes
`POST /v1/cw/callback/:secret/:resource` is intentionally unauthenticated for inbound ConnectWise callbacks and does **not** require a permission node.
| Permission Node | Description | Used In | Dependencies |
| --------------- | ------------------------------------------------------------------------------- | ------------------------------------------------ | ------------ |
| _None_ | Inbound callback route; secured operationally (network controls / source trust) | [src/api/cw/callback.ts](src/api/cw/callback.ts) | N/A |
### Sales Permissions
Permissions for accessing and managing sales opportunities. Opportunities are synced from ConnectWise and stored locally; sub-resources (products, notes, contacts) are fetched live from CW.
| Permission Node | Description | Used In | Dependencies |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------- |
| `sales.opportunity.fetch` | Fetch a single opportunity and its CW sub-resources (products, notes, contacts) | [src/api/sales/[id]/fetch.ts](src/api/sales/[id]/fetch.ts), [src/api/sales/[id]/products.ts](src/api/sales/[id]/products.ts), [src/api/sales/[id]/notes.ts](src/api/sales/[id]/notes.ts), [src/api/sales/[id]/fetchNote.ts](src/api/sales/[id]/fetchNote.ts), [src/api/sales/[id]/contacts.ts](src/api/sales/[id]/contacts.ts) | |
| `sales.opportunity.fetch.many` | Fetch multiple opportunities (paginated/searchable), count, or opportunity types | [src/api/sales/fetchAll.ts](src/api/sales/fetchAll.ts), [src/api/sales/count.ts](src/api/sales/count.ts), [src/api/sales/fetchOpportunityTypes.ts](src/api/sales/fetchOpportunityTypes.ts) | |
| `sales.opportunity.refresh` | Refresh a single opportunity's local data from ConnectWise | [src/api/sales/[id]/refresh.ts](src/api/sales/[id]/refresh.ts) | `sales.opportunity.fetch` |
| `sales.opportunity.note.create` | Create a new note on an opportunity | [src/api/sales/[id]/createNote.ts](src/api/sales/[id]/createNote.ts) | `sales.opportunity.fetch` |
| `sales.opportunity.note.update` | Update an existing note on an opportunity | [src/api/sales/[id]/updateNote.ts](src/api/sales/[id]/updateNote.ts) | `sales.opportunity.fetch` |
| `sales.opportunity.note.delete` | Delete a note from an opportunity | [src/api/sales/[id]/deleteNote.ts](src/api/sales/[id]/deleteNote.ts) | `sales.opportunity.fetch` |
| `sales.opportunity.product.update` | Update products (forecast items) on an opportunity, including resequencing | [src/api/sales/[id]/resequenceProducts.ts](src/api/sales/[id]/resequenceProducts.ts) | `sales.opportunity.fetch` |
| `sales.opportunity.product.add` | Add a new product (forecast item) to an opportunity. Individual fields gated by `sales.opportunity.product.field.<field>` permissions. | [src/api/sales/[id]/addProduct.ts](src/api/sales/[id]/addProduct.ts) | `sales.opportunity.fetch` |
<details>
<summary><strong>Field-level permissions for <code>sales.opportunity.product.add</code></strong></summary>
Each submitted field is gated by a `sales.opportunity.product.field.<field>` permission node. Only fields the user has permission for are forwarded to ConnectWise.
| Field Permission Node | Description |
| ----------------------------------------------------- | -------------------------------------------------------- |
| `sales.opportunity.product.field.catalogItem` | Set the catalog item reference |
| `sales.opportunity.product.field.forecastDescription` | Set the forecast description |
| `sales.opportunity.product.field.productDescription` | Set the product description |
| `sales.opportunity.product.field.quantity` | Set the quantity |
| `sales.opportunity.product.field.status` | Set the status reference |
| `sales.opportunity.product.field.productClass` | Set the product class (e.g. Product, Service, Agreement) |
| `sales.opportunity.product.field.forecastType` | Set the forecast type |
| `sales.opportunity.product.field.revenue` | Set the revenue amount |
| `sales.opportunity.product.field.cost` | Set the cost amount |
| `sales.opportunity.product.field.includeFlag` | Set the include flag |
| `sales.opportunity.product.field.linkFlag` | Set the link flag |
| `sales.opportunity.product.field.recurringFlag` | Set the recurring flag |
| `sales.opportunity.product.field.taxableFlag` | Set the taxable flag |
| `sales.opportunity.product.field.recurringRevenue` | Set the recurring revenue amount |
| `sales.opportunity.product.field.recurringCost` | Set the recurring cost amount |
| `sales.opportunity.product.field.cycles` | Set the number of recurring cycles |
| `sales.opportunity.product.field.sequenceNumber` | Set the sequence number (display order) |
</details>
### UniFi Permissions
Permissions for accessing and managing UniFi network infrastructure. The `unifi.access` permission is a gate permission required for **all** UniFi routes.
| Permission Node | Description | Used In | Dependencies |
| ------------------------------ | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |
| `unifi.access` | Gate permission for the entire UniFi API — required for all | [src/api/unifi/sites/fetchAll.ts](src/api/unifi/sites/fetchAll.ts), [src/api/unifi/sites/sync.ts](src/api/unifi/sites/sync.ts), [src/api/unifi/site/fetch.ts](src/api/unifi/site/fetch.ts), [src/api/unifi/site/overview.ts](src/api/unifi/site/overview.ts), [src/api/unifi/site/devices.ts](src/api/unifi/site/devices.ts), [src/api/unifi/site/wifi/fetchAll.ts](src/api/unifi/site/wifi/fetchAll.ts), [src/api/unifi/site/wifi/update.ts](src/api/unifi/site/wifi/update.ts), [src/api/unifi/site/networks.ts](src/api/unifi/site/networks.ts), [src/api/unifi/site/link.ts](src/api/unifi/site/link.ts), [src/api/unifi/site/unlink.ts](src/api/unifi/site/unlink.ts), [src/api/companies/[id]/unifiSites.ts](src/api/companies/[id]/unifiSites.ts), [src/api/unifi/sites/create.ts](src/api/unifi/sites/create.ts) | |
| `unifi.sites.create` | Create a new site on the UniFi controller | [src/api/unifi/sites/create.ts](src/api/unifi/sites/create.ts) | `unifi.access` |
| `unifi.sites.fetch` | Fetch a single UniFi site | [src/api/unifi/site/fetch.ts](src/api/unifi/site/fetch.ts) | `unifi.access` |
| `unifi.sites.fetch.many` | Fetch all UniFi sites | [src/api/unifi/sites/fetchAll.ts](src/api/unifi/sites/fetchAll.ts) | `unifi.access` |
| `unifi.sites.sync` | Sync sites from the UniFi controller into the database | [src/api/unifi/sites/sync.ts](src/api/unifi/sites/sync.ts) | `unifi.access` |
| `unifi.sites.link` | Link or unlink a UniFi site to/from a company | [src/api/unifi/site/link.ts](src/api/unifi/site/link.ts), [src/api/unifi/site/unlink.ts](src/api/unifi/site/unlink.ts) | `unifi.access` |
| `unifi.site.overview` | View live site overview from the UniFi controller | [src/api/unifi/site/overview.ts](src/api/unifi/site/overview.ts) | `unifi.access` |
| `unifi.site.devices` | View live device list from the UniFi controller | [src/api/unifi/site/devices.ts](src/api/unifi/site/devices.ts) | `unifi.access` |
| `unifi.site.wifi` | View WiFi networks (WLANs) from the UniFi controller | [src/api/unifi/site/wifi/fetchAll.ts](src/api/unifi/site/wifi/fetchAll.ts) | `unifi.access` |
| `unifi.site.wifi.read` | Field-level gate for WiFi response data (see note below) | [src/api/unifi/site/wifi/fetchAll.ts](src/api/unifi/site/wifi/fetchAll.ts) | `unifi.access`, `unifi.site.wifi` |
| `unifi.site.wifi.read.<field>` | Read a specific field from WiFi response (e.g. `unifi.site.wifi.read.passphrase`) | [src/api/unifi/site/wifi/fetchAll.ts](src/api/unifi/site/wifi/fetchAll.ts) | `unifi.access`, `unifi.site.wifi`, `unifi.site.wifi.read` |
| `unifi.site.wifi.update` | Update a WiFi network on the UniFi controller | [src/api/unifi/site/wifi/update.ts](src/api/unifi/site/wifi/update.ts) | `unifi.access`, `unifi.site.wifi` |
#### Field-Level Permission Gating (`unifi.site.wifi.read`)
The WiFi fetch route uses `processObjectValuePerms` to filter each WLAN object on a per-field basis. For every key on the `WlanConf` response object, the system checks `unifi.site.wifi.read.<key>`. Only fields the user has permission for are included in the response. Use `unifi.site.wifi.read.*` to grant access to all fields.
**Available field-level nodes:**
`unifi.site.wifi.read.id`, `unifi.site.wifi.read.name`, `unifi.site.wifi.read.siteId`, `unifi.site.wifi.read.enabled`, `unifi.site.wifi.read.security`, `unifi.site.wifi.read.wpaMode`, `unifi.site.wifi.read.wpaEnc`, `unifi.site.wifi.read.wpa3Support`, `unifi.site.wifi.read.wpa3Transition`, `unifi.site.wifi.read.wpa3FastRoaming`, `unifi.site.wifi.read.wpa3Enhanced192`, `unifi.site.wifi.read.passphrase`, `unifi.site.wifi.read.passphraseAutogenerated`, `unifi.site.wifi.read.hideSSID`, `unifi.site.wifi.read.isGuest`, `unifi.site.wifi.read.band`, `unifi.site.wifi.read.bands`, `unifi.site.wifi.read.networkconfId`, `unifi.site.wifi.read.usergroupId`, `unifi.site.wifi.read.apGroupIds`, `unifi.site.wifi.read.apGroupMode`, `unifi.site.wifi.read.pmfMode`, `unifi.site.wifi.read.groupRekey`, `unifi.site.wifi.read.dtimMode`, `unifi.site.wifi.read.dtimNg`, `unifi.site.wifi.read.dtimNa`, `unifi.site.wifi.read.dtim6e`, `unifi.site.wifi.read.l2Isolation`, `unifi.site.wifi.read.fastRoamingEnabled`, `unifi.site.wifi.read.bssTransition`, `unifi.site.wifi.read.uapsdEnabled`, `unifi.site.wifi.read.iappEnabled`, `unifi.site.wifi.read.proxyArp`, `unifi.site.wifi.read.mcastenhanceEnabled`, `unifi.site.wifi.read.macFilterEnabled`, `unifi.site.wifi.read.macFilterPolicy`, `unifi.site.wifi.read.macFilterList`, `unifi.site.wifi.read.radiusDasEnabled`, `unifi.site.wifi.read.radiusMacAuthEnabled`, `unifi.site.wifi.read.radiusMacaclFormat`, `unifi.site.wifi.read.minrateSettingPreference`, `unifi.site.wifi.read.minrateNgEnabled`, `unifi.site.wifi.read.minrateNgDataRateKbps`, `unifi.site.wifi.read.minrateNgAdvertisingRates`, `unifi.site.wifi.read.minrateNaEnabled`, `unifi.site.wifi.read.minrateNaDataRateKbps`, `unifi.site.wifi.read.minrateNaAdvertisingRates`, `unifi.site.wifi.read.settingPreference`, `unifi.site.wifi.read.no2ghzOui`, `unifi.site.wifi.read.privatePreSharedKeysEnabled`, `unifi.site.wifi.read.privatePreSharedKeys`, `unifi.site.wifi.read.saeGroups`, `unifi.site.wifi.read.saePsk`, `unifi.site.wifi.read.schedule`, `unifi.site.wifi.read.scheduleWithDuration`, `unifi.site.wifi.read.bcFilterList`, `unifi.site.wifi.read.externalId`
| `unifi.site.networks` | View network configurations from the UniFi controller | [src/api/unifi/site/networks.ts](src/api/unifi/site/networks.ts) | `unifi.access` |
| `unifi.site.wlan-groups` | View WLAN groups (AP broadcasting groups) from the UniFi controller for a site | [src/api/unifi/site/wlanGroups.ts](src/api/unifi/site/wlanGroups.ts), [src/api/unifi/site/wlanGroupsCreate.ts](src/api/unifi/site/wlanGroupsCreate.ts) | `unifi.access` |
| `unifi.site.wlan-groups.create` | Create a new WLAN group (AP broadcasting group) on the UniFi controller | [src/api/unifi/site/wlanGroupsCreate.ts](src/api/unifi/site/wlanGroupsCreate.ts) | `unifi.access`, `unifi.site.wlan-groups` |
| `unifi.site.access-points` | View access points (UAPs only) from the UniFi controller for a site | [src/api/unifi/site/accessPoints.ts](src/api/unifi/site/accessPoints.ts) | `unifi.access` |
| `unifi.site.ap-groups` | View AP groups — shows which APs are grouped together for SSID broadcasting | [src/api/unifi/site/apGroups.ts](src/api/unifi/site/apGroups.ts) | `unifi.access` |
| `unifi.site.wifi-limits` | View WiFi SSID limits per AP per radio band | [src/api/unifi/site/wifiLimits.ts](src/api/unifi/site/wifiLimits.ts) | `unifi.access` |
| `unifi.site.speed-profiles` | View speed limit profiles (user groups) from the UniFi controller | [src/api/unifi/site/speedProfilesFetchAll.ts](src/api/unifi/site/speedProfilesFetchAll.ts), [src/api/unifi/site/speedProfilesCreate.ts](src/api/unifi/site/speedProfilesCreate.ts) | `unifi.access` |
| `unifi.site.speed-profiles.create` | Create a new speed limit profile (user group) on the UniFi controller | [src/api/unifi/site/speedProfilesCreate.ts](src/api/unifi/site/speedProfilesCreate.ts) | `unifi.access`, `unifi.site.speed-profiles` |
| `unifi.site.wifi.ppsk` | View private pre-shared keys (PPSKs) for a specific WiFi network | [src/api/unifi/site/wifi/ppskFetchAll.ts](src/api/unifi/site/wifi/ppskFetchAll.ts), [src/api/unifi/site/wifi/ppskCreate.ts](src/api/unifi/site/wifi/ppskCreate.ts) | `unifi.access`, `unifi.site.wifi` |
| `unifi.site.wifi.ppsk.create` | Create a private pre-shared key on a specific WiFi network | [src/api/unifi/site/wifi/ppskCreate.ts](src/api/unifi/site/wifi/ppskCreate.ts) | `unifi.access`, `unifi.site.wifi`, `unifi.site.wifi.ppsk` |
---
## Object Type Permissions (Field-Level Gating)
All fetch and fetchAll routes gate response object keys using `processObjectValuePerms`. For each object type, only fields whose corresponding `<scope>.<field>` permission the user holds are included in the response. Grant `<scope>.*` to allow all fields on that object type.
### Company (`obj.company`)
| Field Permission | Description |
| --------------------------- | ----------------------------------------- |
| `obj.company.id` | View company ID |
| `obj.company.name` | View company name |
| `obj.company.cw_Identifier` | View ConnectWise identifier |
| `obj.company.cw_CompanyId` | View ConnectWise company ID |
| `obj.company.cw_Data` | View ConnectWise data (address, contacts) |
| `obj.company.createdAt` | View creation timestamp |
| `obj.company.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/companies/[id]/fetch.ts](src/api/companies/[id]/fetch.ts), [src/api/companies/fetchAll.ts](src/api/companies/fetchAll.ts)
### Credential (`obj.credential`)
| Field Permission | Description |
| ---------------------------------- | ----------------------------- |
| `obj.credential.id` | View credential ID |
| `obj.credential.name` | View credential name |
| `obj.credential.notes` | View credential notes |
| `obj.credential.typeId` | View credential type ID |
| `obj.credential.companyId` | View linked company ID |
| `obj.credential.subCredentialOfId` | View parent credential ID |
| `obj.credential.fields` | View credential field values |
| `obj.credential.type` | View credential type object |
| `obj.credential.company` | View linked company object |
| `obj.credential.subCredentials` | View sub-credentials array |
| `obj.credential.secureFieldIds` | View secure field identifiers |
| `obj.credential.createdAt` | View creation timestamp |
| `obj.credential.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/credentials/fetch.ts](src/api/credentials/fetch.ts), [src/api/credentials/fetchByCompany.ts](src/api/credentials/fetchByCompany.ts), [src/api/credentials/fetchSubCredentials.ts](src/api/credentials/fetchSubCredentials.ts), [src/api/credential-types/fetchCredentials.ts](src/api/credential-types/fetchCredentials.ts)
### Credential Type (`obj.credentialType`)
| Field Permission | Description |
| ------------------------------------ | ----------------------------------------- |
| `obj.credentialType.id` | View credential type ID |
| `obj.credentialType.name` | View credential type name |
| `obj.credentialType.permissionScope` | View permission scope |
| `obj.credentialType.icon` | View icon |
| `obj.credentialType.fields` | View field definitions |
| `obj.credentialType.credentialCount` | View count of credentials using this type |
| `obj.credentialType.createdAt` | View creation timestamp |
| `obj.credentialType.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/credential-types/fetch.ts](src/api/credential-types/fetch.ts), [src/api/credential-types/fetchAll.ts](src/api/credential-types/fetchAll.ts)
### User (`obj.user`)
| Field Permission | Description |
| ---------------------- | -------------------------------- |
| `obj.user.id` | View user ID |
| `obj.user.name` | View user display name |
| `obj.user.roles` | View assigned role monikers |
| `obj.user.permissions` | View aggregated permission nodes |
| `obj.user.login` | View login identifier |
| `obj.user.email` | View email address |
| `obj.user.image` | View profile image URL |
| `obj.user.createdAt` | View creation timestamp |
| `obj.user.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/user/@me/fetch.ts](src/api/user/@me/fetch.ts), [src/api/user/fetch.ts](src/api/user/fetch.ts), [src/api/user/fetchAll.ts](src/api/user/fetchAll.ts), [src/api/roles/getUsers.ts](src/api/roles/getUsers.ts)
### Role (`obj.role`)
| Field Permission | Description |
| ---------------------- | -------------------------------- |
| `obj.role.id` | View role ID |
| `obj.role.title` | View role title |
| `obj.role.moniker` | View role moniker |
| `obj.role.permissions` | View role permission nodes |
| `obj.role.users` | View users assigned to this role |
| `obj.role.createdAt` | View creation timestamp |
| `obj.role.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/roles/fetch.ts](src/api/roles/fetch.ts), [src/api/roles/fetchAll.ts](src/api/roles/fetchAll.ts), [src/api/user/fetchRoles.ts](src/api/user/fetchRoles.ts)
### Catalog Item (`obj.catalogItem`)
| Field Permission | Description |
| ------------------------------------- | -------------------------------- |
| `obj.catalogItem.id` | View catalog item ID |
| `obj.catalogItem.cwCatalogId` | View ConnectWise catalog ID |
| `obj.catalogItem.identifier` | View item identifier |
| `obj.catalogItem.name` | View item name |
| `obj.catalogItem.description` | View description |
| `obj.catalogItem.customerDescription` | View customer-facing description |
| `obj.catalogItem.internalNotes` | View internal notes |
| `obj.catalogItem.manufacturer` | View manufacturer name |
| `obj.catalogItem.manufactureCwId` | View manufacturer ConnectWise ID |
| `obj.catalogItem.partNumber` | View part number |
| `obj.catalogItem.vendorName` | View vendor name |
| `obj.catalogItem.vendorSku` | View vendor SKU |
| `obj.catalogItem.vendorCwId` | View vendor ConnectWise ID |
| `obj.catalogItem.price` | View price |
| `obj.catalogItem.cost` | View cost |
| `obj.catalogItem.inactive` | View inactive flag |
| `obj.catalogItem.salesTaxable` | View sales-taxable flag |
| `obj.catalogItem.onHand` | View on-hand inventory count |
| `obj.catalogItem.cwLastUpdated` | View CW last-updated timestamp |
| `obj.catalogItem.linkedItems` | View linked catalog items |
| `obj.catalogItem.createdAt` | View creation timestamp |
| `obj.catalogItem.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/procurement/fetchAll.ts](src/api/procurement/fetchAll.ts), [src/api/procurement/[id]/fetch.ts](src/api/procurement/[id]/fetch.ts), [src/api/procurement/[id]/fetchLinked.ts](src/api/procurement/[id]/fetchLinked.ts)
### Opportunity (`obj.opportunity`)
| Field Permission | Description |
| ------------------------------------ | ------------------------------- |
| `obj.opportunity.id` | View opportunity ID |
| `obj.opportunity.cwOpportunityId` | View ConnectWise opportunity ID |
| `obj.opportunity.name` | View opportunity name |
| `obj.opportunity.notes` | View notes |
| `obj.opportunity.type` | View opportunity type |
| `obj.opportunity.stage` | View stage |
| `obj.opportunity.status` | View status |
| `obj.opportunity.priority` | View priority |
| `obj.opportunity.rating` | View rating |
| `obj.opportunity.source` | View source |
| `obj.opportunity.campaign` | View campaign |
| `obj.opportunity.primarySalesRep` | View primary sales rep |
| `obj.opportunity.secondarySalesRep` | View secondary sales rep |
| `obj.opportunity.company` | View company |
| `obj.opportunity.contact` | View contact |
| `obj.opportunity.site` | View site |
| `obj.opportunity.customerPO` | View customer PO |
| `obj.opportunity.totalSalesTax` | View total sales tax |
| `obj.opportunity.location` | View location |
| `obj.opportunity.department` | View department |
| `obj.opportunity.expectedCloseDate` | View expected close date |
| `obj.opportunity.pipelineChangeDate` | View pipeline change date |
| `obj.opportunity.dateBecameLead` | View date became lead |
| `obj.opportunity.closedDate` | View closed date |
| `obj.opportunity.closedFlag` | View closed flag |
| `obj.opportunity.closedBy` | View closed-by member |
| `obj.opportunity.companyId` | View linked company ID |
| `obj.opportunity.cwLastUpdated` | View CW last-updated timestamp |
| `obj.opportunity.createdAt` | View creation timestamp |
| `obj.opportunity.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/sales/fetchAll.ts](src/api/sales/fetchAll.ts), [src/api/sales/[id]/fetch.ts](src/api/sales/[id]/fetch.ts)
### UniFi Site (`obj.unifiSite`)
| Field Permission | Description |
| ------------------------- | ----------------------------- |
| `obj.unifiSite.id` | View site internal ID |
| `obj.unifiSite.name` | View site name |
| `obj.unifiSite.siteId` | View UniFi controller site ID |
| `obj.unifiSite.companyId` | View linked company ID |
| `obj.unifiSite.company` | View linked company object |
| `obj.unifiSite.createdAt` | View creation timestamp |
| `obj.unifiSite.updatedAt` | View last-updated timestamp |
**Used in:** [src/api/unifi/sites/fetchAll.ts](src/api/unifi/sites/fetchAll.ts), [src/api/unifi/site/fetch.ts](src/api/unifi/site/fetch.ts), [src/api/companies/[id]/unifiSites.ts](src/api/companies/[id]/unifiSites.ts)
### WiFi Network (`unifi.site.wifi.read`)
See **UniFi Permissions > Field-Level Permission Gating** above for the full list of `unifi.site.wifi.read.<field>` nodes.
---
## Permission Issuers
Permissions can be issued by different sources:
- `roles` - Permissions granted through role assignment
- `user` - Permissions granted directly to a user
- `api_key` - Permissions associated with an API key
## Permission Validation
The authorization middleware ([src/api/middleware/authorization.ts](src/api/middleware/authorization.ts)) enforces permissions by:
1. Extracting the authorization header (Bearer token or API Key)
2. Validating the session/token
3. Checking if the user has all required permissions for the route
4. Throwing an `InsufficentPermission` error (403) if any required permission is missing
## Usage Example
```typescript
// Require single permission
authMiddleware({ permissions: ["credential.fetch"] })
// Require multiple permissions (all must be satisfied)
authMiddleware({
permissions: ["credential.fetch", "credential.secure_values.read"]
})
// Administrator role with wildcard permission
{
moniker: "administrator",
permissions: ["*"] // Grants all permissions
}
```
## Notes
- Multiple permissions in a single route require **all** permissions to be satisfied (AND logic)
- The `*` wildcard permission grants access to everything in the application
- Permissions are signed using JWT with a private key for integrity
- Permission validation supports pattern matching for flexible permission management
+2 -116
View File
@@ -1,116 +1,2 @@
# SveltronKit
A minimal template for building Electron apps with SvelteKit.
Includes native support for Typscript and uses Electron's official recommended Electron Forge for packaging.
Everything you can do in SvelteKit, you can do in SveltronKit; meaning that you can use component
libraries like [Shadcn-Svelte](https://next.shadcn-svelte.com/).
> [!IMPORTANT]
> This template uses SvelteKit's [hash router](https://svelte.dev/docs/kit/configuration#router) to
> create a single-page app. The only difference you'll have to look out for is to start all your routed
> links with `#/` instead of `/`.
## Dependencies & Frameworks
- [SvelteKit](https://kit.svelte.dev/)
- [Electron](https://www.electronjs.org/)
- [Electron Forge](https://www.electronforge.io/)
- [TypeScript](https://www.typescriptlang.org/)
- [TailwindCSS](https://tailwindcss.com/)
> [!NOTE]
> I've included TailwindCSS in this template because I use it in my own projects, but you can remove
> it easily if you don't want it.
## Getting Started
> [!WARNING]
> This project uses [`bun`](https://bun.sh/) and uses [patching](https://bun.sh/docs/install/patch) to work
> around some issues with SvelteKit. When this [PR](https://github.com/sveltejs/kit/pull/13812) merges,
> you can remove the patching and use the latest version of SvelteKit.
Start by installing the dependencies:
```
bun install
```
**Development:**
```
bun start
```
[Electron Forge](https://www.electronforge.io/) with the [Vite plugin](https://www.electronforge.io/plugins/vite)
will take care of running the development server and building the app for you. You don't need to run
`vite dev` or `vite build` yourself. This also means that it supports hot module replacement (HMR).
**Production:**
```
bun run package
```
This will build the app and you can find the output in the `out` directory. You can run the production
app by opening the `.app` file in the `out` directory. This will not create your app's installer
for distribution though.
To create a distributable installer, you can use:
```
bun run make
```
This will create a distributable installer for your app. You can configure this in the `makers` section
in `forge.config.ts`. Reference the [makers documentation](https://www.electronforge.io/makers) for more
information.
# Electron Crash Course
> [!NOTE]
> This is a super simplified version of the Electron documentation meant to give you a general idea
> of how Electron works and how each file corresponds to responsibilities in Electron. For a more
> accurate description of how Electron works, you can refer to the [official documentation](https://www.electronjs.org/docs).
I found that most of the problems I encountered when setting up Electron were because I didn't know
how Electron works and that the documentation was too dense to get up to speed with, so I'll include
a crash course here. _I will be making a lot of analogies to web development_ as it seems like a lot
of people who are new to Electron come from web development.
Because everything in Electron is client based, you'll need to host your own server if you want to
access any sensitive logic like a database or authentication, etc.
## main.ts
This file defines what the main process will do. The process runs your app. It's the one that
creates and manages windows and also has permissions to access the file system. You also define
"_signals_"/"_endpoints_", through IPC, that let the renderer process (browser that runs your app)
can "_call_" to interact with the file system.
By default, Electron will block off file system access to the renderer process as a security measure,
which is the reason why you need to use IPC to interact with the file system.
## preload.ts
Think about this as a "bridge" or a "network"/"proxy" between the main process and the renderer process.
You specify what functions that the renderer process can call and these functions will usually be
interacting with the file system through the main process.
## renderer
The renderer process is the browser that runs your app. Just treat this like another SvelteKit app.
## Overview
```mermaid
flowchart LR
subgraph main[Main Process]
electron
end
subgraph renderer[Renderer Process]
browser
end
electron <-- preload --> renderer
```
# ttsci-api
The Api for the TTS Credentials Manager
+21
View File
@@ -0,0 +1,21 @@
meta {
name: Check User Permission
type: http
seq: 3
}
post {
url: {{baseUrl}}/v1/user/@me/check-permission
body: json
auth: none
}
headers {
Content-Type: application/json
}
body:json {
{
"permissions": ["user.read", "company.create", "credential.write"]
}
}
+15
View File
@@ -0,0 +1,15 @@
meta {
name: Fetch Company Pages.
type: http
seq: 2
}
get {
url:
body: none
auth: inherit
}
settings {
encodeUrl: true
}
+15
View File
@@ -0,0 +1,15 @@
meta {
name: Teapot
type: http
seq: 1
}
get {
url: http://localhost:3000/v1/teapot
body: none
auth: inherit
}
settings {
encodeUrl: true
}
+9
View File
@@ -0,0 +1,9 @@
{
"version": "1",
"name": "optima",
"type": "collection",
"ignore": [
"node_modules",
".git"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"version": "1",
"name": "optima",
"type": "collection",
"ignore": ["node_modules", ".git"]
}
+176 -1541
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
[test]
preload = ["./tests/setup.ts"]
+307
View File
@@ -0,0 +1,307 @@
#!/usr/bin/env python3
"""
Analyze ConnectWise API call logs.
Looks for the most recent log file in cw-api-logs/ by default,
or accepts an explicit path as an argument.
Usage:
python3 analyze-cw-calls.py # latest file in cw-api-logs/
python3 analyze-cw-calls.py cw-api-logs/specific.jsonl
"""
import json
import sys
import os
import glob
import statistics
from collections import Counter, defaultdict
from datetime import datetime, timedelta
# ── Colours ──────────────────────────────────────────────────────────────────
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
def colour_duration(ms: float) -> str:
if ms >= 10_000:
return f"{RED}{ms:,.0f}ms{RESET}"
if ms >= 5_000:
return f"{YELLOW}{ms:,.0f}ms{RESET}"
return f"{GREEN}{ms:,.0f}ms{RESET}"
def header(title: str) -> str:
return f"\n{BOLD}{CYAN}{'' * 60}\n {title}\n{'' * 60}{RESET}"
# ── Resolve log file ────────────────────────────────────────────────────────
def find_latest_log() -> str:
"""Find the most recent .jsonl file in cw-api-logs/."""
log_dir = os.path.join(os.getcwd(), "cw-api-logs")
files = sorted(glob.glob(os.path.join(log_dir, "*.jsonl")))
if not files:
print(f"{RED}No log files found in cw-api-logs/{RESET}")
print(f"Run {BOLD}bun run dev:log{RESET} to start logging CW API calls.")
sys.exit(1)
return files[-1]
if len(sys.argv) > 1:
log_path = sys.argv[1]
else:
log_path = find_latest_log()
print(f"{DIM}Reading: {log_path}{RESET}")
entries = []
parse_errors = 0
with open(log_path) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
entries.append(json.loads(line))
except json.JSONDecodeError:
parse_errors += 1
if not entries:
print("No entries found. Check the log file path.")
sys.exit(1)
# ── Derived fields ───────────────────────────────────────────────────────────
durations = [e["durationMs"] for e in entries]
errors = [e for e in entries if e.get("error")]
successes = [e for e in entries if not e.get("error")]
timestamps = [datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00")) for e in entries]
time_span = (timestamps[-1] - timestamps[0]) if len(timestamps) > 1 else timedelta(0)
# Normalise the URL to a route pattern for grouping
def normalise_url(url: str) -> str:
parts = url.split("?")[0].rstrip("/").split("/")
normalised = []
for p in parts:
if p.isdigit():
normalised.append(":id")
else:
normalised.append(p)
return "/".join(normalised)
# ── 1. Overview ──────────────────────────────────────────────────────────────
print(header("OVERVIEW"))
print(f" Log file : {log_path}")
print(f" Total calls : {BOLD}{len(entries):,}{RESET}")
print(f" Successes : {GREEN}{len(successes):,}{RESET}")
print(f" Failures : {RED}{len(errors):,}{RESET} ({len(errors)/len(entries)*100:.1f}%)")
print(f" Time span : {time_span}")
if time_span.total_seconds() > 0:
rps = len(entries) / time_span.total_seconds()
print(f" Avg req/sec : {rps:.2f}")
if parse_errors:
print(f" Parse errors : {YELLOW}{parse_errors}{RESET}")
# ── 2. Duration stats ───────────────────────────────────────────────────────
print(header("DURATION STATS (all calls)"))
sorted_dur = sorted(durations)
p50 = sorted_dur[len(sorted_dur) * 50 // 100]
p90 = sorted_dur[len(sorted_dur) * 90 // 100]
p95 = sorted_dur[len(sorted_dur) * 95 // 100]
p99 = sorted_dur[len(sorted_dur) * 99 // 100]
print(f" Min : {colour_duration(min(durations))}")
print(f" Max : {colour_duration(max(durations))}")
print(f" Mean : {colour_duration(statistics.mean(durations))}")
print(f" Median (p50) : {colour_duration(p50)}")
print(f" p90 : {colour_duration(p90)}")
print(f" p95 : {colour_duration(p95)}")
print(f" p99 : {colour_duration(p99)}")
print(f" Std dev : {statistics.stdev(durations):,.0f}ms" if len(durations) > 1 else "")
# Duration buckets
buckets = {"<500ms": 0, "500ms-1s": 0, "1-3s": 0, "3-5s": 0, "5-10s": 0, "10-20s": 0, "20s+": 0}
for d in durations:
if d < 500: buckets["<500ms"] += 1
elif d < 1000: buckets["500ms-1s"] += 1
elif d < 3000: buckets["1-3s"] += 1
elif d < 5000: buckets["3-5s"] += 1
elif d < 10000: buckets["5-10s"] += 1
elif d < 20000: buckets["10-20s"] += 1
else: buckets["20s+"] += 1
print(f"\n {BOLD}Distribution:{RESET}")
max_bar = 40
max_count = max(buckets.values()) if buckets else 1
for label, count in buckets.items():
bar_len = int(count / max_count * max_bar) if max_count else 0
pct = count / len(durations) * 100
bar = "" * bar_len
clr = GREEN if "500" in label or "<" in label else (YELLOW if "1-3" in label or "3-5" in label else RED)
print(f" {label:>10s} {clr}{bar}{RESET} {count:>5,} ({pct:5.1f}%)")
# ── 3. Errors breakdown ─────────────────────────────────────────────────────
print(header("ERROR BREAKDOWN"))
if not errors:
print(f" {GREEN}No errors! 🎉{RESET}")
else:
error_codes = Counter()
for e in errors:
err_str = e.get("error", "unknown")
code = err_str.split(":")[0] if ":" in err_str else err_str
error_codes[code] += 1
for code, count in error_codes.most_common():
print(f" {RED}{code:<30s}{RESET} {count:>5,} ({count/len(entries)*100:.1f}%)")
# Errored URLs
errored_urls = Counter(normalise_url(e["url"]) for e in errors)
print(f"\n {BOLD}Top errored endpoints:{RESET}")
for url, count in errored_urls.most_common(10):
print(f" {count:>5,} {url}")
# ── 4. Slowest individual calls ─────────────────────────────────────────────
print(header("TOP 20 SLOWEST CALLS"))
slowest = sorted(entries, key=lambda e: e["durationMs"], reverse=True)[:20]
for i, e in enumerate(slowest, 1):
status = e.get("status") or f"{RED}ERR{RESET}"
err_tag = f" {RED}[{e['error'].split(':')[0]}]{RESET}" if e.get("error") else ""
print(f" {i:>2}. {colour_duration(e['durationMs']):>20s} {e['method']:>4s} {e['url'][:60]:<60s} {DIM}{status}{RESET}{err_tag}")
# ── 5. Per-endpoint stats ───────────────────────────────────────────────────
print(header("PER-ENDPOINT STATS (by route pattern)"))
by_route = defaultdict(list)
for e in entries:
route = normalise_url(e["url"])
by_route[route].append(e)
# Sort by total time spent descending (most impactful)
route_stats = []
for route, calls in by_route.items():
durs = [c["durationMs"] for c in calls]
errs = sum(1 for c in calls if c.get("error"))
sorted_d = sorted(durs)
route_stats.append({
"route": route,
"count": len(calls),
"errors": errs,
"total_ms": sum(durs),
"mean": statistics.mean(durs),
"p50": sorted_d[len(sorted_d) * 50 // 100],
"p95": sorted_d[len(sorted_d) * 95 // 100],
"max": max(durs),
})
route_stats.sort(key=lambda r: r["total_ms"], reverse=True)
print(f" {'Route':<55s} {'Count':>6s} {'Errs':>5s} {'Mean':>8s} {'p50':>8s} {'p95':>8s} {'Max':>8s} {'Total':>10s}")
print(f" {'' * 55} {'' * 6} {'' * 5} {'' * 8} {'' * 8} {'' * 8} {'' * 8} {'' * 10}")
for r in route_stats[:25]:
err_str = f"{RED}{r['errors']}{RESET}" if r['errors'] else f"{DIM}0{RESET}"
print(
f" {r['route']:<55s} {r['count']:>6,} {err_str:>14s} "
f"{r['mean']:>7,.0f}ms {r['p50']:>7,.0f}ms {r['p95']:>7,.0f}ms "
f"{r['max']:>7,.0f}ms {r['total_ms']/1000:>8,.1f}s"
)
# ── 6. HTTP method breakdown ────────────────────────────────────────────────
print(header("BY HTTP METHOD"))
by_method = defaultdict(list)
for e in entries:
by_method[e["method"]].append(e["durationMs"])
print(f" {'Method':<8s} {'Count':>7s} {'Mean':>9s} {'p95':>9s} {'Max':>9s}")
print(f" {'' * 8} {'' * 7} {'' * 9} {'' * 9} {'' * 9}")
for method in sorted(by_method.keys()):
durs = by_method[method]
sd = sorted(durs)
print(
f" {method:<8s} {len(durs):>7,} "
f"{statistics.mean(durs):>8,.0f}ms "
f"{sd[len(sd)*95//100]:>8,.0f}ms "
f"{max(durs):>8,.0f}ms"
)
# ── 7. Timeline (calls per minute) ──────────────────────────────────────────
if time_span.total_seconds() > 60:
print(header("TIMELINE (per-minute throughput & errors)"))
by_minute = defaultdict(lambda: {"count": 0, "errors": 0, "dur_sum": 0})
for e in entries:
ts = e["timestamp"][:16] # YYYY-MM-DDTHH:MM
by_minute[ts]["count"] += 1
by_minute[ts]["dur_sum"] += e["durationMs"]
if e.get("error"):
by_minute[ts]["errors"] += 1
for minute in sorted(by_minute.keys()):
m = by_minute[minute]
avg = m["dur_sum"] / m["count"] if m["count"] else 0
err_part = f" {RED}({m['errors']} errs){RESET}" if m["errors"] else ""
bar = "" * min(m["count"] // 5, 50)
avg_clr = colour_duration(avg)
print(f" {minute} {m['count']:>5,} reqs avg {avg_clr:>20s} {bar}{err_part}")
# ── 8. Concurrency hotspots ─────────────────────────────────────────────────
print(header("CONCURRENCY HOTSPOTS (calls starting within 100ms of each other)"))
ts_ms = [int(t.timestamp() * 1000) for t in timestamps]
bursts = []
i = 0
while i < len(ts_ms):
j = i
while j < len(ts_ms) - 1 and ts_ms[j + 1] - ts_ms[j] < 100:
j += 1
burst_size = j - i + 1
if burst_size >= 5:
burst_entries = entries[i:j + 1]
avg_dur = statistics.mean(e["durationMs"] for e in burst_entries)
bursts.append((burst_size, entries[i]["timestamp"], avg_dur, burst_entries))
i = j + 1
bursts.sort(key=lambda b: b[0], reverse=True)
if bursts:
print(f" Found {len(bursts)} burst(s) of ≥5 concurrent requests\n")
for size, ts, avg, _ in bursts[:10]:
print(f" {YELLOW}{size:>3} concurrent{RESET} at {ts} avg {colour_duration(avg)}")
else:
print(f" {GREEN}No major concurrency bursts detected.{RESET}")
# ── 9. Summary / recommendations ────────────────────────────────────────────
print(header("SUMMARY"))
err_rate = len(errors) / len(entries) * 100
slow_5s = sum(1 for d in durations if d >= 5000)
slow_pct = slow_5s / len(entries) * 100
if err_rate > 5:
print(f" {RED}⚠ Error rate is {err_rate:.1f}% — CW API is struggling{RESET}")
elif err_rate > 1:
print(f" {YELLOW}⚠ Error rate is {err_rate:.1f}% — some instability{RESET}")
else:
print(f" {GREEN}✓ Error rate is {err_rate:.1f}% — acceptable{RESET}")
if slow_pct > 10:
print(f" {RED}{slow_5s:,} calls ({slow_pct:.1f}%) took >5s — CW is slow or rate-limiting{RESET}")
elif slow_pct > 2:
print(f" {YELLOW}{slow_5s:,} calls ({slow_pct:.1f}%) took >5s{RESET}")
else:
print(f" {GREEN}✓ Only {slow_5s:,} calls ({slow_pct:.1f}%) over 5s{RESET}")
if bursts:
max_burst = max(b[0] for b in bursts)
print(f" {YELLOW}⚠ Max concurrency burst: {max_burst} simultaneous requests — consider lowering CONCURRENCY{RESET}")
total_time_s = sum(durations) / 1000
print(f"\n Total wall-clock time spent waiting on CW: {BOLD}{total_time_s:,.1f}s{RESET} ({total_time_s/60:,.1f} min)")
print()
+441
View File
@@ -0,0 +1,441 @@
#!/usr/bin/env python3
import argparse
import json
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
def parse_iso(value: str | None) -> datetime | None:
if not value:
return None
normalized = value.replace("Z", "+00:00")
try:
return datetime.fromisoformat(normalized)
except ValueError:
return None
def first_non_empty(*values: Any) -> str:
for value in values:
if value is None:
continue
if isinstance(value, str) and value.strip() == "":
continue
return str(value)
return "unknown"
def top_lines(counter: Counter[str], limit: int) -> list[str]:
return [f"{k}: {v}" for k, v in counter.most_common(limit)]
def fmt_pct(part: int, total: int) -> str:
if total == 0:
return "0.0%"
return f"{(part / total) * 100:.1f}%"
def human_duration(start: datetime | None, end: datetime | None) -> str:
if start is None or end is None:
return "unknown"
delta = end - start
total_seconds = int(delta.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours}h {minutes}m {seconds}s"
def truncate(value: str, max_len: int = 90) -> str:
if len(value) <= max_len:
return value
return value[: max_len - 1] + ""
def add_section(lines: list[str], title: str) -> None:
lines.append("")
lines.append(title)
lines.append("-" * len(title))
def supports_color(enabled: bool) -> bool:
return enabled
def paint(text: str, code: str, use_color: bool) -> str:
if not use_color:
return text
return f"\033[{code}m{text}\033[0m"
def good_bad_neutral(value: str, state: str, use_color: bool) -> str:
if state == "good":
return paint(value, "32", use_color)
if state == "bad":
return paint(value, "31", use_color)
return paint(value, "36", use_color)
def add_ranked_counter(
lines: list[str],
title: str,
counter: Counter[str],
top_n: int,
total: int,
truncate_labels: bool = False,
) -> None:
lines.append(f"{title}")
items = counter.most_common(top_n)
if not items:
lines.append(" (no data)")
return
for index, (key, count) in enumerate(items, start=1):
label = truncate(key) if truncate_labels else key
lines.append(f" {index:>2}. {label:<90} {count:>4} {fmt_pct(count, total):>6}")
def stream_row_summary(row: dict[str, Any], use_color: bool, max_path: int) -> str:
request = row.get("request") or {}
response = row.get("response") or {}
body_parsed = request.get("bodyParsed") or {}
entity_parsed = request.get("entityParsed") or {}
summary = request.get("summary") or {}
timestamp = parse_iso(row.get("timestamp"))
time_label = timestamp.astimezone(timezone.utc).strftime("%H:%M:%S") if timestamp else "--:--:--"
method = first_non_empty(request.get("method"))
path = first_non_empty(request.get("path"))
endpoint = path.split("?", 1)[0]
status_code = first_non_empty(response.get("status"))
event_type = first_non_empty(body_parsed.get("Type"), summary.get("type"))
action = first_non_empty(
body_parsed.get("Action"),
summary.get("action"),
request.get("query", {}).get("params", {}).get("action"),
)
item_id = first_non_empty(body_parsed.get("ID"), summary.get("id"), request.get("query", {}).get("inferredId"))
actor = first_non_empty(
request.get("query", {}).get("params", {}).get("memberId"),
summary.get("entityUpdatedBy"),
entity_parsed.get("UpdatedBy"),
)
entity_status = first_non_empty(entity_parsed.get("StatusName"), summary.get("entityStatus"))
endpoint_label = truncate(endpoint, max_path)
status_state = "good" if status_code.startswith("2") else "bad"
status_colored = good_bad_neutral(status_code, status_state, use_color)
event_colored = paint(f"{event_type}.{action}", "36", use_color)
endpoint_colored = paint(endpoint_label, "94", use_color)
return (
f"[{time_label}] {method:<4} {endpoint_colored:<20} "
f"{status_colored:>3} {event_colored:<22} "
f"id={item_id:<7} actor={truncate(actor, 16):<16} status={truncate(entity_status, 22)}"
)
def endpoint_stream_summary(log_path: Path, use_color: bool, max_path: int) -> str:
lines: list[str] = []
lines.append(paint("ENDPOINT STREAM (chronological)", "1;95", use_color))
lines.append(paint("────────────────────────────────────────────────────────────────────────────────────────────", "90", use_color))
count = 0
invalid = 0
with log_path.open("r", encoding="utf-8") as handle:
for raw_line in handle:
line = raw_line.strip()
if not line:
continue
try:
row = json.loads(line)
except json.JSONDecodeError:
invalid += 1
continue
lines.append(stream_row_summary(row, use_color=use_color, max_path=max_path))
count += 1
lines.append(paint("────────────────────────────────────────────────────────────────────────────────────────────", "90", use_color))
lines.append(
f"events={count} invalid={good_bad_neutral(str(invalid), 'good' if invalid == 0 else 'bad', use_color)}"
)
return "\n".join(lines)
@dataclass
class LogStats:
total_rows: int = 0
parsed_rows: int = 0
invalid_rows: int = 0
earliest: datetime | None = None
latest: datetime | None = None
methods: Counter[str] = None # type: ignore[assignment]
paths: Counter[str] = None # type: ignore[assignment]
endpoint_roots: Counter[str] = None # type: ignore[assignment]
response_statuses: Counter[str] = None # type: ignore[assignment]
event_types: Counter[str] = None # type: ignore[assignment]
actions: Counter[str] = None # type: ignore[assignment]
type_action_combo: Counter[str] = None # type: ignore[assignment]
company_ids: Counter[str] = None # type: ignore[assignment]
source_members: Counter[str] = None # type: ignore[assignment]
actor_members: Counter[str] = None # type: ignore[assignment]
entity_updated_by: Counter[str] = None # type: ignore[assignment]
requests_by_hour: Counter[str] = None # type: ignore[assignment]
requests_by_minute: Counter[str] = None # type: ignore[assignment]
endpoint_by_hour: dict[str, Counter[str]] = None # type: ignore[assignment]
def __post_init__(self) -> None:
self.methods = Counter()
self.paths = Counter()
self.endpoint_roots = Counter()
self.response_statuses = Counter()
self.event_types = Counter()
self.actions = Counter()
self.type_action_combo = Counter()
self.company_ids = Counter()
self.source_members = Counter()
self.actor_members = Counter()
self.entity_updated_by = Counter()
self.requests_by_hour = Counter()
self.requests_by_minute = Counter()
self.endpoint_by_hour = defaultdict(Counter)
def add_timestamp(self, timestamp: datetime | None) -> None:
if timestamp is None:
return
self.earliest = timestamp if self.earliest is None else min(self.earliest, timestamp)
self.latest = timestamp if self.latest is None else max(self.latest, timestamp)
hour_bucket = timestamp.astimezone(timezone.utc).strftime("%Y-%m-%d %H:00 UTC")
minute_bucket = timestamp.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
self.requests_by_hour[hour_bucket] += 1
self.requests_by_minute[minute_bucket] += 1
def summarize(self, top_n: int, busiest_n: int, use_color: bool) -> str:
duration_line = human_duration(self.earliest, self.latest)
time_range_line = "unknown"
if self.earliest and self.latest:
time_range_line = f"{self.earliest.isoformat()}{self.latest.isoformat()}"
total_requests = self.parsed_rows
success_count = self.response_statuses.get("200", 0)
success_pct = fmt_pct(success_count, sum(self.response_statuses.values()))
invalid_state = "good" if self.invalid_rows == 0 else "bad"
top_endpoints = self.endpoint_roots.most_common(2)
top_users = self.actor_members.most_common(3)
top_minutes = self.requests_by_minute.most_common(busiest_n)
lines: list[str] = []
lines.append(paint("WEBHOOK SNAPSHOT", "1;95", use_color))
lines.append(paint("────────────────────────────────────────────────────────", "90", use_color))
lines.append(
" "
+ paint("Rows", "1;97", use_color)
+ f": {self.total_rows:<4} "
+ paint("Parsed", "1;97", use_color)
+ f": {self.parsed_rows:<4} "
+ paint("Invalid", "1;97", use_color)
+ f": {good_bad_neutral(str(self.invalid_rows), invalid_state, use_color)}"
)
lines.append(
" "
+ paint("Window", "1;97", use_color)
+ f": {duration_line:<12} "
+ paint("Success", "1;97", use_color)
+ f": {good_bad_neutral(success_pct, 'good' if success_count else 'neutral', use_color)}"
)
lines.append(" " + paint("UTC Range", "1;97", use_color) + f": {time_range_line}")
lines.append("")
lines.append(paint("Top Endpoints", "1;94", use_color))
if top_endpoints:
for endpoint, count in top_endpoints:
lines.append(f"{endpoint:<14} {count:>4} ({fmt_pct(count, total_requests)})")
if not top_endpoints:
lines.append(" • (no data)")
lines.append("")
lines.append(paint("Most Active Users (query memberId)", "1;94", use_color))
if top_users:
for user, count in top_users:
lines.append(f"{user:<18} {count:>4} ({fmt_pct(count, total_requests)})")
if not top_users:
lines.append(" • (no data)")
lines.append("")
lines.append(paint("Busiest Minutes", "1;94", use_color))
if top_minutes:
for minute, count in top_minutes:
lines.append(f"{minute:<22} {count:>3}")
if not top_minutes:
lines.append(" • (no data)")
lines.append("")
lines.append(paint("Request Mix", "1;94", use_color))
method_line = ", ".join([f"{k}:{v}" for k, v in self.methods.most_common(3)]) or "(no data)"
event_line = ", ".join([f"{k}:{v}" for k, v in self.event_types.most_common(3)]) or "(no data)"
action_line = ", ".join([f"{k}:{v}" for k, v in self.actions.most_common(3)]) or "(no data)"
lines.append(f" • Methods : {method_line}")
lines.append(f" • Types : {event_line}")
lines.append(f" • Actions : {action_line}")
lines.append("")
lines.append(paint("Status Codes", "1;94", use_color))
if self.response_statuses:
status_total = sum(self.response_statuses.values())
for status, count in self.response_statuses.most_common(5):
state = "good" if status.startswith("2") else "bad"
status_label = good_bad_neutral(status, state, use_color)
lines.append(f"{status_label}: {count} ({fmt_pct(count, status_total)})")
if not self.response_statuses:
lines.append(" • (no data)")
return "\n".join(lines)
def update_stats(stats: LogStats, row: dict[str, Any]) -> None:
timestamp = parse_iso(row.get("timestamp"))
stats.add_timestamp(timestamp)
request = row.get("request") or {}
response = row.get("response") or {}
body_parsed = request.get("bodyParsed") or {}
entity_parsed = request.get("entityParsed") or {}
method = first_non_empty(request.get("method"))
path = first_non_empty(request.get("path"))
endpoint_root = path.split("?", 1)[0]
status = first_non_empty(response.get("status"))
event_type = first_non_empty(
body_parsed.get("Type"),
request.get("summary", {}).get("type"),
)
action = first_non_empty(
body_parsed.get("Action"),
request.get("summary", {}).get("action"),
request.get("query", {}).get("params", {}).get("action"),
)
combo = f"{event_type}:{action}"
source_member = first_non_empty(
body_parsed.get("MemberId"),
request.get("summary", {}).get("memberId"),
)
actor_member = first_non_empty(
request.get("query", {}).get("params", {}).get("memberId"),
request.get("summary", {}).get("entityUpdatedBy"),
)
updated_by = first_non_empty(
entity_parsed.get("UpdatedBy"),
request.get("summary", {}).get("entityUpdatedBy"),
)
company_id = first_non_empty(body_parsed.get("CompanyId"), request.get("headers", {}).get("companyname"))
stats.methods[method] += 1
stats.paths[path] += 1
stats.endpoint_roots[endpoint_root] += 1
stats.response_statuses[status] += 1
stats.event_types[event_type] += 1
stats.actions[action] += 1
stats.type_action_combo[combo] += 1
stats.company_ids[company_id] += 1
stats.source_members[source_member] += 1
stats.actor_members[actor_member] += 1
stats.entity_updated_by[updated_by] += 1
if timestamp:
bucket = timestamp.astimezone(timezone.utc).strftime("%Y-%m-%d %H:00 UTC")
stats.endpoint_by_hour[endpoint_root][bucket] += 1
def analyze_file(log_path: Path) -> LogStats:
stats = LogStats()
with log_path.open("r", encoding="utf-8") as handle:
for raw_line in handle:
line = raw_line.strip()
if not line:
continue
stats.total_rows += 1
try:
row = json.loads(line)
except json.JSONDecodeError:
stats.invalid_rows += 1
continue
stats.parsed_rows += 1
update_stats(stats, row)
return stats
def main() -> None:
parser = argparse.ArgumentParser(
description="Analyze webhook JSONL logs by users, time, and request types."
)
parser.add_argument("log_file", help="Path to JSONL log file")
parser.add_argument("--top", type=int, default=10, help="Top N entries per section (default: 10)")
parser.add_argument(
"--busiest-minutes",
type=int,
default=5,
help="How many top minute buckets to show (default: 5)",
)
parser.add_argument(
"--no-color",
action="store_true",
help="Disable ANSI colors",
)
parser.add_argument(
"--endpoint-stream",
action="store_true",
help="Show chronological one-line summary per webhook, similar to live test webserver logs",
)
parser.add_argument(
"--max-path",
type=int,
default=18,
help="Max endpoint width in stream mode before truncation (default: 18)",
)
args = parser.parse_args()
log_path = Path(args.log_file)
if not log_path.exists() or not log_path.is_file():
raise SystemExit(f"Log file not found: {log_path}")
use_color = supports_color(not args.no_color)
if args.endpoint_stream:
print(endpoint_stream_summary(log_path, use_color=use_color, max_path=max(args.max_path, 10)))
return
stats = analyze_file(log_path)
print(
stats.summarize(
top_n=max(args.top, 1),
busiest_n=max(args.busiest_minutes, 1),
use_color=use_color,
)
)
if __name__ == "__main__":
main()
-6
View File
@@ -1,6 +0,0 @@
import { expect, test } from '@playwright/test';
test('home page has expected h1', async ({ page }) => {
await page.goto('/');
await expect(page.locator('h1')).toBeVisible();
});
-54
View File
@@ -1,54 +0,0 @@
import { app, BrowserWindow } from "electron";
import path from "node:path";
import started from "electron-squirrel-startup";
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
app.quit();
}
const PRODUCTION_URL = "https://optima.osdci.net";
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(import.meta.dirname, "preload.js"),
},
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(`${MAIN_WINDOW_VITE_DEV_SERVER_URL}/login`);
mainWindow.webContents.on("did-frame-finish-load", () => {
mainWindow.webContents.openDevTools({ mode: "detach" });
});
} else {
mainWindow.loadURL(PRODUCTION_URL);
}
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
-61
View File
@@ -1,61 +0,0 @@
import type { ForgeConfig } from "@electron-forge/shared-types";
import { MakerSquirrel } from "@electron-forge/maker-squirrel";
import { MakerZIP } from "@electron-forge/maker-zip";
import { MakerDMG } from "@electron-forge/maker-dmg";
import { MakerDeb } from "@electron-forge/maker-deb";
import { MakerRpm } from "@electron-forge/maker-rpm";
import { VitePlugin } from "@electron-forge/plugin-vite";
import { FusesPlugin } from "@electron-forge/plugin-fuses";
import { FuseV1Options, FuseVersion } from "@electron/fuses";
const config: ForgeConfig = {
packagerConfig: {
asar: true,
},
rebuildConfig: {},
makers: [
new MakerSquirrel({}),
new MakerZIP({}, ["darwin"]),
new MakerDMG({}),
new MakerRpm({}),
new MakerDeb({}),
],
plugins: [
new VitePlugin({
// `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.
// If you are familiar with Vite configuration, it will look really familiar.
build: [
{
// `entry` is just an alias for `build.lib.entry` in the corresponding file of `config`.
entry: "electron/main.ts",
config: "vite.main.config.ts",
target: "main",
},
{
entry: "electron/preload.ts",
config: "vite.preload.config.ts",
target: "preload",
},
],
renderer: [
{
name: "main_window",
config: "vite.config.ts",
},
],
}),
// Fuses are used to enable/disable various Electron functionality
// at package time, before code signing the application
new FusesPlugin({
version: FuseVersion.V1,
[FuseV1Options.RunAsNode]: false,
[FuseV1Options.EnableCookieEncryption]: true,
[FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,
[FuseV1Options.EnableNodeCliInspectArguments]: false,
[FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,
[FuseV1Options.OnlyLoadAppFromAsar]: true,
}),
],
};
export default config;
-1
View File
@@ -1 +0,0 @@
/// <reference types="@electron-forge/plugin-vite/forge-vite-env" />
+69
View File
@@ -0,0 +1,69 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma-related types and utilities in a browser.
* Use it to get access to models, enums, and input types.
*
* This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only.
* See `client.ts` for the standard, server-side entry point.
*
* 🟢 You can import this file directly.
*/
import * as Prisma from './internal/prismaNamespaceBrowser.ts'
export { Prisma }
export * as $Enums from './enums.ts'
export * from './enums.ts';
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Role
*
*/
export type Role = Prisma.RoleModel
/**
* Model UnifiSite
*
*/
export type UnifiSite = Prisma.UnifiSiteModel
/**
* Model Company
*
*/
export type Company = Prisma.CompanyModel
/**
* Model CatalogItem
*
*/
export type CatalogItem = Prisma.CatalogItemModel
/**
* Model Opportunity
*
*/
export type Opportunity = Prisma.OpportunityModel
/**
* Model CredentialType
*
*/
export type CredentialType = Prisma.CredentialTypeModel
/**
* Model SecureValue
*
*/
export type SecureValue = Prisma.SecureValueModel
/**
* Model Credential
*
*/
export type Credential = Prisma.CredentialModel
+91
View File
@@ -0,0 +1,91 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types.
* If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead.
*
* 🟢 You can import this file directly.
*/
import * as process from 'node:process'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
globalThis['__dirname'] = path.dirname(fileURLToPath(import.meta.url))
import * as runtime from "@prisma/client/runtime/client"
import * as $Enums from "./enums.ts"
import * as $Class from "./internal/class.ts"
import * as Prisma from "./internal/prismaNamespace.ts"
export * as $Enums from './enums.ts'
export * from "./enums.ts"
/**
* ## Prisma Client
*
* Type-safe database client for TypeScript
* @example
* ```
* const prisma = new PrismaClient()
* // Fetch zero or more Sessions
* const sessions = await prisma.session.findMany()
* ```
*
* Read more in our [docs](https://pris.ly/d/client).
*/
export const PrismaClient = $Class.getPrismaClientClass()
export type PrismaClient<LogOpts extends Prisma.LogLevel = never, OmitOpts extends Prisma.PrismaClientOptions["omit"] = Prisma.PrismaClientOptions["omit"], ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = $Class.PrismaClient<LogOpts, OmitOpts, ExtArgs>
export { Prisma }
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Role
*
*/
export type Role = Prisma.RoleModel
/**
* Model UnifiSite
*
*/
export type UnifiSite = Prisma.UnifiSiteModel
/**
* Model Company
*
*/
export type Company = Prisma.CompanyModel
/**
* Model CatalogItem
*
*/
export type CatalogItem = Prisma.CatalogItemModel
/**
* Model Opportunity
*
*/
export type Opportunity = Prisma.OpportunityModel
/**
* Model CredentialType
*
*/
export type CredentialType = Prisma.CredentialTypeModel
/**
* Model SecureValue
*
*/
export type SecureValue = Prisma.SecureValueModel
/**
* Model Credential
*
*/
export type Credential = Prisma.CredentialModel
+524
View File
@@ -0,0 +1,524 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file exports various common sort, input & filter types that are not directly linked to a particular model.
*
* 🟢 You can import this file directly.
*/
import type * as runtime from "@prisma/client/runtime/client"
import * as $Enums from "./enums.ts"
import type * as Prisma from "./internal/prismaNamespace.ts"
export type StringFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
mode?: Prisma.QueryMode
not?: Prisma.NestedStringFilter<$PrismaModel> | string
}
export type DateTimeFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeFilter<$PrismaModel> | Date | string
}
export type BoolFilter<$PrismaModel = never> = {
equals?: boolean | Prisma.BooleanFieldRefInput<$PrismaModel>
not?: Prisma.NestedBoolFilter<$PrismaModel> | boolean
}
export type DateTimeNullableFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel> | null
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeNullableFilter<$PrismaModel> | Date | string | null
}
export type SortOrderInput = {
sort: Prisma.SortOrder
nulls?: Prisma.NullsOrder
}
export type StringWithAggregatesFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
mode?: Prisma.QueryMode
not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedStringFilter<$PrismaModel>
_max?: Prisma.NestedStringFilter<$PrismaModel>
}
export type DateTimeWithAggregatesFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeWithAggregatesFilter<$PrismaModel> | Date | string
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedDateTimeFilter<$PrismaModel>
_max?: Prisma.NestedDateTimeFilter<$PrismaModel>
}
export type BoolWithAggregatesFilter<$PrismaModel = never> = {
equals?: boolean | Prisma.BooleanFieldRefInput<$PrismaModel>
not?: Prisma.NestedBoolWithAggregatesFilter<$PrismaModel> | boolean
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedBoolFilter<$PrismaModel>
_max?: Prisma.NestedBoolFilter<$PrismaModel>
}
export type DateTimeNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel> | null
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeNullableWithAggregatesFilter<$PrismaModel> | Date | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedDateTimeNullableFilter<$PrismaModel>
_max?: Prisma.NestedDateTimeNullableFilter<$PrismaModel>
}
export type StringNullableFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel> | null
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
mode?: Prisma.QueryMode
not?: Prisma.NestedStringNullableFilter<$PrismaModel> | string | null
}
export type StringNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel> | null
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
mode?: Prisma.QueryMode
not?: Prisma.NestedStringNullableWithAggregatesFilter<$PrismaModel> | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedStringNullableFilter<$PrismaModel>
_max?: Prisma.NestedStringNullableFilter<$PrismaModel>
}
export type IntFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntFilter<$PrismaModel> | number
}
export type IntWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedIntFilter<$PrismaModel>
_max?: Prisma.NestedIntFilter<$PrismaModel>
}
export type IntNullableFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel> | null
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntNullableFilter<$PrismaModel> | number | null
}
export type FloatFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
}
export type IntNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel> | null
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntNullableWithAggregatesFilter<$PrismaModel> | number | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_avg?: Prisma.NestedFloatNullableFilter<$PrismaModel>
_sum?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedIntNullableFilter<$PrismaModel>
_max?: Prisma.NestedIntNullableFilter<$PrismaModel>
}
export type FloatWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedFloatFilter<$PrismaModel>
_min?: Prisma.NestedFloatFilter<$PrismaModel>
_max?: Prisma.NestedFloatFilter<$PrismaModel>
}
export type JsonFilter<$PrismaModel = never> =
| Prisma.PatchUndefined<
Prisma.Either<Required<JsonFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonFilterBase<$PrismaModel>>, 'path'>>,
Required<JsonFilterBase<$PrismaModel>>
>
| Prisma.OptionalFlat<Omit<Required<JsonFilterBase<$PrismaModel>>, 'path'>>
export type JsonFilterBase<$PrismaModel = never> = {
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
path?: string[]
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
}
export type JsonWithAggregatesFilter<$PrismaModel = never> =
| Prisma.PatchUndefined<
Prisma.Either<Required<JsonWithAggregatesFilterBase<$PrismaModel>>, Exclude<keyof Required<JsonWithAggregatesFilterBase<$PrismaModel>>, 'path'>>,
Required<JsonWithAggregatesFilterBase<$PrismaModel>>
>
| Prisma.OptionalFlat<Omit<Required<JsonWithAggregatesFilterBase<$PrismaModel>>, 'path'>>
export type JsonWithAggregatesFilterBase<$PrismaModel = never> = {
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
path?: string[]
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedJsonFilter<$PrismaModel>
_max?: Prisma.NestedJsonFilter<$PrismaModel>
}
export type NestedStringFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
not?: Prisma.NestedStringFilter<$PrismaModel> | string
}
export type NestedDateTimeFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeFilter<$PrismaModel> | Date | string
}
export type NestedBoolFilter<$PrismaModel = never> = {
equals?: boolean | Prisma.BooleanFieldRefInput<$PrismaModel>
not?: Prisma.NestedBoolFilter<$PrismaModel> | boolean
}
export type NestedDateTimeNullableFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel> | null
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeNullableFilter<$PrismaModel> | Date | string | null
}
export type NestedStringWithAggregatesFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel>
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedStringFilter<$PrismaModel>
_max?: Prisma.NestedStringFilter<$PrismaModel>
}
export type NestedIntFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntFilter<$PrismaModel> | number
}
export type NestedDateTimeWithAggregatesFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel>
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeWithAggregatesFilter<$PrismaModel> | Date | string
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedDateTimeFilter<$PrismaModel>
_max?: Prisma.NestedDateTimeFilter<$PrismaModel>
}
export type NestedBoolWithAggregatesFilter<$PrismaModel = never> = {
equals?: boolean | Prisma.BooleanFieldRefInput<$PrismaModel>
not?: Prisma.NestedBoolWithAggregatesFilter<$PrismaModel> | boolean
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedBoolFilter<$PrismaModel>
_max?: Prisma.NestedBoolFilter<$PrismaModel>
}
export type NestedDateTimeNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel> | null
in?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
notIn?: Date[] | string[] | Prisma.ListDateTimeFieldRefInput<$PrismaModel> | null
lt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
lte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gt?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
gte?: Date | string | Prisma.DateTimeFieldRefInput<$PrismaModel>
not?: Prisma.NestedDateTimeNullableWithAggregatesFilter<$PrismaModel> | Date | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedDateTimeNullableFilter<$PrismaModel>
_max?: Prisma.NestedDateTimeNullableFilter<$PrismaModel>
}
export type NestedIntNullableFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel> | null
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntNullableFilter<$PrismaModel> | number | null
}
export type NestedStringNullableFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel> | null
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
not?: Prisma.NestedStringNullableFilter<$PrismaModel> | string | null
}
export type NestedStringNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: string | Prisma.StringFieldRefInput<$PrismaModel> | null
in?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
notIn?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
lt?: string | Prisma.StringFieldRefInput<$PrismaModel>
lte?: string | Prisma.StringFieldRefInput<$PrismaModel>
gt?: string | Prisma.StringFieldRefInput<$PrismaModel>
gte?: string | Prisma.StringFieldRefInput<$PrismaModel>
contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel>
not?: Prisma.NestedStringNullableWithAggregatesFilter<$PrismaModel> | string | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedStringNullableFilter<$PrismaModel>
_max?: Prisma.NestedStringNullableFilter<$PrismaModel>
}
export type NestedIntWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel>
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedIntFilter<$PrismaModel>
_max?: Prisma.NestedIntFilter<$PrismaModel>
}
export type NestedFloatFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatFilter<$PrismaModel> | number
}
export type NestedIntNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.IntFieldRefInput<$PrismaModel> | null
in?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
notIn?: number[] | Prisma.ListIntFieldRefInput<$PrismaModel> | null
lt?: number | Prisma.IntFieldRefInput<$PrismaModel>
lte?: number | Prisma.IntFieldRefInput<$PrismaModel>
gt?: number | Prisma.IntFieldRefInput<$PrismaModel>
gte?: number | Prisma.IntFieldRefInput<$PrismaModel>
not?: Prisma.NestedIntNullableWithAggregatesFilter<$PrismaModel> | number | null
_count?: Prisma.NestedIntNullableFilter<$PrismaModel>
_avg?: Prisma.NestedFloatNullableFilter<$PrismaModel>
_sum?: Prisma.NestedIntNullableFilter<$PrismaModel>
_min?: Prisma.NestedIntNullableFilter<$PrismaModel>
_max?: Prisma.NestedIntNullableFilter<$PrismaModel>
}
export type NestedFloatNullableFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel> | null
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel> | null
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel> | null
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatNullableFilter<$PrismaModel> | number | null
}
export type NestedFloatWithAggregatesFilter<$PrismaModel = never> = {
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel>
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
notIn?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel>
lt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
lte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gt?: number | Prisma.FloatFieldRefInput<$PrismaModel>
gte?: number | Prisma.FloatFieldRefInput<$PrismaModel>
not?: Prisma.NestedFloatWithAggregatesFilter<$PrismaModel> | number
_count?: Prisma.NestedIntFilter<$PrismaModel>
_avg?: Prisma.NestedFloatFilter<$PrismaModel>
_sum?: Prisma.NestedFloatFilter<$PrismaModel>
_min?: Prisma.NestedFloatFilter<$PrismaModel>
_max?: Prisma.NestedFloatFilter<$PrismaModel>
}
export type NestedJsonFilter<$PrismaModel = never> =
| Prisma.PatchUndefined<
Prisma.Either<Required<NestedJsonFilterBase<$PrismaModel>>, Exclude<keyof Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>,
Required<NestedJsonFilterBase<$PrismaModel>>
>
| Prisma.OptionalFlat<Omit<Required<NestedJsonFilterBase<$PrismaModel>>, 'path'>>
export type NestedJsonFilterBase<$PrismaModel = never> = {
equals?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
path?: string[]
mode?: Prisma.QueryMode | Prisma.EnumQueryModeFieldRefInput<$PrismaModel>
string_contains?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_starts_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
string_ends_with?: string | Prisma.StringFieldRefInput<$PrismaModel>
array_starts_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_ends_with?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
array_contains?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | null
lt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
lte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gt?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
gte?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel>
not?: runtime.InputJsonValue | Prisma.JsonFieldRefInput<$PrismaModel> | Prisma.JsonNullValueFilter
}
+15
View File
@@ -0,0 +1,15 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file exports all enum related types from the schema.
*
* 🟢 You can import this file directly.
*/
// This file is empty because there are no enums in the schema.
export {}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,312 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* WARNING: This is an internal file that is subject to change!
*
* 🛑 Under no circumstances should you import this file directly! 🛑
*
* All exports from this file are wrapped under a `Prisma` namespace object in the browser.ts file.
* While this enables partial backward compatibility, it is not part of the stable public API.
*
* If you are looking for your Models, Enums, and Input Types, please import them from the respective
* model files in the `model` directory!
*/
import * as runtime from "@prisma/client/runtime/index-browser"
export type * from '../models.ts'
export type * from './prismaNamespace.ts'
export const Decimal = runtime.Decimal
export const NullTypes = {
DbNull: runtime.NullTypes.DbNull as (new (secret: never) => typeof runtime.DbNull),
JsonNull: runtime.NullTypes.JsonNull as (new (secret: never) => typeof runtime.JsonNull),
AnyNull: runtime.NullTypes.AnyNull as (new (secret: never) => typeof runtime.AnyNull),
}
/**
* Helper for filtering JSON entries that have `null` on the database (empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const DbNull = runtime.DbNull
/**
* Helper for filtering JSON entries that have JSON `null` values (not empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const JsonNull = runtime.JsonNull
/**
* Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull`
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const AnyNull = runtime.AnyNull
export const ModelName = {
Session: 'Session',
User: 'User',
Role: 'Role',
UnifiSite: 'UnifiSite',
Company: 'Company',
CatalogItem: 'CatalogItem',
Opportunity: 'Opportunity',
CredentialType: 'CredentialType',
SecureValue: 'SecureValue',
Credential: 'Credential'
} as const
export type ModelName = (typeof ModelName)[keyof typeof ModelName]
/*
* Enums
*/
export const TransactionIsolationLevel = runtime.makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
} as const)
export type TransactionIsolationLevel = (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel]
export const SessionScalarFieldEnum = {
id: 'id',
sessionKey: 'sessionKey',
userId: 'userId',
expires: 'expires',
refreshTokenGenerated: 'refreshTokenGenerated',
refreshedAt: 'refreshedAt',
invalidatedAt: 'invalidatedAt'
} as const
export type SessionScalarFieldEnum = (typeof SessionScalarFieldEnum)[keyof typeof SessionScalarFieldEnum]
export const UserScalarFieldEnum = {
id: 'id',
permissions: 'permissions',
login: 'login',
name: 'name',
email: 'email',
emailVerified: 'emailVerified',
image: 'image',
cwIdentifier: 'cwIdentifier',
userId: 'userId',
token: 'token',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type UserScalarFieldEnum = (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum]
export const RoleScalarFieldEnum = {
id: 'id',
title: 'title',
moniker: 'moniker',
permissions: 'permissions',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type RoleScalarFieldEnum = (typeof RoleScalarFieldEnum)[keyof typeof RoleScalarFieldEnum]
export const UnifiSiteScalarFieldEnum = {
id: 'id',
name: 'name',
siteId: 'siteId',
companyId: 'companyId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type UnifiSiteScalarFieldEnum = (typeof UnifiSiteScalarFieldEnum)[keyof typeof UnifiSiteScalarFieldEnum]
export const CompanyScalarFieldEnum = {
id: 'id',
name: 'name',
cw_CompanyId: 'cw_CompanyId',
cw_Identifier: 'cw_Identifier',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type CompanyScalarFieldEnum = (typeof CompanyScalarFieldEnum)[keyof typeof CompanyScalarFieldEnum]
export const CatalogItemScalarFieldEnum = {
id: 'id',
cwCatalogId: 'cwCatalogId',
identifier: 'identifier',
name: 'name',
description: 'description',
customerDescription: 'customerDescription',
internalNotes: 'internalNotes',
category: 'category',
categoryCwId: 'categoryCwId',
subcategory: 'subcategory',
subcategoryCwId: 'subcategoryCwId',
manufacturer: 'manufacturer',
manufactureCwId: 'manufactureCwId',
partNumber: 'partNumber',
vendorName: 'vendorName',
vendorSku: 'vendorSku',
vendorCwId: 'vendorCwId',
price: 'price',
cost: 'cost',
inactive: 'inactive',
salesTaxable: 'salesTaxable',
onHand: 'onHand',
cwLastUpdated: 'cwLastUpdated',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type CatalogItemScalarFieldEnum = (typeof CatalogItemScalarFieldEnum)[keyof typeof CatalogItemScalarFieldEnum]
export const OpportunityScalarFieldEnum = {
id: 'id',
cwOpportunityId: 'cwOpportunityId',
name: 'name',
notes: 'notes',
typeName: 'typeName',
typeCwId: 'typeCwId',
stageName: 'stageName',
stageCwId: 'stageCwId',
statusName: 'statusName',
statusCwId: 'statusCwId',
priorityName: 'priorityName',
priorityCwId: 'priorityCwId',
ratingName: 'ratingName',
ratingCwId: 'ratingCwId',
source: 'source',
campaignName: 'campaignName',
campaignCwId: 'campaignCwId',
primarySalesRepName: 'primarySalesRepName',
primarySalesRepIdentifier: 'primarySalesRepIdentifier',
primarySalesRepCwId: 'primarySalesRepCwId',
secondarySalesRepName: 'secondarySalesRepName',
secondarySalesRepIdentifier: 'secondarySalesRepIdentifier',
secondarySalesRepCwId: 'secondarySalesRepCwId',
companyCwId: 'companyCwId',
companyName: 'companyName',
contactCwId: 'contactCwId',
contactName: 'contactName',
siteCwId: 'siteCwId',
siteName: 'siteName',
customerPO: 'customerPO',
totalSalesTax: 'totalSalesTax',
locationName: 'locationName',
locationCwId: 'locationCwId',
departmentName: 'departmentName',
departmentCwId: 'departmentCwId',
expectedCloseDate: 'expectedCloseDate',
pipelineChangeDate: 'pipelineChangeDate',
dateBecameLead: 'dateBecameLead',
closedDate: 'closedDate',
closedFlag: 'closedFlag',
closedByName: 'closedByName',
closedByCwId: 'closedByCwId',
companyId: 'companyId',
productSequence: 'productSequence',
cwLastUpdated: 'cwLastUpdated',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type OpportunityScalarFieldEnum = (typeof OpportunityScalarFieldEnum)[keyof typeof OpportunityScalarFieldEnum]
export const CredentialTypeScalarFieldEnum = {
id: 'id',
name: 'name',
permissionScope: 'permissionScope',
icon: 'icon',
fields: 'fields',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type CredentialTypeScalarFieldEnum = (typeof CredentialTypeScalarFieldEnum)[keyof typeof CredentialTypeScalarFieldEnum]
export const SecureValueScalarFieldEnum = {
id: 'id',
name: 'name',
content: 'content',
hash: 'hash',
credentialId: 'credentialId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type SecureValueScalarFieldEnum = (typeof SecureValueScalarFieldEnum)[keyof typeof SecureValueScalarFieldEnum]
export const CredentialScalarFieldEnum = {
id: 'id',
name: 'name',
notes: 'notes',
subCredentialOfId: 'subCredentialOfId',
typeId: 'typeId',
fields: 'fields',
companyId: 'companyId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type CredentialScalarFieldEnum = (typeof CredentialScalarFieldEnum)[keyof typeof CredentialScalarFieldEnum]
export const SortOrder = {
asc: 'asc',
desc: 'desc'
} as const
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
export const JsonNullValueInput = {
JsonNull: JsonNull
} as const
export type JsonNullValueInput = (typeof JsonNullValueInput)[keyof typeof JsonNullValueInput]
export const QueryMode = {
default: 'default',
insensitive: 'insensitive'
} as const
export type QueryMode = (typeof QueryMode)[keyof typeof QueryMode]
export const NullsOrder = {
first: 'first',
last: 'last'
} as const
export type NullsOrder = (typeof NullsOrder)[keyof typeof NullsOrder]
export const JsonNullValueFilter = {
DbNull: DbNull,
JsonNull: JsonNull,
AnyNull: AnyNull
} as const
export type JsonNullValueFilter = (typeof JsonNullValueFilter)[keyof typeof JsonNullValueFilter]
+21
View File
@@ -0,0 +1,21 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This is a barrel export file for all models and their related types.
*
* 🟢 You can import this file directly.
*/
export type * from './models/Session.ts'
export type * from './models/User.ts'
export type * from './models/Role.ts'
export type * from './models/UnifiSite.ts'
export type * from './models/Company.ts'
export type * from './models/CatalogItem.ts'
export type * from './models/Opportunity.ts'
export type * from './models/CredentialType.ts'
export type * from './models/SecureValue.ts'
export type * from './models/Credential.ts'
export type * from './commonInputTypes.ts'
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+10 -12
View File
@@ -1,29 +1,27 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: optima-ui
name: optima-api
namespace: optima
spec:
selector:
matchLabels:
app: optima-ui
app: optima-api
replicas: 1
template:
metadata:
labels:
app: optima-ui
app: optima-api
spec:
containers:
- name: optima-ui
image: ghcr.io/project-optima/ttscm-ui:latest
- name: optima-api
image: ghcr.io/project-optima/ttscm-api:latest
imagePullPolicy: Always
env:
- name: PUBLIC_API_URL
value: "https://opt-api.osdci.net"
- name: ORIGIN
value: "https://optima.osdci.net"
- name: PORT
value: "3000"
envFrom:
- secretRef:
name: api-env-secret
- secretRef:
name: optima-keys-secret
ports:
- containerPort: 3000
imagePullSecrets:
+7 -7
View File
@@ -1,7 +1,7 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: optima-ui-ingress
name: optima-api-ingress
namespace: optima
annotations:
traefik.ingress.kubernetes.io/router.entrypoints: websecure
@@ -9,31 +9,31 @@ metadata:
spec:
tls:
- hosts:
- optima.osdci.net
- opt-api.osdci.net
secretName: osdci-net-cert
rules:
- host: optima.osdci.net
- host: opt-api.osdci.net
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: optima-ui
name: optima-api
port:
number: 3000
---
apiVersion: v1
kind: Service
metadata:
name: optima-ui
name: optima-api
namespace: optima
labels:
app: optima-ui
app: optima-api
spec:
type: ClusterIP
ports:
- port: 3000
protocol: TCP
selector:
app: optima-ui
app: optima-api
+23
View File
@@ -0,0 +1,23 @@
apiVersion: batch/v1
kind: Job
metadata:
name: prisma-migrate-RELEASE_TAG
namespace: optima
labels:
app: prisma-migrate
spec:
backoffLimit: 3
ttlSecondsAfterFinished: 300
template:
spec:
containers:
- name: migrate
image: ghcr.io/project-optima/ttscm-api-migrate:RELEASE_TAG
envFrom:
- secretRef:
name: api-env-secret
- secretRef:
name: optima-keys-secret
restartPolicy: Never
imagePullSecrets:
- name: github-container-registry
+47 -64
View File
@@ -1,73 +1,56 @@
{
"name": "electron-svelte",
"productName": "electron-svelte",
"description": "Electron Svelte",
"private": true,
"version": "0.0.1",
"type": "module",
"main": ".vite/build/main.js",
"name": "tts-optima-api",
"homepage": "https://totaltech.net",
"version": "v0.1.0",
"author": {
"name": "Pandoks_",
"email": "35944715+Pandoks@users.noreply.github.com"
"name": "Jackson Roberts",
"email": "jackson.roberts@totaltech.net",
"url": "https://totaltech.net"
},
"module": "src/index.ts",
"type": "module",
"private": true,
"devDependencies": {
"@types/bun": "latest",
"@types/jsonwebtoken": "^9.0.10"
},
"peerDependencies": {
"typescript": "^5"
},
"scripts": {
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test:unit": "vitest",
"test": "bun run test:unit -- --run && bun run test:e2e",
"test:e2e": "playwright test",
"start": "electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"make:macos": "electron-forge make --platform darwin",
"build:server": "vite build",
"publish": "electron-forge publish"
},
"devDependencies": {
"@electron-forge/cli": "^7.11.1",
"@electron-forge/maker-deb": "^7.11.1",
"@electron-forge/maker-dmg": "^7.11.1",
"@electron-forge/maker-rpm": "^7.11.1",
"@electron-forge/maker-squirrel": "^7.11.1",
"@electron-forge/maker-zip": "^7.11.1",
"@electron-forge/plugin-auto-unpack-natives": "^7.11.1",
"@electron-forge/plugin-fuses": "^7.11.1",
"@electron-forge/plugin-vite": "^7.11.1",
"@electron/fuses": "^1.8.0",
"@playwright/test": "^1.58.0",
"@sveltejs/adapter-node": "^5.5.3",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.1",
"@sveltejs/vite-plugin-svelte": "^5.1.1",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.1.18",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/svelte": "^5.3.1",
"@types/electron-squirrel-startup": "^1.0.2",
"@types/node": "^22.19.7",
"electron": "^36.9.5",
"jsdom": "^26.1.0",
"svelte": "^5.48.2",
"svelte-check": "^4.3.5",
"tailwindcss": "^4.1.18",
"typescript": "^5.9.3",
"vite": "^6.4.1",
"vitest": "^3.2.4"
"dev": "NODE_ENV=development bun --watch src/index.ts",
"dev:log": "LOG_CW_API=1 NODE_ENV=development bun --watch src/index.ts",
"test": "bun test --preload ./tests/setup.ts",
"db:gen": "prisma generate",
"db:push": "prisma migrate dev --skip-generate",
"db:deploy": "prisma migrate deploy",
"utils:dev": "docker compose -f .docker/docker-compose.yml up --build",
"utils:gen_private_keys": "bun ./utils/genPrivateKeys",
"utils:create_admin_role": "bun ./utils/createAdminRole",
"utils:assign_user_role": "bun ./utils/assignUserRole",
"utils:test_webserver": "bun ./utils/testWebserver.ts",
"utils:test_adjustments_poll": "bun ./utils/testAdjustmentsPoll.ts",
"utils:analyze_cw": "python3 debug-scripts/analyze-cw-calls.py",
"db:check": "bunx prisma migrate diff --from-migrations prisma/migrations --to-schema prisma/schema.prisma --shadow-database-url $DATABASE_URL --exit-code"
},
"dependencies": {
"@azure/msal-node": "^5.0.2",
"@discordjs/collection": "^2.1.1",
"@duxcore/eventra": "^1.1.0",
"@prisma/adapter-pg": "^7.3.0",
"@prisma/client": "^7.3.0",
"@socket.io/bun-engine": "^0.1.0",
"axios": "^1.13.3",
"dotenv": "^17.2.3",
"electron-squirrel-startup": "^1.0.1",
"socket.io-client": "^4.8.3"
},
"trustedDependencies": [
"esbuild",
"electron",
"electron-winstaller"
],
"patchedDependencies": {
"@sveltejs/kit": "patches/@sveltejs__kit.patch"
"blakets": "^0.1.12",
"cors": "^2.8.6",
"cuid": "^3.0.0",
"hono": "^4.11.5",
"ioredis": "^5.10.0",
"jsonwebtoken": "^9.0.3",
"keypair": "^1.0.4",
"prisma": "^7.3.0",
"socket.io": "^4.8.3",
"zod": "^4.3.6",
"zon": "^1.0.3"
}
}
-26
View File
@@ -1,26 +0,0 @@
diff --git a/src/exports/vite/index.js b/src/exports/vite/index.js
index e23cf2b833fc0a04287d34328b97bf64c7916f0d..81b6f30f3a5f2c8d3d0337777e141e549c4a5f98 100644
--- a/src/exports/vite/index.js
+++ b/src/exports/vite/index.js
@@ -473,7 +473,7 @@ Tips:
// for internal use only. it's published as $app/paths externally
// we use this alias so that we won't collide with user aliases
case sveltekit_paths: {
- const { assets, base } = svelte_config.kit.paths;
+ const { assets, base, relative } = svelte_config.kit.paths;
// use the values defined in `global`, but fall back to hard-coded values
// for the sake of things like Vitest which may import this module
@@ -488,10 +488,10 @@ Tips:
return dedent`
export let base = ${s(base)};
- export let assets = ${assets ? s(assets) : 'base'};
+ export let assets = ${relative ? "'.' + " : ''}${assets ? s(assets) : 'base'};
export const app_dir = ${s(kit.appDir)};
- export const relative = ${svelte_config.kit.paths.relative};
+ export const relative = ${relative};
const initial = { base, assets };
-9
View File
@@ -1,9 +0,0 @@
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run build && npm run preview',
port: 4173
},
testDir: 'e2e'
});
+12
View File
@@ -0,0 +1,12 @@
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -e
# ---------------------------------------------------------------------------
# 1. Resolve any previously failed migrations so deploy can proceed.
# Only migrations explicitly marked as "Failed" in the status output are
# resolved. We grep for lines containing "Failed" and extract the name.
# ---------------------------------------------------------------------------
echo "[migrate] Checking for failed migrations..."
STATUS_OUTPUT=$(bunx prisma migrate status 2>&1 || true)
echo "$STATUS_OUTPUT"
# Only resolve migrations whose status line explicitly says "Failed"
echo "$STATUS_OUTPUT" | grep -i "failed" | grep -oE '[0-9]{14}_[a-zA-Z_]+' | while read -r MIGRATION; do
echo "[migrate] Resolving failed migration: $MIGRATION"
bunx prisma migrate resolve --rolled-back "$MIGRATION" || true
done
# ---------------------------------------------------------------------------
# 2. Deploy all pending migrations from the migrations directory.
# ---------------------------------------------------------------------------
echo "[migrate] Running prisma migrate deploy..."
bunx prisma migrate deploy
@@ -0,0 +1,76 @@
-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"sessionKey" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
"refreshTokenGenerated" BOOLEAN NOT NULL DEFAULT false,
"refreshedAt" TIMESTAMP(3),
"invalidatedAt" TIMESTAMP(3),
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"permissions" TEXT,
"login" TEXT NOT NULL,
"name" TEXT,
"email" TEXT NOT NULL,
"emailVerified" TIMESTAMP(3),
"image" TEXT,
"userId" TEXT NOT NULL,
"token" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Role" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"moniker" TEXT NOT NULL,
"permissions" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Role_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "_RoleToUser" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL,
CONSTRAINT "_RoleToUser_AB_pkey" PRIMARY KEY ("A","B")
);
-- CreateIndex
CREATE UNIQUE INDEX "Session_sessionKey_key" ON "Session"("sessionKey");
-- CreateIndex
CREATE UNIQUE INDEX "User_login_key" ON "User"("login");
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "User_userId_key" ON "User"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "Role_moniker_key" ON "Role"("moniker");
-- CreateIndex
CREATE INDEX "_RoleToUser_B_index" ON "_RoleToUser"("B");
-- AddForeignKey
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_RoleToUser" ADD CONSTRAINT "_RoleToUser_A_fkey" FOREIGN KEY ("A") REFERENCES "Role"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_RoleToUser" ADD CONSTRAINT "_RoleToUser_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,73 @@
-- CreateTable
CREATE TABLE "Company" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"cw_CompanyId" INTEGER NOT NULL,
"cw_Identifier" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Company_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CredentialType" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"permissionScope" TEXT NOT NULL,
"icon" TEXT,
"fields" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CredentialType_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SecureValue" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"content" TEXT NOT NULL,
"hash" TEXT NOT NULL,
"credentialId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecureValue_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Credential" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"notes" TEXT,
"subCredentialOfId" TEXT,
"typeId" TEXT NOT NULL,
"fields" JSONB NOT NULL,
"companyId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Credential_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Company_cw_CompanyId_key" ON "Company"("cw_CompanyId");
-- CreateIndex
CREATE UNIQUE INDEX "Company_cw_Identifier_key" ON "Company"("cw_Identifier");
-- CreateIndex
CREATE UNIQUE INDEX "CredentialType_name_key" ON "CredentialType"("name");
-- AddForeignKey
ALTER TABLE "SecureValue" ADD CONSTRAINT "SecureValue_credentialId_fkey" FOREIGN KEY ("credentialId") REFERENCES "Credential"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Credential" ADD CONSTRAINT "Credential_subCredentialOfId_fkey" FOREIGN KEY ("subCredentialOfId") REFERENCES "Credential"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Credential" ADD CONSTRAINT "Credential_typeId_fkey" FOREIGN KEY ("typeId") REFERENCES "CredentialType"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Credential" ADD CONSTRAINT "Credential_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,63 @@
-- CreateTable
CREATE TABLE "UnifiSite" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"siteId" TEXT NOT NULL,
"companyId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "UnifiSite_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CatalogItem" (
"id" TEXT NOT NULL,
"cwCatalogId" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"customerDescription" TEXT,
"internalNotes" TEXT,
"manufacturer" TEXT,
"manufactureCwId" INTEGER,
"partNumber" TEXT,
"vendorName" TEXT,
"vendorSku" TEXT,
"vendorCwId" INTEGER,
"price" DOUBLE PRECISION NOT NULL,
"cost" DOUBLE PRECISION NOT NULL,
"inactive" BOOLEAN NOT NULL DEFAULT false,
"salesTaxable" BOOLEAN NOT NULL DEFAULT true,
"onHand" INTEGER NOT NULL DEFAULT 0,
"cwLastUpdated" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CatalogItem_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "_LinkedItems" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL,
CONSTRAINT "_LinkedItems_AB_pkey" PRIMARY KEY ("A","B")
);
-- CreateIndex
CREATE UNIQUE INDEX "UnifiSite_siteId_key" ON "UnifiSite"("siteId");
-- CreateIndex
CREATE UNIQUE INDEX "CatalogItem_cwCatalogId_key" ON "CatalogItem"("cwCatalogId");
-- CreateIndex
CREATE INDEX "_LinkedItems_B_index" ON "_LinkedItems"("B");
-- AddForeignKey
ALTER TABLE "UnifiSite" ADD CONSTRAINT "UnifiSite_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkedItems" ADD CONSTRAINT "_LinkedItems_A_fkey" FOREIGN KEY ("A") REFERENCES "CatalogItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkedItems" ADD CONSTRAINT "_LinkedItems_B_fkey" FOREIGN KEY ("B") REFERENCES "CatalogItem"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,57 @@
-- CreateTable
CREATE TABLE "Opportunity" (
"id" TEXT NOT NULL,
"cwOpportunityId" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"notes" TEXT,
"typeName" TEXT,
"typeCwId" INTEGER,
"stageName" TEXT,
"stageCwId" INTEGER,
"statusName" TEXT,
"statusCwId" INTEGER,
"priorityName" TEXT,
"priorityCwId" INTEGER,
"ratingName" TEXT,
"ratingCwId" INTEGER,
"source" TEXT,
"campaignName" TEXT,
"campaignCwId" INTEGER,
"primarySalesRepName" TEXT,
"primarySalesRepIdentifier" TEXT,
"primarySalesRepCwId" INTEGER,
"secondarySalesRepName" TEXT,
"secondarySalesRepIdentifier" TEXT,
"secondarySalesRepCwId" INTEGER,
"companyCwId" INTEGER,
"companyName" TEXT,
"contactCwId" INTEGER,
"contactName" TEXT,
"siteCwId" INTEGER,
"siteName" TEXT,
"customerPO" TEXT,
"totalSalesTax" DOUBLE PRECISION NOT NULL DEFAULT 0,
"locationName" TEXT,
"locationCwId" INTEGER,
"departmentName" TEXT,
"departmentCwId" INTEGER,
"expectedCloseDate" TIMESTAMP(3),
"pipelineChangeDate" TIMESTAMP(3),
"dateBecameLead" TIMESTAMP(3),
"closedDate" TIMESTAMP(3),
"closedFlag" BOOLEAN NOT NULL DEFAULT false,
"closedByName" TEXT,
"closedByCwId" INTEGER,
"companyId" TEXT,
"cwLastUpdated" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Opportunity_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Opportunity_cwOpportunityId_key" ON "Opportunity"("cwOpportunityId");
-- AddForeignKey
ALTER TABLE "Opportunity" ADD CONSTRAINT "Opportunity_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "CatalogItem" ADD COLUMN "identifier" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "CatalogItem_identifier_key" ON "CatalogItem"("identifier");
@@ -0,0 +1,11 @@
-- AlterTable: User
ALTER TABLE "User" ADD COLUMN "cwIdentifier" TEXT;
-- AlterTable: CatalogItem
ALTER TABLE "CatalogItem" ADD COLUMN "category" TEXT;
ALTER TABLE "CatalogItem" ADD COLUMN "categoryCwId" INTEGER;
ALTER TABLE "CatalogItem" ADD COLUMN "subcategory" TEXT;
ALTER TABLE "CatalogItem" ADD COLUMN "subcategoryCwId" INTEGER;
-- AlterTable: Opportunity
ALTER TABLE "Opportunity" ADD COLUMN "productSequence" INTEGER[] DEFAULT ARRAY[]::INTEGER[];
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+246
View File
@@ -0,0 +1,246 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
model Session {
id String @id @default(uuid())
sessionKey String @unique @default(cuid())
userId String
expires DateTime
refreshTokenGenerated Boolean @default(false)
refreshedAt DateTime?
invalidatedAt DateTime?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
id String @id @default(cuid())
roles Role[]
permissions String?
login String @unique
name String?
email String @unique
emailVerified DateTime?
image String?
cwIdentifier String?
userId String @unique
token String?
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Role {
id String @id @default(uuid())
title String
moniker String @unique // e.g. admin, super_admin, moderator
permissions String
users User[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model UnifiSite {
id String @id @default(cuid())
name String
siteId String @unique
companyId String?
company Company? @relation(fields: [companyId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Company {
id String @id @default(cuid())
name String
cw_CompanyId Int @unique
cw_Identifier String @unique
credentials Credential[]
unifiSites UnifiSite[]
opportunities Opportunity[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model CatalogItem {
id String @id @default(cuid())
cwCatalogId Int @unique
identifier String? @unique
name String
description String?
customerDescription String?
internalNotes String?
linkedItems CatalogItem[] @relation("LinkedItems")
linkedTo CatalogItem[] @relation("LinkedItems")
category String?
categoryCwId Int?
subcategory String?
subcategoryCwId Int?
manufacturer String?
manufactureCwId Int?
partNumber String?
vendorName String?
vendorSku String?
vendorCwId Int?
price Float
cost Float
inactive Boolean @default(false)
salesTaxable Boolean @default(true)
onHand Int @default(0)
cwLastUpdated DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Opportunity {
id String @id @default(cuid())
cwOpportunityId Int @unique
name String
notes String?
// Stage / status / priority / type / rating stored as JSON references
// so we don't need separate lookup tables for CW enums
typeName String?
typeCwId Int?
stageName String?
stageCwId Int?
statusName String?
statusCwId Int?
priorityName String?
priorityCwId Int?
ratingName String?
ratingCwId Int?
source String?
campaignName String?
campaignCwId Int?
// Sales rep references
primarySalesRepName String?
primarySalesRepIdentifier String?
primarySalesRepCwId Int?
secondarySalesRepName String?
secondarySalesRepIdentifier String?
secondarySalesRepCwId Int?
// Company / contact / site
companyCwId Int?
companyName String?
contactCwId Int?
contactName String?
siteCwId Int?
siteName String?
customerPO String?
// Financials
totalSalesTax Float @default(0)
// Location / department
locationName String?
locationCwId Int?
departmentName String?
departmentCwId Int?
// Dates
expectedCloseDate DateTime?
pipelineChangeDate DateTime?
dateBecameLead DateTime?
closedDate DateTime?
closedFlag Boolean @default(false)
closedByName String?
closedByCwId Int?
// Internal relation to Company (optional, linked by cwCompanyId)
companyId String?
company Company? @relation(fields: [companyId], references: [id])
// Local product sequence — array of CW forecast item IDs in display order.
// When present, fetchProducts() uses this order instead of CW sequenceNumber.
productSequence Int[] @default([])
cwLastUpdated DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model CredentialType {
id String @id @default(cuid())
name String @unique
permissionScope String
icon String?
fields Json
credentials Credential[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model SecureValue {
id String @id @default(cuid())
name String
content String // Encrypted content
hash String // Hash of the original content for integrity verification and Search
credentialId String
credential Credential @relation(fields: [credentialId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Credential {
id String @id @default(cuid())
name String
notes String?
subCredentialOfId String?
subCredentialOf Credential? @relation("SubCredentials", fields: [subCredentialOfId], references: [id], onDelete: Cascade)
subCredentials Credential[] @relation("SubCredentials")
typeId String
type CredentialType @relation(fields: [typeId], references: [id], onDelete: Cascade)
fields Json
companyId String
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
securevalues SecureValue[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
BIN
View File
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
export default class AuthenticationError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "AuthenticationError";
this.message = message;
this.cause = cause;
}
}
+11
View File
@@ -0,0 +1,11 @@
export default class AuthorizationError extends Error {
public status: number;
constructor(message: string, cause?: string, status?: number) {
super();
this.name = "AuthorizationError";
this.status = status ?? 401;
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class BodyError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "BodyError";
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class ExpiredAccessTokenError extends Error {
constructor(cause?: string) {
super();
this.name = "ExpiredAccessTokenError";
this.message = "The provided access token has expired.";
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class ExpiredRefreshTokenError extends Error {
constructor(cause?: string) {
super();
this.name = "ExpiredRefreshTokenError";
this.message = "The provided refresh token has expired.";
this.cause = cause;
}
}
+16
View File
@@ -0,0 +1,16 @@
export default class GenericError extends Error {
public status: number;
constructor(info: {
name: string;
message: string;
cause?: string;
status?: number;
}) {
super();
this.name = info.name;
this.status = info.status ?? 400;
this.message = info.message;
this.cause = info.cause;
}
}
+11
View File
@@ -0,0 +1,11 @@
export default class InsufficientPermission extends Error {
public status: number;
constructor(message: string, cause?: string) {
super();
this.name = "InsufficientPermission";
this.status = 403;
this.message = message;
this.cause = cause;
}
}
+9
View File
@@ -0,0 +1,9 @@
export default class MissingBodyValue extends Error {
constructor(valueName: string) {
super();
this.name = "MissingBodyValue";
this.message = `Value '${valueName}' is missing from the body.`;
this.cause =
"A value that was required by the body of this request is missing.";
}
}
@@ -0,0 +1,8 @@
export default class PermissionsVerificationError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "PermissionsVerificationError";
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class RoleError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "RoleError";
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class SessionError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "SessionError";
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class SessionTokenError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "SessionTokenError";
this.message = message;
this.cause = cause;
}
}
+8
View File
@@ -0,0 +1,8 @@
export default class UserError extends Error {
constructor(message: string, cause?: string) {
super();
this.name = "UserError";
this.message = message;
this.cause = cause;
}
}
+3
View File
@@ -0,0 +1,3 @@
export { default as redirect } from "./redirect";
export { default as refresh } from "./refresh";
export { default as uri } from "./uri";
+39
View File
@@ -0,0 +1,39 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import * as msal from "@azure/msal-node";
import { API_BASE_URL, io, msalClient } from "../../constants";
import { users } from "../../managers/users";
/* /v1/auth/redirect */
export default createRoute("get", ["/redirect"], async (c) => {
c.status(200);
const tokenRequest: msal.AuthorizationCodeRequest = {
code: c.req.query().code as string,
scopes: ["user.read"],
redirectUri: `${API_BASE_URL}/v1/auth/redirect`,
};
const authResult = await msalClient.acquireTokenByCode(tokenRequest);
const callbackKey = c.req.query().state as string;
const tokens = await users.authenticate(authResult);
io.of(`/auth_callback`).emit(`auth:login:callback:${callbackKey}`, {
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
});
// Close the window because duh
return c.html(
`<script>
window.close();
</script>`,
);
return c.json({
status: 200,
message: "Auth Redirect Endpoint",
data: authResult,
successful: true,
});
});
+26
View File
@@ -0,0 +1,26 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { sessions } from "../../managers/sessions";
/* /v1/auth/refresh */
export default createRoute("post", ["/refresh"], async (c) => {
c.status(201);
const refreshToken = c.req.header("x-refresh-token") || "";
const session = await sessions.fetch({
refreshToken: refreshToken,
});
const newAccessToken = await session.refresh(refreshToken);
return c.json({
status: 201,
message: "Token refreshed successfully!",
data: {
accessToken: newAccessToken,
refreshToken,
},
successful: true,
});
});
+23
View File
@@ -0,0 +1,23 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { API_BASE_URL } from "../../constants";
import cuid from "cuid";
/* /v1/auth/uri */
export default createRoute("get", ["/uri"], (c) => {
c.status(200);
const callbackKey = cuid();
const redirectUri = encodeURIComponent(`${API_BASE_URL}/v1/auth/redirect`);
const msUri = `https://login.microsoftonline.com/${process.env.MICROSOFT_TENANT_ID}/oauth2/v2.0/authorize?client_id=${process.env.MICROSOFT_CLIENT_ID}&response_type=code&redirect_uri=${redirectUri}&scope=openid+User.Read&state=${callbackKey}&prompt=login`;
return c.json({
status: 200,
message: "Successfully fetch Auth URI",
data: {
uri: msUri,
callbackKey: callbackKey,
},
successful: true,
});
});
+26
View File
@@ -0,0 +1,26 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../../modules/api-utils/createRoute";
import { companies } from "../../../managers/companies";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
/* /v1/company/companies/[id]/configurations */
export default createRoute(
"get",
["/companies/:identifier/configurations"],
async (c) => {
const company = await companies.fetch(c.req.param("identifier"));
const configurations = await company.fetchConfigurations();
const response = apiResponse.successful(
"Company Configurations Fetched Successfully!",
configurations,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["company.fetch", "company.fetch.configurations"],
}),
);
+64
View File
@@ -0,0 +1,64 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../../modules/api-utils/createRoute";
import { companies } from "../../../managers/companies";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import GenericError from "../../../Errors/GenericError";
import { processObjectValuePerms } from "../../../modules/permission-utils/processObjectPermissions";
/* /v1/company/companies/[id] */
export default createRoute(
"get",
["/companies/:identifier"],
async (c) => {
const company = await companies.fetch(c.req.param("identifier"));
const includeAddress = c.req.query("includeAddress") === "true";
const includePrimaryContact =
c.req.query("includePrimaryContact") === "true";
const includeAllContacts = c.req.query("includeAllContacts") === "true";
// Check for address-specific permission if includeAddress is requested
if (includeAddress) {
const user = c.get("user");
if (!user || !(await user.hasPermission("company.fetch.address"))) {
throw new GenericError({
name: "InsufficientPermission",
message: "You do not have permission to view company addresses.",
status: 403,
});
}
}
// Check for contacts permission if includeAllContacts is requested
if (includeAllContacts) {
const user = c.get("user");
if (!user || !(await user.hasPermission("company.fetch.contacts"))) {
throw new GenericError({
name: "InsufficientPermission",
message: "You do not have permission to view company contacts.",
status: 403,
});
}
}
const companyData = company.toJson({
includeAddress,
includePrimaryContact,
includeAllContacts,
});
const gatedData = await processObjectValuePerms(
companyData,
"obj.company",
c.get("user"),
);
const response = apiResponse.successful(
"Company Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["company.fetch"] }),
);
+32
View File
@@ -0,0 +1,32 @@
import { createRoute } from "../../../modules/api-utils/createRoute";
import { unifiSites } from "../../../managers/unifiSites";
import { companies } from "../../../managers/companies";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import { processObjectValuePerms } from "../../../modules/permission-utils/processObjectPermissions";
/* GET /v1/company/companies/:identifier/unifi/sites */
export default createRoute(
"get",
["/companies/:identifier/unifi/sites"],
async (c) => {
const company = await companies.fetch(c.req.param("identifier"));
const sites = await unifiSites.fetchByCompany(company.id);
const gatedData = await Promise.all(
sites.map((site) =>
processObjectValuePerms(site, "obj.unifiSite", c.get("user")),
),
);
const response = apiResponse.successful(
"Company UniFi Sites Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["unifi.access", "company.fetch"],
}),
);
+25
View File
@@ -0,0 +1,25 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { companies } from "../../managers/companies";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
/* /v1/company/count */
export default createRoute(
"get",
["/count"],
async (c) => {
const count = await companies.count();
const response = apiResponse.successful(
"Company count fetched successfully!",
{
count,
},
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["company.fetch.many"] }),
);
+50
View File
@@ -0,0 +1,50 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { companies } from "../../managers/companies";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/company/companies */
export default createRoute(
"get",
["/companies"],
async (c) => {
const page = new Number(c.req.query("page") ?? 1) as number;
const rpp = new Number(c.req.query("rpp") ?? 30) as number; // Records Per Page
const search = c.req.query("search") as string;
const data = search
? await companies.search(search, page, rpp)
: await companies.fetchPages(page, rpp);
const companyQty = search
? (await companies.search(search, 1, 999999)).length
: await companies.count();
const gatedData = await Promise.all(
data.map((item) =>
processObjectValuePerms(item, "obj.company", c.get("user")),
),
);
let response = apiResponse.successful(
"Companies Fetched Successfully!",
gatedData,
{
pagination: {
previousPage: page == 1 ? null : page - 1, // Previous Page
currentPage: page, // Current Page
nextPage: page >= companyQty / rpp ? null : page + 1, // Next Page
totalPages: Math.ceil(companyQty / rpp), // Total Number of Pages
totalRecords: companyQty, // Total Number of Records
listedRecords: rpp, // Total Number of Records being recieved at time of request.
},
},
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["company.fetch.many"] }),
);
+7
View File
@@ -0,0 +1,7 @@
import { default as fetchAll } from "./fetchAll";
import { default as fetch } from "./[id]/fetch";
import { default as configurations } from "./[id]/configurations";
import { default as unifiSites } from "./[id]/unifiSites";
import { default as count } from "./count";
export { configurations, count, fetch, fetchAll, unifiSites };
+49
View File
@@ -0,0 +1,49 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { z } from "zod";
import { ValueType } from "../../modules/credentials/credentialTypeDefs";
/* /v1/credential-type */
export default createRoute(
"post",
["/"],
async (c) => {
const body = await c.req.json();
const fieldSchema: z.ZodType<any> = z.lazy(() =>
z.object({
id: z.string(),
name: z.string(),
required: z.boolean(),
secure: z.boolean(),
valueType: z.enum(Object.values(ValueType)),
subFields: z.array(fieldSchema).optional(),
}),
);
const schema = z.object({
name: z.string().min(1, "Name is required"),
permissionScope: z.string().min(1, "Permission scope is required"),
icon: z.string().optional(),
fields: z.array(fieldSchema),
});
const data = schema.parse(body);
console.log("Creating Credential Type with data:", data);
const credentialType = await credentialTypes.create(data as any);
const response = apiResponse.created(
"Credential Type Created Successfully!",
credentialType.toJson(),
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential_type.create"] }),
);
+23
View File
@@ -0,0 +1,23 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
/* /v1/credential-type/:id */
export default createRoute(
"delete",
["/:id"],
async (c) => {
await credentialTypes.delete(c.req.param("id"));
const response = apiResponse.successful(
"Credential Type Deleted Successfully!",
null,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential_type.delete"] }),
);
+32
View File
@@ -0,0 +1,32 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/credential-type/:identifier */
export default createRoute(
"get",
["/:identifier"],
async (c) => {
const credentialType = await credentialTypes.fetch(
c.req.param("identifier"),
);
const gatedData = await processObjectValuePerms(
credentialType.toJson({ includeCredentialCount: true }),
"obj.credentialType",
c.get("user"),
);
const response = apiResponse.successful(
"Credential Type Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential_type.fetch"] }),
);
+34
View File
@@ -0,0 +1,34 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/credential-type */
export default createRoute(
"get",
["/"],
async (c) => {
const allCredentialTypes = await credentialTypes.fetchAll();
const gatedData = await Promise.all(
allCredentialTypes.map((ct) =>
processObjectValuePerms(
ct.toJson({ includeCredentialCount: true }),
"obj.credentialType",
c.get("user"),
),
),
);
const response = apiResponse.successful(
"Credential Types Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential_type.fetch.many"] }),
);
@@ -0,0 +1,33 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/credential-type/:id/credentials */
export default createRoute(
"get",
["/:id/credentials"],
async (c) => {
const credentialType = await credentialTypes.fetch(c.req.param("id"));
const credentials = await credentialType.fetchCredentials();
const gatedData = await Promise.all(
credentials.map((cred) =>
processObjectValuePerms(cred.toJson(), "obj.credential", c.get("user")),
),
);
const response = apiResponse.successful(
"Credentials Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["credential_type.fetch", "credential.fetch.many"],
}),
);
+15
View File
@@ -0,0 +1,15 @@
import { default as fetch } from "./fetch";
import { default as fetchAll } from "./fetchAll";
import { default as create } from "./create";
import { default as update } from "./update";
import { default as deleteCredentialType } from "./delete";
import { default as fetchCredentials } from "./fetchCredentials";
export {
fetch,
fetchAll,
create,
update,
deleteCredentialType as delete,
fetchCredentials,
};
+48
View File
@@ -0,0 +1,48 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentialTypes } from "../../managers/credentialTypes";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { z } from "zod";
import { ValueType } from "../../modules/credentials/credentialTypeDefs";
/* /v1/credential-type/:id */
export default createRoute(
"patch",
["/:id"],
async (c) => {
const body = await c.req.json();
const credentialType = await credentialTypes.fetch(c.req.param("id"));
const fieldSchema: z.ZodType<any> = z.lazy(() =>
z.object({
id: z.string(),
name: z.string(),
required: z.boolean(),
secure: z.boolean(),
valueType: z.enum(Object.values(ValueType)),
subFields: z.array(fieldSchema).optional(),
}),
);
const schema = z.object({
name: z.string().optional(),
permissionScope: z.string().optional(),
icon: z.string().optional(),
fields: z.array(fieldSchema).optional(),
});
const data = schema.parse(body);
await credentialType.update(data as any);
const response = apiResponse.successful(
"Credential Type Updated Successfully!",
credentialType.toJson(),
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential_type.update"] }),
);
+48
View File
@@ -0,0 +1,48 @@
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { z } from "zod";
/* POST /v1/credential/credentials/:id/sub-credentials */
export default createRoute(
"post",
["/credentials/:id/sub-credentials"],
async (c) => {
const parentId = c.req.param("id");
const body = await c.req.json();
const schema = z.object({
fieldId: z.string().min(1, "Field ID is required"),
name: z.string().min(1, "Name is required"),
fields: z.array(
z.object({
fieldId: z.string(),
value: z.string(),
}),
),
});
const data = schema.parse(body);
const subCredential = await credentials.addSubCredential(
parentId,
data.fieldId,
{
name: data.name,
fields: data.fields,
},
);
const response = apiResponse.created(
"Sub-Credential Created Successfully!",
subCredential.toJson(),
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["credential.fetch", "credential.sub_credentials.create"],
}),
);
+57
View File
@@ -0,0 +1,57 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { z } from "zod";
/* /v1/credential */
export default createRoute(
"post",
["/credentials"],
async (c) => {
const body = await c.req.json();
const schema = z.object({
name: z.string().min(1, "Name is required"),
notes: z.string().optional(),
typeId: z.string().min(1, "Type ID is required"),
companyId: z.string().min(1, "Company ID is required"),
fields: z.array(
z.object({
fieldId: z.string(),
value: z.string(),
}),
),
subCredentials: z
.record(
z.string(),
z.array(
z.object({
name: z.string().min(1, "Sub-credential name is required"),
fields: z.array(
z.object({
fieldId: z.string(),
value: z.string(),
}),
),
}),
),
)
.optional(),
});
const data = schema.parse(body);
const credential = await credentials.create(data);
const response = apiResponse.created(
"Credential Created Successfully!",
credential.toJson(),
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential.create"] }),
);
+23
View File
@@ -0,0 +1,23 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
/* /v1/credential/:id */
export default createRoute(
"delete",
["/credentials/:id"],
async (c) => {
await credentials.delete(c.req.param("id"));
const response = apiResponse.successful(
"Credential Deleted Successfully!",
null,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential.delete"] }),
);
+29
View File
@@ -0,0 +1,29 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/credential/:id */
export default createRoute(
"get",
["/credentials/:id"],
async (c) => {
const credential = await credentials.fetch(c.req.param("id"));
const gatedData = await processObjectValuePerms(
credential.toJson(),
"obj.credential",
c.get("user"),
);
const response = apiResponse.successful(
"Credential Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential.fetch"] }),
);
+32
View File
@@ -0,0 +1,32 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* /v1/credential/company/:companyId */
export default createRoute(
"get",
["/credentials/company/:companyId"],
async (c) => {
const companyCredentials = await credentials.fetchByCompany(
c.req.param("companyId"),
);
const gatedData = await Promise.all(
companyCredentials.map((cred) =>
processObjectValuePerms(cred.toJson(), "obj.credential", c.get("user")),
),
);
const response = apiResponse.successful(
"Company Credentials Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["credential.fetch.many"] }),
);
+26
View File
@@ -0,0 +1,26 @@
import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
/* /v1/credential/:id/fields */
export default createRoute(
"get",
["/credentials/:id/fields"],
async (c) => {
const credential = await credentials.fetch(c.req.param("id"));
const fields = await credential.fetchAllFieldValues();
const response = apiResponse.successful(
"Credential Fields Fetched Successfully!",
fields,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["credential.fetch", "credential.fields.fetch"],
}),
);
@@ -0,0 +1,36 @@
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";
/* GET /v1/credential/credentials/:id/sub-credentials */
export default createRoute(
"get",
["/credentials/:id/sub-credentials"],
async (c) => {
const parentId = c.req.param("id");
// Verify the parent credential exists
await credentials.fetch(parentId);
const subCredentials = await credentials.fetchSubCredentials(parentId);
const gatedData = await Promise.all(
subCredentials.map((sc) =>
processObjectValuePerms(sc.toJson(), "obj.credential", c.get("user")),
),
);
const response = apiResponse.successful(
"Sub-Credentials Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({
permissions: ["credential.fetch", "credential.sub_credentials.fetch"],
}),
);

Some files were not shown because too many files have changed in this diff Show More