diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 1d86058..0000000 --- a/.babelrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "presets": ["@vue/app"] -} \ No newline at end of file diff --git a/.dockerignore b/.dockerignore index 5d3f495..fd22a59 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,11 @@ +.git +.data +.nuxt +.output node_modules -db-data +dist build -dist \ No newline at end of file +docker +*.db +*.db-* +.env diff --git a/.env.sample b/.env.sample deleted file mode 100644 index 073563f..0000000 --- a/.env.sample +++ /dev/null @@ -1,6 +0,0 @@ -DB_USER=zeithub -DB_PASSWD=zeithub -DB_NAME=zeithub -JWT_SECRET=secret -NODE_ENV=development -CHROME_BIN="/snap/bin/chromium" \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 3329e29..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "env": { - "browser": true, - "commonjs": true, - "es6": true, - "node": true - }, - "extends": "eslint:recommended", - "parserOptions": { - "sourceType": "module", - "ecmaVersion": 2017 - }, - "rules": { - "indent": [ - "error", - 2 - ], - "linebreak-style": [ - "error", - "unix" - ], - "quotes": [ - "error", - "single" - ], - "semi": [ - "error", - "always" - ], - "prefer-arrow-callback": [ "error", { "allowNamedFunctions": true } ] - } -} \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ddbbf14 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,27 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + cache: npm + + # GitHub's Ubuntu runners ship Google Chrome; the PDF test uses it. + - run: echo "CHROME_BIN=$(command -v google-chrome)" >> "$GITHUB_ENV" + + - run: npm ci + - run: npm run lint + - run: npx prettier --check . + - run: npm run typecheck + - run: npm test + - run: npm run build diff --git a/.gitignore b/.gitignore index 8fc46c8..2fc35f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,22 @@ -db-data/ -docker/ +# Dependencies and build output node_modules/ -.vagrant -.env +.nuxt/ +.output/ dist/ build/ + +# Local data +.data/ +*.db +*.db-shm +*.db-wal +docker/ + +# Env +.env +.env.* +!example.env + +# Misc +.DS_Store +.vagrant diff --git a/.nvmrc b/.nvmrc index 72c7744..a45fd52 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -18.12.1 \ No newline at end of file +24 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..daf4ff8 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +.nuxt +.output +.data +node_modules +server/db/migrations +package-lock.json +flake.lock diff --git a/.prettierrc b/.prettierrc index 5b1d61d..acf6257 100644 --- a/.prettierrc +++ b/.prettierrc @@ -4,5 +4,6 @@ "semi": true, "singleQuote": true, "bracketSpacing": true, - "arrowParens": "avoid" -} \ No newline at end of file + "arrowParens": "avoid", + "trailingComma": "es5" +} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8473882..0000000 --- a/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -services: - - mysql -node_js: "11" -env: - - DB_USER=travis - - DB_NAME_TEST=zeithub_test diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..1882997 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,53 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project + +Zeithub is an open source invoicing app for freelancers (clients, projects, bank accounts, addresses, line-item invoices with PDF export). It is a single Nuxt 4 app: a Vue 3.5 SPA in `app/` and a Nitro API in `server/`, backed by one SQLite file through Drizzle ORM. + +## Commands + +```bash +npm install # also runs `nuxt prepare` (generates .nuxt/ types) +npm run dev # http://localhost:3002, DB at .data/zeithub.db +npm run build && npm start # production build in .output/ +npm test # Vitest: unit + e2e projects +npm run lint # ESLint (flat config from @nuxt/eslint) +npm run format # Prettier +npm run typecheck # nuxt typecheck (vue-tsc) +npm run db:generate -- --name my-change # migration from schema changes +``` + +- Run one project: `npx vitest run --project unit` (fast, no server) or `--project e2e` (builds the app, runs it against a temp SQLite file). Filter with `-t "isolation"`. +- The e2e PDF test needs Chrome/Chromium: it uses `CHROME_BIN`, or Google Chrome's default macOS path. It is skipped if neither exists. +- Env vars: `DATABASE_PATH`, `NUXT_APP_SECRET` (required in production, 32+ chars; generated in dev), `CHROME_BIN`, `NUXT_SESSION_COOKIE_SECURE`. See `example.env`. +- Node 24 (`.nvmrc`, `flake.nix`, Dockerfile). + +## Architecture + +**Layout.** `app/` is the client (pages, components, layouts, stores, middleware). `server/` is Nitro (`api/`, `utils/`, `plugins/`, `db/`). `shared/` is imported by both. Nuxt auto-imports `app/{components,composables,utils,stores}`, `server/utils`, `shared/utils` and `shared/types`. Other files (e.g. `shared/invoice/document.ts`, `server/db/schema.ts`) are imported explicitly (`#shared/...` or relative paths). + +**Database.** `server/db/schema.ts` is the source of truth. Drizzle uses `casing: 'snake_case'`, so code is camelCase and columns are snake_case with no aliasing. Money is integer cents (`unitPriceCents`, `discountCents`); `taxRate` is a percent (real); invoice dates are ISO `YYYY-MM-DD` text. Foreign keys are enforced. `server/utils/db.ts` exposes one shared connection via `useDb()` (WAL mode). `server/plugins/database.ts` runs migrations from `server/db/migrations/` and seeds currencies on startup. The build copies migrations to `.output/server/migrations`. The driver is synchronous (better-sqlite3): use `.get()`, `.all()`, `.run()`, and `.sync()` on relational `db.query.*` calls. Transaction callbacks must be synchronous. + +**API (`server/api`).** File-based routes, one handler per file named by method (`index.get.ts`, `[id].put.ts`, …). Each handler: + +1. calls `requireUser(event)` → `userId`, +2. validates input with `readBodyAs(event, schema)` / `getIdParam(event)` / `getParamsAs(...)` (`server/utils/validate.ts`), +3. queries with Drizzle, always filtering with `eq(table.userId, userId)`. + +When a body references other rows (clientId, bankAccountId, projectId…), call `assertReferencesOwned` (`server/utils/ownership.ts`) so users can't attach each other's data. Errors use `createError({ statusCode })`. 400 responses carry `data.issues: [{ path, message }]`. Responses are plain data, with no `{ success }` envelope. Deleting a client, address or bank account used by an invoice returns 409. + +**Validation schemas.** `shared/utils/schemas.ts` holds the zod schemas for every request body. The API validates with them, and forms run the same schema client-side (`validationMessages`) before submitting, so messages match. + +**Auth.** `nuxt-auth-utils`: a sealed, httpOnly cookie session holding `{ user: { id, name } }` (type in `shared/types/auth.d.ts`). Passwords are scrypt (`hashPassword`). Legacy bcrypt hashes (imported from MySQL) are verified with bcryptjs and rehashed on sign-in (`server/utils/users.ts`). Client side: `useUserSession()`; `app/middleware/auth.global.ts` guards pages; `app/plugins/unauthorized.client.ts` sends the user to `/signin` on any API 401. Nothing auth-related lives in localStorage. + +**Client.** Pages use ` diff --git a/app/components/AddressList.vue b/app/components/AddressList.vue new file mode 100644 index 0000000..4193267 --- /dev/null +++ b/app/components/AddressList.vue @@ -0,0 +1,114 @@ + + + diff --git a/app/components/AppCard.vue b/app/components/AppCard.vue new file mode 100644 index 0000000..d585490 --- /dev/null +++ b/app/components/AppCard.vue @@ -0,0 +1,21 @@ + + + diff --git a/app/components/AppSidebar.vue b/app/components/AppSidebar.vue new file mode 100644 index 0000000..8574e1d --- /dev/null +++ b/app/components/AppSidebar.vue @@ -0,0 +1,91 @@ + + + diff --git a/app/components/BankAccountList.vue b/app/components/BankAccountList.vue new file mode 100644 index 0000000..7094620 --- /dev/null +++ b/app/components/BankAccountList.vue @@ -0,0 +1,111 @@ + + + diff --git a/app/components/ChangePassword.vue b/app/components/ChangePassword.vue new file mode 100644 index 0000000..28c2819 --- /dev/null +++ b/app/components/ChangePassword.vue @@ -0,0 +1,63 @@ + + + diff --git a/app/components/ClientForm.vue b/app/components/ClientForm.vue new file mode 100644 index 0000000..caca403 --- /dev/null +++ b/app/components/ClientForm.vue @@ -0,0 +1,67 @@ + + + diff --git a/app/components/FormErrors.vue b/app/components/FormErrors.vue new file mode 100644 index 0000000..34ae8f7 --- /dev/null +++ b/app/components/FormErrors.vue @@ -0,0 +1,16 @@ + + + diff --git a/app/components/InvoiceForm.vue b/app/components/InvoiceForm.vue new file mode 100644 index 0000000..3f829a9 --- /dev/null +++ b/app/components/InvoiceForm.vue @@ -0,0 +1,453 @@ + - - diff --git a/src/client/routes/clients.vue b/src/client/routes/clients.vue deleted file mode 100644 index 90ffc34..0000000 --- a/src/client/routes/clients.vue +++ /dev/null @@ -1,55 +0,0 @@ - - - diff --git a/src/client/routes/create-project.vue b/src/client/routes/create-project.vue deleted file mode 100644 index 7ddf909..0000000 --- a/src/client/routes/create-project.vue +++ /dev/null @@ -1,57 +0,0 @@ - - - diff --git a/src/client/routes/edit-invoice.vue b/src/client/routes/edit-invoice.vue deleted file mode 100644 index a0e7d31..0000000 --- a/src/client/routes/edit-invoice.vue +++ /dev/null @@ -1,225 +0,0 @@ - - - diff --git a/src/client/routes/home.vue b/src/client/routes/home.vue deleted file mode 100644 index 79704dc..0000000 --- a/src/client/routes/home.vue +++ /dev/null @@ -1,5 +0,0 @@ - diff --git a/src/client/routes/index.ts b/src/client/routes/index.ts deleted file mode 100644 index dcf4f3d..0000000 --- a/src/client/routes/index.ts +++ /dev/null @@ -1,99 +0,0 @@ -// import Vue from 'vue'; -import { createRouter, createWebHistory } from 'vue-router'; -import Home from './home.vue'; -import Projects from './projects.vue'; -import Project from './project.vue'; -import CreateProject from './create-project.vue'; -import SignIn from './sign-in.vue'; -import SignOut from './sign-out.vue'; -import SignUp from './sign-up.vue'; -import Me from './me.vue'; -import Invoices from './invoices.vue'; -import Invoice from './invoice.vue'; -import AddInvoice from './add-invoice.vue'; -import EditInvoice from './edit-invoice.vue'; -import Clients from './clients.vue'; - -import { requireAuth, requireUnauth } from './../auth'; - -const router = createRouter({ - history: createWebHistory(), - routes: [ - { path: '/', name: 'Home', component: Home }, - { - path: '/projects', - name: 'Projects', - beforeEnter: requireAuth, - component: Projects, - }, - { - path: '/projects/new', - name: 'CreateProject', - beforeEnter: requireAuth, - component: CreateProject, - }, - { - path: '/projects/:slug', - name: 'Project', - beforeEnter: requireAuth, - component: Project, - }, - - { - path: '/signin', - name: 'SignIn', - beforeEnter: requireUnauth, - component: SignIn, - }, - { - path: '/signout', - name: 'SignOut', - beforeEnter: requireAuth, - component: SignOut, - }, - { - path: '/signup', - name: 'SignUp', - beforeEnter: requireUnauth, - component: SignUp, - }, - { - path: '/me', - name: 'Me', - beforeEnter: requireAuth, - component: Me, - }, - { - path: '/invoices', - name: 'Invoices', - beforeEnter: requireAuth, - component: Invoices, - }, - { - path: '/invoices/new', - name: 'AddInvoice', - beforeEnter: requireAuth, - component: AddInvoice, - }, - { - path: '/invoices/:id/edit', - name: 'EditInvoice', - beforeEnter: requireAuth, - component: EditInvoice, - }, - { - path: '/invoices/:id', - name: 'Invoice', - beforeEnter: requireAuth, - component: Invoice, - }, - { - path: '/clients', - name: 'Clients', - beforeEnter: requireAuth, - component: Clients, - }, - ], -}); - -export default router; diff --git a/src/client/routes/invoice.vue b/src/client/routes/invoice.vue deleted file mode 100644 index 0c339f0..0000000 --- a/src/client/routes/invoice.vue +++ /dev/null @@ -1,225 +0,0 @@ - - - - - diff --git a/src/client/routes/invoices.vue b/src/client/routes/invoices.vue deleted file mode 100644 index dea2e4e..0000000 --- a/src/client/routes/invoices.vue +++ /dev/null @@ -1,73 +0,0 @@ - - - diff --git a/src/client/routes/me.vue b/src/client/routes/me.vue deleted file mode 100644 index b12020d..0000000 --- a/src/client/routes/me.vue +++ /dev/null @@ -1,55 +0,0 @@ - - - diff --git a/src/client/routes/project.vue b/src/client/routes/project.vue deleted file mode 100644 index 829737d..0000000 --- a/src/client/routes/project.vue +++ /dev/null @@ -1,107 +0,0 @@ - - - - - diff --git a/src/client/routes/projects.vue b/src/client/routes/projects.vue deleted file mode 100644 index 79bb3fa..0000000 --- a/src/client/routes/projects.vue +++ /dev/null @@ -1,34 +0,0 @@ - - - diff --git a/src/client/routes/sign-in.vue b/src/client/routes/sign-in.vue deleted file mode 100644 index ee528b4..0000000 --- a/src/client/routes/sign-in.vue +++ /dev/null @@ -1,86 +0,0 @@ - - - diff --git a/src/client/routes/sign-out.vue b/src/client/routes/sign-out.vue deleted file mode 100644 index d88686b..0000000 --- a/src/client/routes/sign-out.vue +++ /dev/null @@ -1,15 +0,0 @@ - - - diff --git a/src/client/routes/sign-up.vue b/src/client/routes/sign-up.vue deleted file mode 100644 index af503b7..0000000 --- a/src/client/routes/sign-up.vue +++ /dev/null @@ -1,116 +0,0 @@ - - - diff --git a/src/client/sfc.d.ts b/src/client/sfc.d.ts deleted file mode 100644 index 8f6f410..0000000 --- a/src/client/sfc.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module '*.vue' { - import Vue from 'vue'; - export default Vue; -} diff --git a/src/client/stores/invoices.ts b/src/client/stores/invoices.ts deleted file mode 100644 index 2d7990c..0000000 --- a/src/client/stores/invoices.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { defineStore } from 'pinia'; -import { ref } from 'vue'; -import http from '../http'; - -export const useInvoicesStore = defineStore('invoices', () => { - const invoices = ref([]); - - async function fetchInvoices() { - const response = await http('/api/invoices', { - method: 'GET', - headers: { 'Content-Type': 'application/json' }, - }); - - const data = await response.json(); - - if (data.success) { - invoices.value = data.invoices; - } - } - - async function removeInvoice({ id }) { - if (window.confirm('Do you really want to delete this invoice?')) { - const response = await http(`/api/invoices/${id}`, { - headers: { 'Content-Type': 'application/json' }, - method: 'DELETE', - }); - - const data = await response.json(); - - if (data.success) { - fetchInvoices(); - } - } - } - - return { invoices, fetchInvoices, removeInvoice }; -}); diff --git a/src/client/stores/me.ts b/src/client/stores/me.ts deleted file mode 100644 index 4a7094f..0000000 --- a/src/client/stores/me.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { defineStore } from 'pinia'; -import { ref } from 'vue'; -import { Me } from '../../models'; -import http from '../http'; - -export const useMeStore = defineStore('me', () => { - const me = ref(new Me()); - - async function fetchMe() { - const response = await http('/api/me'); - const data = await response.json(); - - if (data.success) { - me.value = data.me; - } - } - - return { me, fetchMe }; -}); diff --git a/src/client/style.css b/src/client/style.css deleted file mode 100644 index ff697c1..0000000 --- a/src/client/style.css +++ /dev/null @@ -1,34 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -.btn-primary { - @apply bg-blue-500 bg-blue-500 text-white font-bold py-2 px-4 rounded; -} -.btn-primary:hover { - @apply bg-blue-700; -} -.btn-primary:focus { - @apply outline-none ring; -} - -.btn { - @apply bg-transparent text-blue-700 font-semibold py-2 px-4 border border-blue-500 rounded; -} -.btn:hover { - @apply border-transparent bg-blue-500 text-white; -} - -.input { - @apply shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight; -} -.input:focus { - @apply outline-none ring; -} - -.select { - @apply block appearance-none bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight; -} -.select:focus { - @apply outline-none bg-white border-gray-500; -} diff --git a/src/lib/components/invoice-info.ts b/src/lib/components/invoice-info.ts deleted file mode 100644 index 34f26eb..0000000 --- a/src/lib/components/invoice-info.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { defineComponent } from 'vue'; -import { formatDate, invoiceNum } from '../filters'; - -export default defineComponent({ - props: ['invoice', 'me'], - computed: { - invoiceNumber() { - return invoiceNum(this.invoice.number); - }, - invoiceDate() { - return formatDate(this.invoice.date, 'dd/MM/yyyy'); - }, - invoiceDueDate() { - return formatDate(this.invoice.dueDate, 'dd/MM/yyyy'); - }, - }, - template: ` - - - - - - - - - - - - - -
Invoice number{{ invoiceNumber }}
Date{{invoiceDate}}
Due date{{invoiceDueDate}}
- `, -}); diff --git a/src/lib/components/items-table.ts b/src/lib/components/items-table.ts deleted file mode 100644 index d7b2ce5..0000000 --- a/src/lib/components/items-table.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { defineComponent } from 'vue'; -import { currency, percentage } from '../filters'; - -export default defineComponent({ - methods: { currency, percentage }, - template: ` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DescriptionUnit priceQtyAmount ({{ invoice.currencyCode }})
{{ item.title }} - {{ currency(item.unitPrice, invoice) }} - {{ item.qty }}{{ (item.qty * item.unitPrice) | currency(invoice) }}
Net Amount - {{ computeNetAmount | currency(invoice) }} -
Discount - {{ invoice.discount | currency(invoice) }} -
Tax (VAT) - {{ invoice.tax | percentage }} -
Tax Amount - {{ taxAmount | currency(invoice) }} -
- Total ({{ invoice.currencyCode }}) - - {{ computeTotal | currency(invoice) }} -
- `, - props: ['invoice', 'items'], - computed: { - computeNetAmount() { - const netAmount = this.items.reduce((acc, item) => { - return acc + item.unitPrice * item.qty; - }, 0); - - currency(netAmount, this.invoice); - }, - - computeTotal() { - const subTotal = this.items.reduce((acc, item) => { - return acc + item.unitPrice * item.qty; - }, 0); - - let total = subTotal; - - if (this.invoice.discount > 0) { - total = total - this.invoice.discount; - } - - if (this.invoice.tax > 0) { - total = total * (1 + this.invoice.tax / 100); - } - - return total; - }, - - taxAmount() { - const total = this.computeTotal; - - return total - total / (1 + this.invoice.tax / 100); - }, - }, -}); diff --git a/src/lib/filters.ts b/src/lib/filters.ts deleted file mode 100644 index 6727760..0000000 --- a/src/lib/filters.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { DateTime } from 'luxon'; - -export const formatDate = (date, format = 'MMMM cccc yyyy, HH:mm:ss') => { - if (typeof date === 'object') { - return DateTime.fromJSDate(date).toFormat(format); - } - return DateTime.fromISO(date).toFormat(format); -}; - -export const currency = ( - amount, - invoice = { currencySign: '€', currencyLeading: false } -) => { - if (invoice.currencyLeading) { - return `${invoice.currencySign}${parseFloat(amount).toFixed(2)}`; - } - - return `${parseFloat(amount).toFixed(2)}${invoice.currencySign}`; -}; - -export const percentage = amount => `${parseFloat(amount).toFixed(2)}%`; - -export const totalHours = minutes => - `${Math.floor(minutes / 60)}:${(minutes % 60).toString().padStart(2, '0')}`; - -export const iban = value => { - const pattern = '#### #### #### #### #### ##'; - let i = 0; - - return pattern.replace(/#/g, () => value[i++]); -}; - -export const invoiceNum = number => number.toString().padStart(3, '0'); diff --git a/src/models.ts b/src/models.ts deleted file mode 100644 index 7759cd3..0000000 --- a/src/models.ts +++ /dev/null @@ -1,61 +0,0 @@ -import * as T from './types'; - -export class Activity implements T.Activity { - name: string = ''; - durationMinutes: number = 0; - durationDays: number = 0; - projectName: string = ''; - projectSlug: string = ''; -} - -export class Invoice implements T.Invoice { - id: number = 0; - name: string = ''; - tax: number = 0; - discount: number = 0; - rate: number = 0; - number: number = 0; - date: string = ''; - dueDate: string = ''; - memo: string = ''; - currencyCode: string = ''; - currencySign: string = ''; - currencyLeading: boolean = false; - bankAccountId: number = 0; - userAddressId: number = 0; - clientId: number = 0; -} - -export class BankAccount implements T.BankAccount { - name: string = ''; - owner: string = ''; - iban: string = ''; - bic: string = ''; -} - -export class Me implements T.Me { - firstName: string = ''; - lastName: string = ''; -} - -export class Item { - title: string = ''; - unitPrice: number = 0; - qty: number = 1; - projectId: number = 0; -} - -export class Client { - id: number = 0; - name: string = ''; - taxNumber: string = ''; - vatNumber: string = ''; - street: string = ''; - postcode: string = ''; - country: string = ''; -} - -export class Project { - id: number = 0; - name: string = ''; -} diff --git a/src/server/db.ts b/src/server/db.ts deleted file mode 100644 index f06b2d4..0000000 --- a/src/server/db.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Pool, Connection, createPool } from 'mysql2/promise'; -import { PoolOptions } from 'mysql2/typings/mysql'; - -const { - NODE_ENV, - CLEARDB_DATABASE_URL, - DB_HOST, - DB_USER, - DB_NAME, - DB_NAME_TEST, - DB_PASSWD, -} = process.env; -console.log('NODE_ENV', NODE_ENV); - -const checkTypes = row => { - for (const key of Object.keys(row)) { - if (key === 'durationMinutes') { - row[key] = parseInt(row[key]); - } - } - - return row; -}; - -export default class DB { - private pool: Pool; - private connection?: Connection; - - constructor() { - if (CLEARDB_DATABASE_URL) { - this.pool = createPool(CLEARDB_DATABASE_URL as PoolOptions); - } else { - this.pool = createPool({ - host: DB_HOST, - user: DB_USER, - password: DB_PASSWD, - database: NODE_ENV == 'test' ? DB_NAME_TEST : DB_NAME, - }); - } - } - - async init() { - this.connection = await this.pool.getConnection(); - return true; - } - - async query(sql) { - const [results] = await this.pool.query(sql); - - return (results as []).map(checkTypes); - } - - async queryOne(sql) { - const [results] = await this.pool.query(sql); - return (results as []).length > 0 ? checkTypes(results[0]) : false; - } - - async execute(sql, data) { - const [results] = await this.pool.execute(sql, data); - const { insertId } = results as any; - return insertId ? insertId : false; - } -} diff --git a/src/server/index.test.ts b/src/server/index.test.ts deleted file mode 100644 index f873a11..0000000 --- a/src/server/index.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import * as assert from "assert"; -import * as request from "supertest"; -import app from "./index"; - -describe("Get api/me", function() { - this.timeout(3000); - - it("should respond with 403 if not logged", function(done) { - request(app) - .get("/api/me") - .set("Accept", "application/json") - .expect("Content-Type", /json/) - .expect(403) - .end(function(err) { - console.log("end", err); - done(); - }); - }); -}); - -describe("Sign up", function() { - it("should create a new user and return a token", function(done) { - request(app) - .post("/api/sign/up") - .send({ username: "test", password: "test123", email: "test@te.st" }) - .set("Accept", "application/json") - .expect(200) - .end((err, res) => { - const { user, token } = res.body; - - assert.equal(user.id, 1); - assert.equal(user.name, "test"); - assert.equal(user.email, "test@te.st"); - assert.ok(token); - - done(); - }); - }); -}); - -after(() => { - process.exit(0); -}); diff --git a/src/server/index.ts b/src/server/index.ts deleted file mode 100644 index 10bbb9b..0000000 --- a/src/server/index.ts +++ /dev/null @@ -1,182 +0,0 @@ -if (process.env.NODE_ENV !== 'production') { - require('dotenv').config(); -} - -import * as express from 'express'; -import helmet from 'helmet'; -import * as cookieParser from 'cookie-parser'; -import * as logger from 'morgan'; -import * as fallback from 'express-history-api-fallback'; -import * as http from 'http'; -import * as fs from 'fs'; -import * as path from 'path'; -import { createServer as createViteServer } from 'vite'; - -import bankAccounts from './routes/bank-accounts'; -import addresses from './routes/addresses'; -import clients from './routes/clients'; -import invoices from './routes/invoices'; -import currencies from './routes/currencies'; - -const projectsRouter = require('./routes/projects'); -const signRouter = require('./routes/sign'); -const meRouter = require('./routes/me'); - -const createServer = async () => { - const app = express(); - - if (process.env.NODE_ENV !== 'production') { - const webpack = require('webpack'); - const config = require('../../webpack.dev'); - const compiler = webpack(config); - app.use( - require('webpack-dev-middleware')(compiler, { - writeToDisk: true, - // noInfo: true, - publicPath: config.output.publicPath, - }) - ); - - // Create Vite server in middleware mode and configure the app type as - // 'custom', disabling Vite's own HTML serving logic so parent server - // can take control - // const vite = await createViteServer({ - // server: { middlewareMode: true }, - // appType: 'custom', - // }); - - // // use vite's connect instance as middleware - // // if you use your own express router (express.Router()), you should use router.use - // app.use(vite.middlewares); - // app.use('*', async (req, res, next) => { - // const url = req.originalUrl; - - // try { - // // 1. Read index.html - // let template = fs.readFileSync( - // path.resolve(__dirname, '../../public/index.html'), - // 'utf-8' - // ); - - // // 2. Apply Vite HTML transforms. This injects the Vite HMR client, and - // // also applies HTML transforms from Vite plugins, e.g. global preambles - // // from @vitejs/plugin-react - // template = await vite.transformIndexHtml(url, template); - - // // 3. Load the server entry. vite.ssrLoadModule automatically transforms - // // your ESM source code to be usable in Node.js! There is no bundling - // // required, and provides efficient invalidation similar to HMR. - // const { render } = await vite.ssrLoadModule('/src/client/index.ts'); - - // // 4. render the app HTML. This assumes entry-server.js's exported `render` - // // function calls appropriate framework SSR APIs, - // // e.g. ReactDOMServer.renderToString() - // const appHtml = await render(url); - - // // 5. Inject the app-rendered HTML into the template. - // const html = template.replace(``, appHtml); - - // // 6. Send the rendered HTML back. - // res.status(200).set({ 'Content-Type': 'text/html' }).end(html); - // } catch (e: any) { - // // If an error is caught, let Vite fix the stack trace so it maps back to - // // your actual source code. - // vite.ssrFixStacktrace(e); - // next(e); - // } - // }); - } - - app.use(logger('dev')); - app.use(express.json()); - app.use(express.urlencoded({ extended: false })); - app.use(cookieParser()); - app.use(helmet()); - - app.use('/dist', express.static('dist')); - app.use('/api/projects', projectsRouter); - app.use('/api/sign', signRouter); - app.use('/api/me', meRouter); - app.use('/api/invoices', invoices); - app.use('/api/bank-accounts', bankAccounts); - app.use('/api/addresses', addresses); - app.use('/api/clients', clients); - app.use('/api/currencies', currencies); - - app.use(express.static('public')); - app.use(fallback('index.html', { root: 'public' })); - - // app.get('/', (req, res) => { - // res.sendFile('index.html'); - // }); - - // error handler - interface Error { - status: number; - message: string; - } - - app.use((err: Error, req: express.Request, res: express.Response) => { - // set locals, only providing error in development - res.locals.message = err.message; - res.locals.error = err; - - // render the error page - res.status(err.status || 500); - res.json({ error: err }); - }); - - var port = normalizePort(process.env.PORT || '3000'); - app.set('port', port); - - const server = http.createServer(app); - - server.listen(port); - server.on('error', onError); - server.on('listening', onListening); - - function normalizePort(val: string) { - var port = parseInt(val, 10); - - if (isNaN(port)) { - // named pipe - return val; - } - - if (port >= 0) { - // port number - return port; - } - - return false; - } - - function onError(error: { syscall: string; code: string }) { - if (error.syscall !== 'listen') { - throw error; - } - - var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; - - // handle specific listen errors with friendly messages - switch (error.code) { - case 'EACCES': - console.error(bind + ' requires elevated privileges'); - process.exit(1); - break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); - process.exit(1); - break; - default: - throw error; - } - } - - function onListening() { - const addr = server.address() as { port: number }; - console.info('Listening on port ' + addr.port); - } -}; - -export default createServer(); diff --git a/src/server/invoice-template.html b/src/server/invoice-template.html deleted file mode 100644 index 512cd47..0000000 --- a/src/server/invoice-template.html +++ /dev/null @@ -1 +0,0 @@ -

Invoice Farm Radio International 03/2018

Loïc Nogues

Wibsyerstr. 22A

10439 Berlin, Germany

Farm Radio International

1404 Scott Street

Ottawa, Canada

Invoice number

003

Date

13/04/2018

Due date

13/05/2018

Tax Number

31/457/01861

Project

Description

Days

Amount (CAD)

Zammad Audio player in view all

2

$600.00

Uliza.fm button to send a ticket to zammad

1

$300.00

Zammad audio recorder

1

$300.00

Zammad fuzzy search for linked tickets

1

$300.00

Zammad audio player in zoom ticket view

2

$600.00

Server configuration

1

$300.00

Total days

$8.00

Sub total

$2,400.00

Total with tax

$2,400.00

Total paid

$0.00

Amount due (CAD)

$2,400.00

                                   

Loïc Nogues

Wisbyerstr. 22A

10439 Berlin

Mail: nogues.loic@gmail.com

Tel: +49 163 6884263

Web: http://loicnogu.es

Sparkasse Berlin

IBAN: DE46 1005 0000 1061 3342 32
BIC:
BELADEBEXXX

\ No newline at end of file diff --git a/src/server/routes/addresses/create.ts b/src/server/routes/addresses/create.ts deleted file mode 100644 index 7477cf8..0000000 --- a/src/server/routes/addresses/create.ts +++ /dev/null @@ -1,59 +0,0 @@ -const DB = require('./../../db').default; - -const db = new DB(); - -const create = async (req, res) => { - const userId = req.userId; - - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - if (!req.body.street) { - return res.status(403).json({ success: false, message: 'Missing street' }); - } - - if (!req.body.postcode) { - return res - .status(403) - .json({ success: false, message: 'Missing postcode' }); - } - - if (!req.body.city) { - return res.status(403).json({ success: false, message: 'Missing city' }); - } - - if (!req.body.country) { - return res.status(403).json({ success: false, message: 'Missing country' }); - } - - const { name, street, postcode, city, country, extra } = req.body; - let addressId; - - try { - addressId = await db.execute(` - insert into addresses (name, street, extra, city, postcode, country, user_id) - values ('${name}', '${street}', '${extra}', '${city}', '${postcode}', '${country}', ${userId}) - `); - } catch (error) { - return res.status(500).json({ - success: false, - message: 'Error on insert', - error - }); - } - - const address = await db.queryOne(` - select name, street, extra, city, postcode, country - from addresses - where id = ${addressId} and user_id = ${userId} - `); - - if (address) { - return res.json({ success: true, address }); - } - - return res.status(500).json({ success: false, message: 'Address not found' }); -}; - -export default create; diff --git a/src/server/routes/addresses/index.ts b/src/server/routes/addresses/index.ts deleted file mode 100644 index 1885a6d..0000000 --- a/src/server/routes/addresses/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Router } from 'express'; - -import verifyToken from './../../verify-token'; -import create from './create'; -import list from './list'; -import remove from './remove'; -import update from './update'; - -const router = Router(); - -router.post('/', verifyToken, create); -router.get('/', verifyToken, list); -router.delete('/:id', verifyToken, remove); -router.put('/:id', verifyToken, update); - -export default router; diff --git a/src/server/routes/addresses/list.ts b/src/server/routes/addresses/list.ts deleted file mode 100644 index 9eff810..0000000 --- a/src/server/routes/addresses/list.ts +++ /dev/null @@ -1,16 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - - const addresses = await db.query(` - select id, name, street, city, postcode, country - from addresses - where user_id = ${userId} - `); - - res.json({ success: true, addresses }); -}; - diff --git a/src/server/routes/addresses/remove.ts b/src/server/routes/addresses/remove.ts deleted file mode 100644 index b879561..0000000 --- a/src/server/routes/addresses/remove.ts +++ /dev/null @@ -1,26 +0,0 @@ -import DB from "./../../db"; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - - try { - await db.execute( - ` - delete from addresses - where id = ? and user_id = ? - `, - [id, userId] - ); - } catch (error) { - return res.status(500).json({ - success: false, - message: "Error on delete", - error - }); - } - - return res.json({ success: true }); -}; diff --git a/src/server/routes/addresses/update.ts b/src/server/routes/addresses/update.ts deleted file mode 100644 index 8a10b12..0000000 --- a/src/server/routes/addresses/update.ts +++ /dev/null @@ -1,23 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - - const { name, street, extra, city, postcode, country } = req.body; - - try { - await db.execute( - `update addresses - set name = ?, street = ?, extra = ?, city = ?, postcode = ?, country = ? - where id = ? and user_id = ?`, - [name, street, extra, city, postcode, country, id, userId] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - return res.json({ success: true }); -}; diff --git a/src/server/routes/bank-accounts/create.js b/src/server/routes/bank-accounts/create.js deleted file mode 100644 index a73456e..0000000 --- a/src/server/routes/bank-accounts/create.js +++ /dev/null @@ -1,52 +0,0 @@ -const DB = require('./../../db').default; - -const db = new DB(); - -const create = async (req, res) => { - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - if (!req.body.owner) { - return res.status(403).json({ success: false, message: 'Missing owner' }); - } - - if (!req.body.iban) { - return res.status(403).json({ success: false, message: 'Missing IBAN' }); - } - - if (!req.body.bic) { - return res.status(403).json({ success: false, message: 'Missing BIC' }); - } - - const userId = req.userId; - const { name, owner, iban, bic } = req.body; - let bankAccountID; - - try { - bankAccountID = await db.execute(` - insert into bank_accounts (name, owner, iban, bic, user_id) - values ('${name}', '${owner}', '${iban}', '${bic}', ${userId}) - `); - } catch (error) { - return res.status(500).json({ - success: false, - message: 'Error on insert', - error - }); - } - - const bankAccount = await db.query(` - select name, owner, iban, bic - from bank_accounts - where id = ${bankAccountID} and user_id = ${userId} - `); - - if (bankAccount) { - return res.json({ success: true, bankAccount }); - } - - return res.status(500).json({ success: false, message: 'Bank account not found' }); -}; - -module.exports = create; \ No newline at end of file diff --git a/src/server/routes/bank-accounts/delete.js b/src/server/routes/bank-accounts/delete.js deleted file mode 100644 index 8bd98d9..0000000 --- a/src/server/routes/bank-accounts/delete.js +++ /dev/null @@ -1,25 +0,0 @@ -const DB = require("./../../db").default; - -const db = new DB(); - -const deleteAccount = async (req, res) => { - const iban = req.params.iban; - const userId = req.userId; - - try { - await db.execute(` - delete from bank_accounts - where iban = '${iban}' and user_id = ${userId} - `); - } catch (error) { - return res.status(500).json({ - success: false, - message: "Error on delete", - error - }); - } - - return res.json({ success: true }); -}; - -module.exports = deleteAccount; diff --git a/src/server/routes/bank-accounts/get-bank-accounts.js b/src/server/routes/bank-accounts/get-bank-accounts.js deleted file mode 100644 index 13cba12..0000000 --- a/src/server/routes/bank-accounts/get-bank-accounts.js +++ /dev/null @@ -1,17 +0,0 @@ -const DB = require('./../../db').default; - -const db = new DB(); - -const getBankAccounts = async (req, res) => { - const userId = req.userId; - - const bankAccounts = await db.query(` - select id, name, owner, iban, bic - from bank_accounts - where user_id = ${userId} - `); - - res.json({ success: true, bankAccounts }); -}; - -module.exports = getBankAccounts; diff --git a/src/server/routes/bank-accounts/index.ts b/src/server/routes/bank-accounts/index.ts deleted file mode 100644 index 0580c38..0000000 --- a/src/server/routes/bank-accounts/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Router } from 'express'; - -import verifyToken from './../../verify-token'; -import * as create from './create'; -import * as getBankAccounts from './get-bank-accounts'; -import * as deleteBankAccount from './delete'; - -const router = Router(); - -router.post('/', verifyToken, create); -router.get('/', verifyToken, getBankAccounts); -router.delete('/:iban', verifyToken, deleteBankAccount); - -export default router; \ No newline at end of file diff --git a/src/server/routes/clients/create.ts b/src/server/routes/clients/create.ts deleted file mode 100644 index 71988c3..0000000 --- a/src/server/routes/clients/create.ts +++ /dev/null @@ -1,76 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - if (!req.body.street) { - return res.status(403).json({ success: false, message: 'Missing street' }); - } - - if (!req.body.postcode) { - return res - .status(403) - .json({ success: false, message: 'Missing postcode' }); - } - - if (!req.body.city) { - return res.status(403).json({ success: false, message: 'Missing city' }); - } - - if (!req.body.country) { - return res.status(403).json({ success: false, message: 'Missing country' }); - } - - const { - name, - street, - extra, - postcode, - city, - country, - taxNumber, - vatNumber - } = req.body; - let clientId, addressId; - - try { - clientId = await db.execute( - `insert into clients (name, user_id, tax_number, vat_number) values (?, ?, ?, ?)`, - [name, userId, taxNumber, vatNumber] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - try { - addressId = await db.execute( - ` - insert into addresses (name, street, extra, city, postcode, country, client_id) - values (?, ?, ?, ?, ?, ?, ?) - `, - [name, street, extra, city, postcode, country, clientId] - ); - } catch (error) { - return res.status(500).json({ - success: false, - message: 'Error on insert', - error - }); - } - - const client = await db.queryOne(` - select name - from clients - where id = ${clientId} - `); - - if (client) { - return res.json({ success: true, client }); - } -}; diff --git a/src/server/routes/clients/index.ts b/src/server/routes/clients/index.ts deleted file mode 100644 index 1998e13..0000000 --- a/src/server/routes/clients/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Router } from "express"; - -import verifyToken from "./../../verify-token"; -import list from "./list"; -import create from "./create"; -import remove from "./remove"; -import update from "./update"; - -const router = Router(); - -router.get("/", verifyToken, list); -router.post("/", verifyToken, create); -router.delete("/:id", verifyToken, remove); -router.put("/:id", verifyToken, update); - -export default router; diff --git a/src/server/routes/clients/list.ts b/src/server/routes/clients/list.ts deleted file mode 100644 index a601e07..0000000 --- a/src/server/routes/clients/list.ts +++ /dev/null @@ -1,25 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - - const clients = await db.query(` - select - c.id, - c.name, - c.tax_number as "taxNumber", - c.vat_number as "vatNumber", - a.extra, - a.street, - a.city, - a.postcode, - a.country - from clients c - left join addresses a on c.id = a.client_id - where c.user_id = ${userId} - `); - - res.json({ success: true, clients }); -}; diff --git a/src/server/routes/clients/remove.ts b/src/server/routes/clients/remove.ts deleted file mode 100644 index 2051ba0..0000000 --- a/src/server/routes/clients/remove.ts +++ /dev/null @@ -1,45 +0,0 @@ -import DB from "./../../db"; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - - try { - await db.execute( - ` - delete from clients - where id = ? and user_id = ? - `, - [id, userId] - ); - } catch (error) { - return res.status(500).json({ - success: false, - message: "Error on delete", - error - }); - } - - // Remove stray addresses - try { - await db.execute( - ` - delete addresses - FROM addresses - left outer join clients c on c.id = addresses.client_id - where addresses.user_id is null - and c.id is null - `, - [] - ); - } catch (error) { - return res.status(500).json({ - success: false, - message: "Error on delete", - error - }); - } - return res.json({ success: true }); -}; diff --git a/src/server/routes/clients/update.ts b/src/server/routes/clients/update.ts deleted file mode 100644 index 34e13a2..0000000 --- a/src/server/routes/clients/update.ts +++ /dev/null @@ -1,43 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - const { - name, - street, - extra, - city, - postcode, - country, - taxNumber, - vatNumber - } = req.body; - - try { - await db.execute( - `update clients - set name = ?, tax_number = ?, vat_number = ? - where id = ? and user_id = ?`, - [name, taxNumber, vatNumber, id, userId] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - // Here we're supposing the client only has one address - try { - await db.execute( - `update addresses - set street = ?, extra = ?, city = ?, postcode = ?, country = ? - where client_id = ?`, - [street, extra, city, postcode, country, id] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - return res.json({ success: true }); -}; diff --git a/src/server/routes/currencies.ts b/src/server/routes/currencies.ts deleted file mode 100644 index 0195a68..0000000 --- a/src/server/routes/currencies.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Router } from "express"; -import verifyToken from "./../verify-token"; -import DB from "./../db"; - -const router = Router(); -const db = new DB(); - -router.get("/", verifyToken, async (req, res) => { - const currencies = await db.query(` - select code, name, sign - from currencies - `); - - if (currencies) { - res.json({ success: true, currencies }); - } -}); - -export default router; diff --git a/src/server/routes/invoices/create-with-items.ts b/src/server/routes/invoices/create-with-items.ts deleted file mode 100644 index f3c09ad..0000000 --- a/src/server/routes/invoices/create-with-items.ts +++ /dev/null @@ -1,99 +0,0 @@ -import DB from './../../db'; -import { Item, Invoice } from './../../../models'; - -const db = new DB(); - -export default async (req, res) => { - if (!req.body.invoice) { - return res.status(403).json({ success: false, message: 'Missing invoice' }); - } - - if (!req.body.items || req.body.items.length === 0) { - return res.status(403).json({ success: false, message: 'Missing items' }); - } - - const userId = req.userId; - const invoice: Invoice = req.body.invoice; - const items: Item[] = req.body.items; - - let invoiceId; - - const isNumberExisting = await db.queryOne(` - select id - from invoices - where user_id = ${userId} and number = ${invoice.number} - `); - - if (isNumberExisting) { - return res - .status(500) - .json({ success: false, message: 'Invoice number already existing' }); - } - - try { - invoiceId = await db.execute( - ` - insert into invoices ( - user_id, - date, - due_date, - name, - memo, - number, - tax, - discount, - user_address_id, - bank_account_id, - currency_code, - client_id - ) - values (?,?,?,?,?,?,?,?,?,?,?,?) - `, - [ - userId, - invoice.date, - invoice.dueDate, - invoice.name, - invoice.memo, - invoice.number, - invoice.tax, - invoice.discount, - invoice.userAddressId, - invoice.bankAccountId, - invoice.currencyCode, - invoice.clientId - ] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - for (let item of items) { - try { - await db.execute( - ` - insert into items ( - title, - unit_price, - qty, - project_id, - user_id, - invoice_id) - values (?,?,?,?,?,?) - `, - [ - item.title, - item.unitPrice, - item.qty, - item.projectId, - userId, - invoiceId - ] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - } - - res.json({ success: true, invoiceId }); -}; diff --git a/src/server/routes/invoices/create.ts b/src/server/routes/invoices/create.ts deleted file mode 100644 index 3778872..0000000 --- a/src/server/routes/invoices/create.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { DateTime } from 'luxon'; -import DB from './../../db'; - -const dateFormat = 'yyyy-MM-dd'; -const db = new DB(); - -export default async (req, res) => { - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - if (!req.body.hourlyRate) { - return res - .status(403) - .json({ success: false, message: 'Missing hourly rate' }); - } - - if (!req.body.month) { - return res.status(403).json({ success: false, message: 'Missing month' }); - } - - if (!req.body.projectSlug) { - return res.status(403).json({ success: false, message: 'Missing project' }); - } - - if (!req.body.iban) { - return res - .status(403) - .json({ success: false, message: 'Missing bank account' }); - } - - if (!req.body.userAddressId) { - return res - .status(403) - .json({ success: false, message: "Missing user's address" }); - } - - if (!req.body.currency) { - return res - .status(403) - .json({ success: false, message: 'Missing currency' }); - } - - const userId = req.userId; - const { - name, - hourlyRate, - projectSlug, - iban, - userAddressId, - currency - } = req.body; - - const [year, month] = req.body.month.split('-'); - - try { - const project = await db.queryOne(` - select id - from projects - where user_id = ${userId} and slug = '${projectSlug}' - `); - - if (!project) { - return res - .status(500) - .json({ success: false, message: 'Project does not exists' }); - } - - const bankAccount = await db.queryOne(` - select id - from bank_accounts - where user_id = ${userId} and iban = '${iban}' - `); - - const dueDate = DateTime.local() - .plus({ months: 1 }) - .toFormat(dateFormat); - - let number = 1; - - const lastInvoice = await db.queryOne(` - select number - from invoices - where user_id = ${userId} - order by id desc - limit 1 - `); - - if (lastInvoice && lastInvoice.number) { - number = parseInt(lastInvoice.number) + 1; - } - - const invoiceId = await db.execute( - ` - insert into invoices ( - user_id, - date, - due_date, - name, - number, - project_id, - rate, - bank_account_id, - user_address_id, - currency_code - ) - values (?, curdate(), ?, ? , ?, ?, ?, ?, ?, ?) - `, - [ - userId, - dueDate, - name, - number, - project.id, - hourlyRate, - bankAccount.id, - userAddressId, - currency - ] - ); - - const activityInvoices = await db.execute( - ` - update activities - set invoice_id = ? - where month(start_time) = ? - and year(start_time) = ? - and project_id = ? - and user_id = ? - `, - [invoiceId, month, year, project.id, userId] - ); - - res.json({ success: true, invoiceId, activityInvoices }); - } catch (error) { - return res.status(500).json({ - success: false, - message: 'Error on insert', - error - }); - } -}; diff --git a/src/server/routes/invoices/get.ts b/src/server/routes/invoices/get.ts deleted file mode 100644 index b5eb9b3..0000000 --- a/src/server/routes/invoices/get.ts +++ /dev/null @@ -1,80 +0,0 @@ -import DB from './../../db'; -import { Invoice, BankAccount, Item, Client } from './../../../models'; - -const db = new DB(); - -export default async (req, res) => { - const id = req.params.id; - const userId = req.userId; - - const invoice: Invoice = await db.queryOne(` - select - i.id, - i.number, - i.name, - i.memo, - i.date, - i.due_date as 'dueDate', - i.rate, - i.rate_daily as dailyRate, - i.tax, - i.discount, - i.user_address_id as 'userAddressId', - i.bank_account_id as 'bankAccountId', - i.client_id as 'clientId', - c.code as 'currencyCode', - c.sign as 'currencySign', - c.name as 'currencyName', - c.leading as 'currencyLeading' - from invoices i - join currencies c on i.currency_code = c.code - where i.id = ${id} and i.user_id = ${userId} - `); - - const bankAccount: BankAccount = await db.queryOne(` - select name, owner, iban, bic - from bank_accounts - where id = ${invoice.bankAccountId} - `); - - const client: Client = await db.queryOne(` - select - c.name, - c.tax_number as 'taxNumber', - c.vat_number as 'vatNumber', - a.extra, - a.street, - a.city, - a.postcode, - a.country - from clients c - join addresses a on a.client_id = c.id - where c.id = ${invoice.clientId} - `); - - const items: Array = await db.query(` - select - title, - qty, - unit_price as 'unitPrice', - project_id as 'projectId' - from items - where user_id = ${req.userId} - and invoice_id = ${invoice.id} - `); - - const address = await db.queryOne(` - select id, name, street, city, postcode, country - from addresses - where id = ${invoice.userAddressId} - `); - - res.json({ - success: true, - invoice, - bankAccount, - client, - address, - items - }); -}; diff --git a/src/server/routes/invoices/index.ts b/src/server/routes/invoices/index.ts deleted file mode 100644 index 3702468..0000000 --- a/src/server/routes/invoices/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Router } from 'express'; - -import verifyToken from './../../verify-token'; -import get from './get'; -import list from './list'; -import createWithItems from './create-with-items'; -import create from './create'; -import update from './update'; -import pdf from './pdf'; -import remove from './remove'; - -const router = Router(); - -router.get('/:id', verifyToken, get); -router.get('/', verifyToken, list); -router.post('/with-items', verifyToken, createWithItems); -router.post('/', verifyToken, create); -router.put('/:id', verifyToken, update); -router.get('/:id/pdf', verifyToken, pdf); -router.delete('/:id', verifyToken, remove); - -export default router; diff --git a/src/server/routes/invoices/list.ts b/src/server/routes/invoices/list.ts deleted file mode 100644 index 55b2e9a..0000000 --- a/src/server/routes/invoices/list.ts +++ /dev/null @@ -1,32 +0,0 @@ -import DB from './../../db'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - - const invoices = await db.query(` - select - i.id, - i.number, - i.name, - i.date, - i.rate, - i.rate_daily as dailyRate, - i.discount, - i.tax, - sum(it.qty * it.unit_price) as 'subTotal', - c.code as 'currencyCode', - c.sign as 'currencySign', - c.name as 'currencyName', - c.leading as 'currencyLeading' - from invoices i - join currencies c on i.currency_code = c.code - join items it on i.id = it.invoice_id - where i.user_id = ${userId} - group by it.invoice_id - order by i.date desc - `); - - res.json({ success: true, invoices }); -}; diff --git a/src/server/routes/invoices/pdf.ts b/src/server/routes/invoices/pdf.ts deleted file mode 100644 index df057b3..0000000 --- a/src/server/routes/invoices/pdf.ts +++ /dev/null @@ -1,220 +0,0 @@ -import * as puppeteer from 'puppeteer-core'; -// import * as Vue from 'vue/dist/vue.cjs.js'; -import DB from './../../db'; -import { Invoice, BankAccount, Item, Client } from './../../../models'; -import InvoiceInfo from '../../../lib/components/invoice-info'; -import ItemsTable from '../../../lib/components/items-table'; -import { iban } from '../../../lib/filters'; -import { createApp } from 'vue'; -const { renderToString } = require('@vue/server-renderer'); - -const db = new DB(); - -export default async (req, res) => { - const id = req.params.id; - const userId = req.userId; - - const me = await db.queryOne(` - select - email, - name, - first_name as 'firstName', - last_name as 'lastName', - tax_number as 'taxNumber', - vat_number as 'vatNumber', - tel, - website - from users - where id = ${userId} - `); - - const invoice: Invoice = await db.queryOne(` - select - i.id, - i.number, - i.name, - i.memo, - i.date, - i.due_date as 'dueDate', - i.rate, - i.rate_daily as 'dailyRate', - i.tax, - i.discount, - i.user_address_id as 'userAddressId', - i.bank_account_id as 'bankAccountId', - i.client_id as 'clientId', - c.code as 'currencyCode', - c.sign as 'currencySign', - c.name as 'currencyName', - c.leading as 'currencyLeading' - from invoices i - join currencies c on i.currency_code = c.code - where i.id = ${id} and i.user_id = ${userId} - `); - - const bankAccount: BankAccount = await db.queryOne(` - select name, owner, iban, bic - from bank_accounts - where id = ${invoice.bankAccountId} - `); - - const client: Client = await db.queryOne(` - select - c.name, - c.tax_number as 'taxNumber', - c.vat_number as 'vatNumber', - a.extra, - a.street, - a.city, - a.postcode, - a.country - from clients c - join addresses a on a.client_id = c.id - where c.id = ${invoice.clientId} - `); - - const items: Array = await db.query(` - select title, qty, unit_price as 'unitPrice' - from items - where user_id = ${req.userId} - and invoice_id = ${invoice.id} - `); - - const address = await db.queryOne(` - select id, name, street, city, postcode, country - from addresses - where id = ${invoice.userAddressId} - `); - - const app = createApp({ - data() { - return { - invoice, - bankAccount, - items, - me, - address, - client, - }; - }, - components: { InvoiceInfo, ItemsTable }, - methods: { iban }, - template: ` -
-

{{invoice.name}}

-
-

{{me.firstName}} {{me.lastName}}

-

{{ me.extra }}

-

{{address.street}}

-

{{address.postcode}} {{address.city}}, {{address.country}}

-

- Steuernummer: - {{ me.taxNumber }} -

-

- VAT number: - {{ me.vatNumber }} -

-
-
-

{{client.name}}

-

{{ client.extra }}

-

{{client.street}}

-

{{client.postcode}} {{client.city}}, {{client.country}}

-

- Steuernummer: - {{ client.taxNumber }} -

-

- VAT number: - {{ client.vatNumber }} -

-
- - -

{{invoice.memo}}

- - - -
- `, - }); - - const html = await renderToString(app); - const browser = await puppeteer.launch({ - executablePath: process.env.CHROME_BIN, - args: ['--no-sandbox', '--disable-setuid-sandbox'], - }); - const page = await browser.newPage(); - - await page.setContent(html); - const pdf = await page.pdf({ format: 'A4' }); - - res.set('Content-Type', 'application/pdf').send(pdf); -}; diff --git a/src/server/routes/invoices/remove.ts b/src/server/routes/invoices/remove.ts deleted file mode 100644 index 26c4dbe..0000000 --- a/src/server/routes/invoices/remove.ts +++ /dev/null @@ -1,26 +0,0 @@ -import DB from "./../../db"; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - - try { - await db.execute( - ` - delete from invoices - where id = ? and user_id = ? - `, - [id, userId] - ); - } catch (error) { - return res.status(500).json({ - success: false, - message: "Error on delete", - error - }); - } - - return res.json({ success: true }); -}; diff --git a/src/server/routes/invoices/update.ts b/src/server/routes/invoices/update.ts deleted file mode 100644 index 5bff2d3..0000000 --- a/src/server/routes/invoices/update.ts +++ /dev/null @@ -1,86 +0,0 @@ -import DB from './../../db'; -import { Invoice, Item } from './../../../models'; - -const db = new DB(); - -export default async (req, res) => { - const userId = req.userId; - const id = req.params.id; - - if (!req.body.invoice) { - return res.status(403).json({ success: false, message: 'Missing invoice' }); - } - - if (!req.body.items) { - return res.status(403).json({ success: false, message: 'Missing items' }); - } - - const invoice: Invoice = req.body.invoice; - const items: Item[] = req.body.items; - - try { - await db.execute( - ` - update invoices - set - date = ?, - due_date = ?, - name = ?, - memo = ?, - number = ?, - tax = ?, - discount = ?, - user_address_id = ?, - bank_account_id = ?, - client_id = ?, - currency_code = ? - where id = ? and user_id = ? - `, - [ - invoice.date, - invoice.dueDate, - invoice.name, - invoice.memo, - invoice.number, - invoice.tax, - invoice.discount, - invoice.userAddressId, - invoice.bankAccountId, - invoice.clientId, - invoice.currencyCode, - id, - userId - ] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - try { - await db.execute(`delete from items where invoice_id = ?`, [id]); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - for (let item of items) { - try { - await db.execute( - ` - insert into items ( - title, - unit_price, - qty, - project_id, - user_id, - invoice_id) - values (?,?,?,?,?,?) - `, - [item.title, item.unitPrice, item.qty, item.projectId, userId, id] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - } - - return res.json({ success: true }); -}; diff --git a/src/server/routes/me.js b/src/server/routes/me.js deleted file mode 100644 index 7a7899f..0000000 --- a/src/server/routes/me.js +++ /dev/null @@ -1,151 +0,0 @@ -const express = require("express"); -const bcrypt = require("bcrypt"); - -const DB = require("./../db").default; -const verifyToken = require("./../verify-token").default; -const { camelToSnake } = require("./../../utils"); - -const router = express.Router(); -const db = new DB(); -const saltRounds = parseInt(process.env.BCRYPT_SALT); - -const buildQuery = body => { - let query = ""; - - Object.keys(body).forEach(key => { - query += ` ${camelToSnake(key)} = '${body[key]}',`; - }); - - return query.slice(0, -1); -}; - -router.get("/", verifyToken, async (req, res) => { - const userId = req.userId; - - try { - const me = await db.queryOne(` - select - email, - name, - first_name as 'firstName', - last_name as 'lastName', - tax_number as 'taxNumber', - vat_number as 'vatNumber', - tel, - website - from users - where id = ${userId} - `); - - res.json({ success: true, me }); - } catch (error) { - res.status(500).json({ success: false, error }); - } -}); - -router.put("/", verifyToken, async (req, res) => { - const userId = req.userId; - const fields = [ - "email", - "firstName", - "lastName", - "tel", - "website", - "taxNumber", - "vatNumber" - ]; - - if (Object.keys(req.body).length === 0) { - return res.status(500).json({ success: false, message: "Empty body" }); - } - - let body = {}; - - fields.forEach(key => { - if (req.body.hasOwnProperty(key)) { - body[key] = req.body[key]; - } - }); - - try { - await db.execute(` - update users - set ${buildQuery(body)} - where id = ${userId} - `); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - const me = await db.queryOne(` - select - email, - name, - first_name as 'firstName', - last_name as 'lastName', - tel, - website - from users - where id = ${userId} - `); - - res.json({ success: true, me }); -}); - -router.put("/passwd", verifyToken, async (req, res) => { - const userId = req.userId; - - if (!req.body.currentPassword) { - return res.status(500).json({ - success: false, - message: "Missing current password" - }); - } - - if (!req.body.password) { - return res.status(500).json({ - success: false, - message: "Missing new password" - }); - } - - const { currentPassword, password } = req.body; - - const user = await db.queryOne(` - select password - from users - where id = ${userId} - `); - - if (!user) { - return res.status(500).json({ - success: false, - message: "Could not find user" - }); - } - - const match = await bcrypt.compare(currentPassword, user.password); - - if (!match) { - return res.status(500).json({ - success: false, - message: "Current password is wrong" - }); - } - - const hash = await bcrypt.hash(password, saltRounds); - - try { - await db.execute(` - update users - set password = '${hash}' - where id = ${userId} - `); - } catch (error) { - res.status(500).json({ success: false, error }); - } - - res.json({ success: true }); -}); - -module.exports = router; diff --git a/src/server/routes/projects.js b/src/server/routes/projects.js deleted file mode 100644 index 9a3f2da..0000000 --- a/src/server/routes/projects.js +++ /dev/null @@ -1,197 +0,0 @@ -// TODO: Refactor to typescript and split the file -const express = require('express'); -const slugify = require('slugify'); - -const DB = require('./../db').default; -const verifyToken = require('./../verify-token').default; - -const router = express.Router(); -const db = new DB(); - -const filterByMonth = monthDate => { - if (!monthDate) { - return ''; - } - - let [year, month] = monthDate.split('-'); - - return ` - and month(a.start_time) = ${month} - and year(a.start_time) = ${year} - `; -}; - -router.get('/:slug', verifyToken, async (req, res) => { - const slug = req.params.slug; - const userId = req.userId; - const month = req.query.month || ''; - - const project = await db.queryOne(` - select id, name, slug - from projects - where slug = '${slug}' and user_id = ${userId} - `); - - const activities = await db.query(` - select - a.id, - a.name, - a.start_time as 'startTime', - a.end_time as 'endTime', - a.duration_minutes as 'durationMinutes' - from activities a - where a.project_id = ${project.id} - ${filterByMonth(month)} - order by a.start_time asc - `); - - res.json({ success: true, project, activities }); -}); - -router.get('/', verifyToken, async (req, res) => { - const projects = await db.query(` - select id, name, slug - from projects - where user_id = ${req.userId} - `); - - res.json(projects); -}); - -router.put('/:slug', verifyToken, async (req, res) => { - const userId = req.userId; - const slug = req.params.slug; - - if (!req.body.clientId) { - return res - .status(403) - .json({ success: false, message: 'Missing client id' }); - } - - const clientId = req.body.clientId; - - try { - await db.execute( - 'update projects set client_id = ? where slug = ? and user_id = ?', - [clientId, slug, userId] - ); - } catch (error) { - return res.status(500).json({ success: false, error }); - } - - return res.json({ success: true }); -}); - -router.post('/', verifyToken, async (req, res) => { - const userId = req.userId; - - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - const name = req.body.name; - const slug = slugify(req.body.name).toLowerCase(); - - const project = await db.queryOne(` - select id - from projects - where user_id = ${userId} and slug = '${slug}' - `); - - if (project) { - return res.status(500).json({ - success: false, - message: 'Project already exists' - }); - } - - const id = await db.execute(` - insert into projects (name, slug, user_id) - values ('${name}', '${slug}', ${userId}) - `); - - if (!id) { - return res.status(500).json({ success: false, message: 'Cannot insert' }); - } - - const newProject = await db.queryOne(` - select id, name, slug from projects where id = ${id} - `); - - if (!newProject) { - return res.status(500).json({ success: false, message: 'Error' }); - } - - res.json({ success: true, project: newProject }); -}); - -router.get('/:slug/clients', verifyToken, async (req, res) => { - const slug = req.params.slug; - const userId = req.userId; - - const clients = await db.query(` - select - c.id, - c.name, - c.tax_number as "taxNumber", - c.vat_number as "vatNumber", - a.street, - a.city, - a.postcode, - a.country - from clients c - join projects p on c.id = p.client_id - left join addresses a on c.id = a.client_id - where c.user_id = ${userId} - and p.slug = '${slug}' - `); - - res.json({ success: true, clients }); -}); - -// TODO: this function is questionable -router.post('/:slug/clients', verifyToken, async (req, res) => { - const slug = req.params.slug; - const userId = req.userId; - let clientId; - - if (!req.body.name) { - return res.status(403).json({ success: false, message: 'Missing name' }); - } - - const name = req.body.name; - - try { - clientId = await db.execute(` - insert into clients (name, user_id) - values ('${name}', ${userId}) - `); - } catch (error) { - return res.json({ success: false, error }); - } - - try { - await db.execute(` - update projects - set client_id = ${clientId} - where slug = '${slug}' - `); - } catch (error) { - return res.json({ success: false, error }); - } - - const client = await db.queryOne(` - select c.id, c.name, a.street, a.city, a.postcode, a.country - from clients c - left join addresses a on c.id = a.client_id - where c.id = ${clientId} - `); - - if (client) { - return res.json({ success: true, client }); - } - - return res.json({ success: false, message: 'Client not found' }); -}); - -module.exports = router; diff --git a/src/server/routes/sign.js b/src/server/routes/sign.js deleted file mode 100644 index 43592f7..0000000 --- a/src/server/routes/sign.js +++ /dev/null @@ -1,101 +0,0 @@ -const express = require('express'); -const bcrypt = require('bcrypt'); -const jwt = require('jsonwebtoken'); - -const DB = require('./../db').default; - -const router = express.Router(); -const db = new DB(); -const saltRounds = parseInt(process.env.BCRYPT_SALT); - -router.post('/up', async (req, res) => { - if (!req.body.username) { - return res.status(403).json({ success: false, message: 'Missing username' }); - } - - if (!req.body.password) { - return res.status(403).json({ success: false, message: 'Missing password' }); - } - - if (!req.body.email) { - return res.status(403).json({ success: false, message: 'Missing email' }); - } - - const email = req.body.email; - const username = req.body.username; - const password = await bcrypt.hash(req.body.password, saltRounds); - - const users = await db.query(` - select id from users where name = '${username}' or email = '${email}' - `); - - if (users.length > 0) { - return res.status(500).json({ success: false, message: 'User already exists' }); - } - - const id = await db.execute(` - insert into users (name, email, password) - values ('${username}', '${email}', '${password}') - `); - - if (!id) { - return res.status(500).json({ success: false, message: 'Cannot insert' }); - } - - const user = await db.queryOne(` - select id, name, email, password from users where id = ${id} - `); - - if (!user) { - return res.status(500).json({ success: false, message: 'Error' }); - } - - const token = jwt.sign({ - data: { id: user.id, username: user.name } - }, process.env.JWT_SECRET, { - expiresIn: '1d', - algorithm: 'HS256' - }); - - res.json({ success: true, user, token }); -}); - -router.post('/in', async (req, res) => { - if (!req.body.username) { - return res.status(403).json({ success: false, message: 'Missing user name' }); - } - - if (!req.body.password) { - return res.status(403).json({ success: false, message: 'Missing password' }); - } - - const sql = ` - select id, name, password - from users - where name='${req.body.username}' - `; - - const users = await db.query(sql); - - if (users.length === 0) { - return res.status(403).json({ success: false, message: 'Wrong credentials' }); - } - - const user = users[0]; - const match = await bcrypt.compare(req.body.password, user.password); - - if (match) { - const token = jwt.sign({ - data: { id: user.id, username: user.name } - }, process.env.JWT_SECRET, { - expiresIn: '1d', - algorithm: 'HS256' - }); - - return res.json({ success: true, token }); - } - - return res.status(403).json({ success: false, message: 'Wrong credentials' }); -}); - -module.exports = router; \ No newline at end of file diff --git a/src/server/verify-token.ts b/src/server/verify-token.ts deleted file mode 100644 index 49ff873..0000000 --- a/src/server/verify-token.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as jwt from "jsonwebtoken"; - -function verifyToken(req, res, next) { - if (!req.headers["authorization"]) { - return res - .status(403) - .send({ auth: false, message: "Missing Authorization headers" }); - } - - const match = req.headers["authorization"].match(/Bearer (.+)/i); - - if (!match) { - return res.status(403).send({ auth: false, message: "Invalid token." }); - } - - const token = match[1]; - - if (!token) { - return res.status(403).send({ auth: false, message: "No token provided." }); - } - - jwt.verify( - token, - process.env.JWT_SECRET, - { algorithm: "HS256" }, - (err, decoded) => { - if (err) { - return res - .status(500) - .send({ auth: false, message: "Failed to authenticate token." }); - } - - req.userId = decoded.data.id; - req.username = decoded.data.username; - - next(); - } - ); -} - -export default verifyToken; diff --git a/src/types.ts b/src/types.ts deleted file mode 100644 index 593136d..0000000 --- a/src/types.ts +++ /dev/null @@ -1,36 +0,0 @@ -export interface Activity { - name: string; - durationMinutes: number; - durationDays: number; - projectName: string; - projectSlug: string; -} - -export interface Invoice { - id: number; - name: string; - tax: number; - discount: number; - rate: number; - bankAccountId: number; - number: number; - userAddressId: number; -} - -export interface BankAccount { - name: string; - owner: string; - iban: string; - bic: string; -} - -export interface Me { - firstName: string; - lastName: string; -} - -export interface Client { - id: number; - name: string; - street: string; -} diff --git a/src/utils.ts b/src/utils.ts deleted file mode 100644 index 0be0137..0000000 --- a/src/utils.ts +++ /dev/null @@ -1,19 +0,0 @@ -export const diff = (original, copy) => { - let diffObj = {}; - - Object.keys(original).forEach(key => { - if (original[key] !== copy[key]) { - diffObj[key] = copy[key]; - } - }); - - return diffObj; -}; - -export const camelToSnake = string => { - return string - .replace(/\.?([A-Z]+)/g, (x, y) => { - return "_" + y.toLowerCase(); - }) - .replace(/^_/, ""); -}; diff --git a/tailwind.config.js b/tailwind.config.js deleted file mode 100644 index 8f222a9..0000000 --- a/tailwind.config.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = { - darkMode: true, - theme: { - extend: {}, - }, - variants: {}, - plugins: [], - content: ['./public/**/*.html', './src/**/*.vue'], -}; diff --git a/test/e2e/api.test.ts b/test/e2e/api.test.ts new file mode 100644 index 0000000..fa5db58 --- /dev/null +++ b/test/e2e/api.test.ts @@ -0,0 +1,568 @@ +// Builds the app, runs it against a throwaway SQLite file, and exercises the +// API over HTTP. +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { setup, url } from '@nuxt/test-utils/e2e'; +import bcrypt from 'bcryptjs'; +import Database from 'better-sqlite3'; +import { afterAll, describe, expect, it } from 'vitest'; + +const tempDir = mkdtempSync(join(tmpdir(), 'zeithub-test-')); +const databasePath = join(tempDir, 'zeithub.db'); + +const macChrome = + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const chromeBin = + process.env.CHROME_BIN || (existsSync(macChrome) ? macChrome : ''); + +await setup({ + rootDir: fileURLToPath(new URL('../..', import.meta.url)), + server: true, + build: true, + env: { + DATABASE_PATH: databasePath, + NUXT_APP_SECRET: 'test-secret-that-is-long-enough-0123456789', + CHROME_BIN: chromeBin, + }, +}); + +afterAll(() => { + rmSync(tempDir, { recursive: true, force: true }); +}); + +interface Response { + status: number; + body: T; + headers: Headers; +} + +// Minimal client that keeps the session cookie, like a browser would. +function client() { + let cookie = ''; + + async function request( + method: string, + path: string, + body?: unknown + ): Promise> { + const res = await fetch(url(path), { + method, + headers: { + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + ...(cookie ? { cookie } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + + const setCookie = res.headers.getSetCookie(); + if (setCookie.length) { + cookie = setCookie.map(value => value.split(';')[0]).join('; '); + } + + const type = res.headers.get('content-type') ?? ''; + const parsed = type.includes('json') + ? await res.json() + : type.includes('pdf') + ? await res.arrayBuffer() + : await res.text(); + + return { status: res.status, body: parsed as T, headers: res.headers }; + } + + return { + get: (path: string) => request('GET', path), + post: (path: string, body?: unknown) => + request('POST', path, body ?? {}), + put: (path: string, body?: unknown) => + request('PUT', path, body ?? {}), + delete: (path: string) => request('DELETE', path), + raw: request, + }; +} + +let userCount = 0; +async function signedUpClient() { + const api = client(); + const name = `user${++userCount}`; + const res = await api.post('/api/auth/signup', { + username: name, + email: `${name}@example.com`, + password: 'correct horse battery', + }); + expect(res.status).toBe(201); + return { api, name }; +} + +const address = { + name: 'Home', + street: 'Wisbyerstr. 22A', + city: 'Berlin', + postcode: '10439', + country: 'Germany', +}; + +const clientBody = { + name: 'Farm Radio International', + vatNumber: 'CA123', + street: '1404 Scott Street', + city: 'Ottawa', + postcode: 'K1Y 4M8', + country: 'Canada', +}; + +const bankAccount = { + name: 'Sparkasse', + owner: 'Jane Doe', + iban: 'DE46 1005 0000 1061 3342 32', + bic: 'BELADEBEXXX', +}; + +// Signs up a user with one of everything and an invoice. +async function userWithInvoice() { + const { api, name } = await signedUpClient(); + const addressId = (await api.post('/api/addresses', address)).body.id; + const clientId = (await api.post('/api/clients', clientBody)).body.id; + const bankAccountId = (await api.post('/api/bank-accounts', bankAccount)).body + .id; + const project = (await api.post('/api/projects', { name: 'Zammad Audio' })) + .body; + + const invoiceBody = { + name: 'Invoice 03/2018', + number: 3, + date: '2018-04-13', + dueDate: '2018-05-13', + memo: 'Thanks', + discountCents: 10000, + taxRate: 19, + currencyCode: 'CAD', + clientId, + bankAccountId, + userAddressId: addressId, + items: [ + { + title: 'Audio player', + qty: 2, + unitPriceCents: 30000, + projectId: project.id, + }, + { title: 'Server setup', qty: 1, unitPriceCents: 30000, projectId: null }, + ], + }; + const invoice = await api.post('/api/invoices', invoiceBody); + expect(invoice.status).toBe(201); + + return { + api, + name, + addressId, + clientId, + bankAccountId, + project, + invoiceBody, + invoiceId: invoice.body.invoice.id as number, + }; +} + +describe('auth', () => { + it('rejects anonymous requests', async () => { + const res = await client().get('/api/me'); + expect(res.status).toBe(401); + }); + + it('signs up with an httpOnly session cookie', async () => { + const res = await fetch(url('/api/auth/signup'), { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + username: 'cookiemonster', + email: 'cookie@example.com', + password: 'correct horse battery', + }), + }); + expect(res.status).toBe(201); + const cookie = res.headers.getSetCookie().join(';'); + expect(cookie).toMatch(/nuxt-auth-session=/); + expect(cookie).toMatch(/HttpOnly/i); + expect(cookie).toMatch(/SameSite=Lax/i); + // No token in the response body. + expect(await res.json()).toEqual({ + id: expect.any(Number), + name: 'cookiemonster', + }); + }); + + it('refuses a duplicate username or email', async () => { + const { name } = await signedUpClient(); + const res = await client().post('/api/auth/signup', { + username: name, + email: 'someone-else@example.com', + password: 'correct horse battery', + }); + expect(res.status).toBe(409); + }); + + it('validates the sign-up body', async () => { + const res = await client().post('/api/auth/signup', { + username: '', + email: 'nope', + password: 'short', + }); + expect(res.status).toBe(400); + expect(res.body.data.issues.map((i: { path: string }) => i.path)).toEqual([ + 'username', + 'email', + 'password', + ]); + }); + + it('signs in, out and back in', async () => { + const { api, name } = await signedUpClient(); + expect((await api.post('/api/auth/signout')).status).toBe(200); + expect((await api.get('/api/me')).status).toBe(401); + + const wrong = await api.post('/api/auth/signin', { + username: name, + password: 'wrong password', + }); + expect(wrong.status).toBe(401); + + const ok = await api.post('/api/auth/signin', { + username: `${name}@example.com`, + password: 'correct horse battery', + }); + expect(ok.status).toBe(200); + expect((await api.get('/api/me')).body.name).toBe(name); + }); + + it('accepts a legacy bcrypt hash and upgrades it to scrypt', async () => { + const sqlite = new Database(databasePath); + sqlite + .prepare('insert into users (name, email, password) values (?, ?, ?)') + .run('legacy', 'legacy@example.com', bcrypt.hashSync('oldpassword', 4)); + + const api = client(); + const res = await api.post('/api/auth/signin', { + username: 'legacy', + password: 'oldpassword', + }); + expect(res.status).toBe(200); + + const { password } = sqlite + .prepare('select password from users where name = ?') + .get('legacy') as { password: string }; + sqlite.close(); + expect(password.startsWith('$scrypt')).toBe(true); + + // The new hash works too. + const again = await client().post('/api/auth/signin', { + username: 'legacy', + password: 'oldpassword', + }); + expect(again.status).toBe(200); + }); + + it('changes the password', async () => { + const { api, name } = await signedUpClient(); + const wrong = await api.put('/api/me/password', { + currentPassword: 'nope', + password: 'a brand new password', + }); + expect(wrong.status).toBe(400); + + const ok = await api.put('/api/me/password', { + currentPassword: 'correct horse battery', + password: 'a brand new password', + }); + expect(ok.status).toBe(200); + + const signin = await client().post('/api/auth/signin', { + username: name, + password: 'a brand new password', + }); + expect(signin.status).toBe(200); + }); +}); + +describe('profile and settings', () => { + it('updates the profile', async () => { + const { api, name } = await signedUpClient(); + const res = await api.put('/api/me', { + email: `${name}@example.org`, + firstName: 'Jane', + lastName: '', + taxNumber: '12/345/67890', + }); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + email: `${name}@example.org`, + firstName: 'Jane', + lastName: null, + taxNumber: '12/345/67890', + }); + expect(res.body).not.toHaveProperty('password'); + }); + + it('lists the currencies', async () => { + const { api } = await signedUpClient(); + const res = await api.get('/api/currencies'); + expect(res.body.map((c: { code: string }) => c.code)).toEqual([ + 'CAD', + 'EUR', + 'USD', + ]); + }); + + it('does CRUD on addresses', async () => { + const { api } = await signedUpClient(); + const created = await api.post('/api/addresses', address); + expect(created.status).toBe(201); + const id = created.body.id; + + const updated = await api.put(`/api/addresses/${id}`, { + ...address, + city: 'Hamburg', + }); + expect(updated.body.city).toBe('Hamburg'); + expect((await api.get('/api/addresses')).body).toHaveLength(1); + + expect((await api.delete(`/api/addresses/${id}`)).status).toBe(204); + expect((await api.get('/api/addresses')).body).toHaveLength(0); + }); + + it('normalises bank accounts and refuses duplicates', async () => { + const { api } = await signedUpClient(); + const created = await api.post('/api/bank-accounts', bankAccount); + expect(created.status).toBe(201); + expect(created.body.iban).toBe('DE46100500001061334232'); + + const duplicate = await api.post('/api/bank-accounts', bankAccount); + expect(duplicate.status).toBe(409); + + const invalid = await api.post('/api/bank-accounts', { + ...bankAccount, + iban: 'not an iban', + }); + expect(invalid.status).toBe(400); + }); + + it('keeps a client and its address together', async () => { + const { api } = await signedUpClient(); + const created = await api.post('/api/clients', clientBody); + expect(created.body).toMatchObject({ + name: 'Farm Radio International', + address: { street: '1404 Scott Street', city: 'Ottawa' }, + }); + + const updated = await api.put(`/api/clients/${created.body.id}`, { + ...clientBody, + street: '1 New Street', + }); + expect(updated.body.address.street).toBe('1 New Street'); + + // Client addresses don't show up as the user's own addresses. + expect((await api.get('/api/addresses')).body).toHaveLength(0); + + expect((await api.delete(`/api/clients/${created.body.id}`)).status).toBe( + 204 + ); + expect((await api.get('/api/clients')).body).toHaveLength(0); + }); + + it('manages projects by slug', async () => { + const { api } = await signedUpClient(); + const created = await api.post('/api/projects', { + name: 'Website Redesign!', + }); + expect(created.body.slug).toBe('website-redesign'); + + const duplicate = await api.post('/api/projects', { + name: 'Website Redesign', + }); + expect(duplicate.status).toBe(409); + + const renamed = await api.put('/api/projects/website-redesign', { + name: 'New name', + }); + expect(renamed.body).toMatchObject({ + name: 'New name', + slug: 'website-redesign', + }); + + expect((await api.delete('/api/projects/website-redesign')).status).toBe( + 204 + ); + expect((await api.get('/api/projects/website-redesign')).status).toBe(404); + }); + + it('is not injectable through the slug', async () => { + const { api } = await signedUpClient(); + await api.post('/api/projects', { name: 'Secret' }); + const res = await api.get("/api/projects/x'%20or%201=1--"); + expect(res.status).toBe(404); + }); +}); + +describe('invoices', () => { + it('creates an invoice with items and computes totals', async () => { + const { api, invoiceId } = await userWithInvoice(); + + const doc = await api.get(`/api/invoices/${invoiceId}`); + expect(doc.status).toBe(200); + expect(doc.body.invoice).toMatchObject({ + number: 3, + discountCents: 10000, + taxRate: 19, + }); + expect(doc.body.items).toHaveLength(2); + expect(doc.body.currency.code).toBe('CAD'); + expect(doc.body.client.address.city).toBe('Ottawa'); + expect(doc.body.bankAccount.iban).toBe('DE46100500001061334232'); + + const list = await api.get('/api/invoices'); + expect(list.body).toHaveLength(1); + expect(list.body[0].totals).toEqual({ + netCents: 90000, + discountCents: 10000, + taxCents: 15200, + totalCents: 95200, + }); + }); + + it('updates an invoice and replaces its items', async () => { + const { api, invoiceId, invoiceBody } = await userWithInvoice(); + const res = await api.put(`/api/invoices/${invoiceId}`, { + ...invoiceBody, + name: 'Renamed', + items: [{ title: 'Only item', qty: 1.5, unitPriceCents: 1000 }], + }); + expect(res.status).toBe(200); + expect(res.body.invoice.name).toBe('Renamed'); + expect(res.body.items).toEqual([ + expect.objectContaining({ + title: 'Only item', + qty: 1.5, + unitPriceCents: 1000, + }), + ]); + }); + + it('refuses duplicate numbers and empty invoices', async () => { + const { api, invoiceBody } = await userWithInvoice(); + const duplicate = await api.post('/api/invoices', invoiceBody); + expect(duplicate.status).toBe(409); + + const empty = await api.post('/api/invoices', { + ...invoiceBody, + number: 99, + items: [], + }); + expect(empty.status).toBe(400); + expect(empty.body.data.issues[0].message).toBe('Add at least one item'); + }); + + it('protects records that invoices point at', async () => { + const { api, clientId, bankAccountId, addressId } = await userWithInvoice(); + expect((await api.delete(`/api/clients/${clientId}`)).status).toBe(409); + expect( + (await api.delete(`/api/bank-accounts/${bankAccountId}`)).status + ).toBe(409); + expect((await api.delete(`/api/addresses/${addressId}`)).status).toBe(409); + }); + + it('deletes an invoice with its items', async () => { + const { api, invoiceId } = await userWithInvoice(); + expect((await api.delete(`/api/invoices/${invoiceId}`)).status).toBe(204); + expect((await api.get(`/api/invoices/${invoiceId}`)).status).toBe(404); + + const sqlite = new Database(databasePath, { readonly: true }); + const { count } = sqlite + .prepare('select count(*) as count from items where invoice_id = ?') + .get(invoiceId) as { count: number }; + sqlite.close(); + expect(count).toBe(0); + }); + + it.skipIf(!chromeBin)('renders the PDF', async () => { + const { api, invoiceId } = await userWithInvoice(); + const res = await api.get(`/api/invoices/${invoiceId}/pdf`); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('application/pdf'); + expect(res.headers.get('content-disposition')).toMatch( + /attachment; filename="003-invoice-032018/ + ); + const bytes = new Uint8Array(res.body as ArrayBuffer); + expect(new TextDecoder().decode(bytes.slice(0, 5))).toBe('%PDF-'); + }); +}); + +describe('isolation between users', () => { + it("never exposes or touches another user's data", async () => { + const alice = await userWithInvoice(); + const { api: bob } = await signedUpClient(); + + // Reads + expect((await bob.get(`/api/invoices/${alice.invoiceId}`)).status).toBe( + 404 + ); + expect((await bob.get(`/api/invoices/${alice.invoiceId}/pdf`)).status).toBe( + 404 + ); + expect((await bob.get('/api/invoices')).body).toEqual([]); + expect((await bob.get('/api/clients')).body).toEqual([]); + expect((await bob.get('/api/addresses')).body).toEqual([]); + expect((await bob.get('/api/bank-accounts')).body).toEqual([]); + expect((await bob.get('/api/projects')).body).toEqual([]); + expect((await bob.get(`/api/projects/${alice.project.slug}`)).status).toBe( + 404 + ); + + // Writes + expect( + (await bob.put(`/api/invoices/${alice.invoiceId}`, alice.invoiceBody)) + .status + ).toBe(400); // references Alice's client etc. + expect( + ( + await bob.put(`/api/invoices/${alice.invoiceId}`, { + ...alice.invoiceBody, + clientId: null, + bankAccountId: null, + userAddressId: null, + items: [{ title: 'x', qty: 1, unitPriceCents: 1 }], + }) + ).status + ).toBe(404); + expect((await bob.delete(`/api/invoices/${alice.invoiceId}`)).status).toBe( + 404 + ); + expect( + (await bob.put(`/api/addresses/${alice.addressId}`, address)).status + ).toBe(404); + expect((await bob.delete(`/api/clients/${alice.clientId}`)).status).toBe( + 404 + ); + expect( + (await bob.delete(`/api/bank-accounts/${alice.bankAccountId}`)).status + ).toBe(404); + + // Bob can't attach Alice's records to his own invoice or project. + const stealing = await bob.post('/api/invoices', { + ...alice.invoiceBody, + clientId: alice.clientId, + }); + expect(stealing.status).toBe(400); + const stealingProject = await bob.post('/api/projects', { + name: 'Mine', + clientId: alice.clientId, + }); + expect(stealingProject.status).toBe(400); + + // Alice's data is untouched. + const doc = await alice.api.get(`/api/invoices/${alice.invoiceId}`); + expect(doc.body.invoice.name).toBe('Invoice 03/2018'); + expect(doc.body.items).toHaveLength(2); + }); +}); diff --git a/test/unit/format.test.ts b/test/unit/format.test.ts new file mode 100644 index 0000000..9667433 --- /dev/null +++ b/test/unit/format.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { + formatDate, + formatIban, + formatInvoiceNumber, + formatMoney, + formatPercentage, + toCents, +} from '../../shared/utils/format'; +import { invoiceFilename } from '../../shared/utils/invoice-filename'; + +const euro = { sign: '€', leading: false }; +const dollar = { sign: '$', leading: true }; + +describe('formatMoney', () => { + it('puts the sign after the amount for EUR', () => { + expect(formatMoney(123456, euro)).toBe('1,234.56€'); + }); + + it('puts the sign before the amount for USD/CAD', () => { + expect(formatMoney(60000, dollar)).toBe('$600.00'); + }); + + it('defaults to euros', () => { + expect(formatMoney(5)).toBe('0.05€'); + }); + + it('keeps the minus sign in front', () => { + expect(formatMoney(-1999, dollar)).toBe('-$19.99'); + expect(formatMoney(-1999, euro)).toBe('-19.99€'); + }); +}); + +describe('formatIban', () => { + it('groups by four', () => { + expect(formatIban('DE46100500001061334232')).toBe( + 'DE46 1005 0000 1061 3342 32' + ); + }); + + it('normalises spaces and case', () => { + expect(formatIban(' de46 1005 0000 1061 3342 32 ')).toBe( + 'DE46 1005 0000 1061 3342 32' + ); + }); + + it('handles other lengths and empty values', () => { + expect(formatIban('NL91ABNA0417164300')).toBe('NL91 ABNA 0417 1643 00'); + expect(formatIban('')).toBe(''); + expect(formatIban(null)).toBe(''); + }); +}); + +describe('other formatters', () => { + it('pads invoice numbers to three digits', () => { + expect(formatInvoiceNumber(7)).toBe('007'); + expect(formatInvoiceNumber(1234)).toBe('1234'); + }); + + it('formats percentages', () => { + expect(formatPercentage(19)).toBe('19.00%'); + expect(formatPercentage(7.7)).toBe('7.70%'); + }); + + it('formats ISO dates', () => { + expect(formatDate('2018-04-13')).toBe('13/04/2018'); + expect(formatDate('2018-04-13', 'yyyy')).toBe('2018'); + expect(formatDate('not a date')).toBe(''); + expect(formatDate(null)).toBe(''); + }); + + it('converts decimals to cents without float drift', () => { + expect(toCents(0.1 + 0.2)).toBe(30); + expect(toCents('19.99')).toBe(1999); + expect(toCents('')).toBe(0); + }); + + it('builds the PDF filename', () => { + expect( + invoiceFilename( + { number: 3, name: 'Invoice Farm Radio 03/2018' }, + { firstName: 'Loïc', lastName: 'Nogues' } + ) + ).toBe('003-invoice-farm-radio-032018-loic-nogues.pdf'); + }); +}); diff --git a/test/unit/invoice-document.test.ts b/test/unit/invoice-document.test.ts new file mode 100644 index 0000000..f57b099 --- /dev/null +++ b/test/unit/invoice-document.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it } from 'vitest'; +import { createSSRApp, h } from 'vue'; +import { renderToString } from 'vue/server-renderer'; +import { InvoiceDocument } from '../../shared/invoice/document'; +import type { InvoiceDocumentData } from '../../shared/types/models'; + +const data: InvoiceDocumentData = { + invoice: { + id: 1, + number: 3, + name: 'Invoice Farm Radio International 03/2018', + date: '2018-04-13', + dueDate: '2018-05-13', + memo: 'Thank you!', + discountCents: 10000, + taxRate: 19, + currencyCode: 'CAD', + clientId: 1, + bankAccountId: 1, + userAddressId: 1, + }, + items: [ + { + id: 1, + title: 'Zammad audio player', + qty: 2, + unitPriceCents: 30000, + projectId: null, + }, + { + id: 2, + title: 'Server configuration', + qty: 1, + unitPriceCents: 30000, + projectId: null, + }, + ], + currency: { code: 'CAD', name: 'Canadian dollar', sign: '$', leading: true }, + client: { + id: 1, + name: 'Farm Radio International', + taxNumber: null, + vatNumber: 'CA123', + address: { + extra: null, + street: '1404 Scott Street', + city: 'Ottawa', + postcode: 'K1Y 4M8', + country: 'Canada', + }, + }, + issuer: { + firstName: 'Loïc', + lastName: 'Nogues', + email: 'loic@example.com', + tel: null, + website: null, + taxNumber: '31/457/01861', + vatNumber: null, + }, + userAddress: { + extra: 'c/o Someone', + street: 'Wisbyerstr. 22A', + city: 'Berlin', + postcode: '10439', + country: 'Germany', + }, + bankAccount: { + name: 'Sparkasse Berlin', + owner: 'Loïc Nogues', + iban: 'DE46100500001061334232', + bic: 'BELADEBEXXX', + }, +}; + +const render = (doc: InvoiceDocumentData) => + renderToString( + createSSRApp({ render: () => h(InvoiceDocument, { data: doc }) }) + ); + +describe('InvoiceDocument', () => { + it('renders the parties, lines, totals and bank details', async () => { + const html = await render(data); + + for (const text of [ + 'Invoice Farm Radio International 03/2018', + 'Loïc Nogues', + 'c/o Someone', + '10439 Berlin, Germany', + 'Steuernummer: 31/457/01861', + 'Farm Radio International', + 'K1Y 4M8 Ottawa, Canada', + 'VAT number: CA123', + '>003<', + '13/04/2018', + '13/05/2018', + 'Amount (CAD)', + '$600.00', + '$900.00', // net + '$100.00', // discount + '19.00%', + '$152.00', // tax + '$952.00', // total + 'Thank you!', + 'DE46 1005 0000 1061 3342 32', + 'BELADEBEXXX', + ]) { + expect(html).toContain(text); + } + }); + + it('escapes user content', async () => { + const html = await render({ + ...data, + invoice: { ...data.invoice, name: '' }, + }); + expect(html).not.toContain(''); + expect(html).toContain('<script>'); + }); + + it('copes with a missing client, address and bank account', async () => { + const html = await render({ + ...data, + client: null, + userAddress: null, + bankAccount: null, + }); + expect(html).toContain('$952.00'); + expect(html).not.toContain('IBAN'); + }); +}); diff --git a/test/unit/invoice-totals.test.ts b/test/unit/invoice-totals.test.ts new file mode 100644 index 0000000..f8b56dd --- /dev/null +++ b/test/unit/invoice-totals.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { + computeInvoiceTotals, + lineAmountCents, +} from '../../shared/utils/invoice-totals'; + +describe('computeInvoiceTotals', () => { + const items = [ + { qty: 2, unitPriceCents: 30000 }, + { qty: 1, unitPriceCents: 30000 }, + ]; + + it('sums the lines', () => { + expect(computeInvoiceTotals(items)).toEqual({ + netCents: 90000, + discountCents: 0, + taxCents: 0, + totalCents: 90000, + }); + }); + + it('applies the discount before tax', () => { + // (900 - 100) * 19% = 152 + expect(computeInvoiceTotals(items, 10000, 19)).toEqual({ + netCents: 90000, + discountCents: 10000, + taxCents: 15200, + totalCents: 95200, + }); + }); + + it('rounds tax to the cent', () => { + const totals = computeInvoiceTotals( + [{ qty: 1, unitPriceCents: 999 }], + 0, + 19 + ); + expect(totals.taxCents).toBe(190); // 189.81 + expect(totals.totalCents).toBe(1189); + }); + + it('rounds fractional quantities per line', () => { + expect(lineAmountCents({ qty: 1.5, unitPriceCents: 33333 })).toBe(50000); + expect(lineAmountCents({ qty: 0.1, unitPriceCents: 3 })).toBe(0); + }); + + it('ignores negative discounts and handles no items', () => { + expect(computeInvoiceTotals([], -500, 19)).toEqual({ + netCents: 0, + discountCents: 0, + taxCents: 0, + totalCents: 0, + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 2f75d4a..cae87c0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,18 +1,9 @@ { - "compilerOptions": { - "sourceMap": true, - "strict": true, - "noImplicitAny": false, - "noImplicitReturns": true, - "module": "ESNext", - "moduleResolution": "node", - "skipLibCheck": true, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es2017", - "resolveJsonModule": true, - "esModuleInterop": false - }, - "include": ["./src/**/*"], - "exclude": ["node_modules"] + "files": [], + "references": [ + { "path": "./.nuxt/tsconfig.app.json" }, + { "path": "./.nuxt/tsconfig.server.json" }, + { "path": "./.nuxt/tsconfig.shared.json" }, + { "path": "./.nuxt/tsconfig.node.json" } + ] } diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 45afb5f..0000000 --- a/tslint.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "rules": { - "member-access": false, - "member-ordering": [ - true, - "public-before-private", - "static-before-instance", - "variables-before-functions" - ], - "no-any": false, - "no-inferrable-types": [false], - "no-internal-module": true, - "no-var-requires": true, - "typedef": [false], - "typedef-whitespace": [ - true, { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - }, { - "call-signature": "space", - "index-signature": "space", - "parameter": "space", - "property-declaration": "space", - "variable-declaration": "space" - } - ], - "ban": false, - "curly": false, - "forin": true, - "label-position": true, - "no-arg": true, - "no-bitwise": true, - "no-conditional-assignment": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-variable": true, - "no-empty": true, - "no-eval": true, - "no-null-keyword": true, - "no-shadowed-variable": true, - "no-string-literal": true, - "no-switch-case-fall-through": true, - "no-unused-expression": true, - "no-var-keyword": true, - "radix": true, - "switch-default": true, - "triple-equals": [ - true, - "allow-undefined-check" - ], - "eofline": false, - "indent": [ - true, - "spaces" - ], - "max-line-length": [ - true, - 150 - ], - "no-require-imports": false, - "no-trailing-whitespace": true, - "object-literal-sort-keys": false, - "trailing-comma": [ - false, { - "multiline": "always", - "singleline": "never" - } - ], - "align": [true], - "class-name": true, - "comment-format": [ - false, - "check-space" - ], - "interface-name": [false], - "jsdoc-format": true, - "no-consecutive-blank-lines": [true], - "no-parameter-properties": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-finally", - "check-whitespace" - ], - "quotemark": [ - true, - "single", - "avoid-escape" - ], - "semicolon": [ - true, - "always" - ], - "variable-name": [ - true, - "check-format", - "allow-leading-underscore", - "ban-keywords" - ], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ] - } -} diff --git a/vite.config.ts b/vite.config.ts deleted file mode 100644 index 6c62862..0000000 --- a/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import vue from '@vitejs/plugin-vue'; -import { UserConfig } from 'vite'; - -const config: UserConfig = { - plugins: [vue()], -}; - -export default config; diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..ee38b48 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + projects: [ + { + test: { + name: 'unit', + include: ['test/unit/**/*.test.ts'], + environment: 'node', + }, + }, + { + test: { + name: 'e2e', + include: ['test/e2e/**/*.test.ts'], + environment: 'node', + // The suite builds the app once, then runs it. + hookTimeout: 300_000, + testTimeout: 60_000, + }, + }, + ], + }, +}); diff --git a/webpack.common.js b/webpack.common.js deleted file mode 100644 index bfe4172..0000000 --- a/webpack.common.js +++ /dev/null @@ -1,52 +0,0 @@ -const webpack = require('webpack'); -const path = require('path'); -const { VueLoaderPlugin } = require('vue-loader'); - -module.exports = { - entry: ['./src/client/index.ts'], - output: { - filename: 'index.bundle.js', - chunkFilename: '[name].bundle.js', - path: path.resolve(__dirname, 'dist'), - }, - module: { - rules: [ - { - test: /\.vue$/, - loader: 'vue-loader', - }, - { - test: /\.tsx?$/, - loader: 'ts-loader', - exclude: /node_modules/, - options: { - transpileOnly: true, - experimentalWatchApi: true, - appendTsSuffixTo: [/\.vue$/], - }, - }, - { - test: /\.css$/, - use: [ - 'vue-style-loader', - // 'style-loader', - 'css-loader', - 'postcss-loader', - ], - }, - ], - }, - resolve: { - // alias: { - // vue$: 'vue/dist/vue.esm.js', - // }, - extensions: ['*', '.ts', '.js', '.vue', '.json'], - fallback: { - fs: false, - }, - }, - plugins: [ - // new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), - new VueLoaderPlugin(), - ], -}; diff --git a/webpack.dev.js b/webpack.dev.js deleted file mode 100644 index e9e992f..0000000 --- a/webpack.dev.js +++ /dev/null @@ -1,18 +0,0 @@ -const { merge } = require('webpack-merge'); -const common = require('./webpack.common.js'); -const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') - .BundleAnalyzerPlugin; - -module.exports = merge(common, { - mode: 'development', - devtool: 'inline-source-map', - devServer: { - contentBase: './dist', - }, - plugins: [ - new BundleAnalyzerPlugin({ - analyzerHost: '0.0.0.0', - openAnalyzer: false, - }), - ], -}); diff --git a/webpack.prod.js b/webpack.prod.js deleted file mode 100644 index a75c2b9..0000000 --- a/webpack.prod.js +++ /dev/null @@ -1,23 +0,0 @@ -const webpack = require('webpack'); -const { merge } = require('webpack-merge'); -// const MinifyPlugin = require('babel-minify-webpack-plugin'); -const common = require('./webpack.common.js'); - -module.exports = merge(common, { - output: { - publicPath: '/dist/', - }, - mode: 'production', - plugins: [ - // new MinifyPlugin(), - new webpack.LoaderOptionsPlugin({ - minimize: true, - debug: false, - }), - new webpack.DefinePlugin({ - 'process.env': { - NODE_ENV: '"production"', - }, - }), - ], -});