22 Commits
2.0.0 ... 2.3.0

Author SHA1 Message Date
abbf39f160 Theme select & Accessability :^)
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m0s
2026-01-27 14:26:14 -07:00
e2949a28ef Update new.astro
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m9s
2026-01-20 12:59:32 -07:00
8b91ec7a71 Updated to Astro 6 beta
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m52s
2026-01-20 12:37:08 -07:00
815c08dd50 Schema fixes
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m59s
2026-01-20 12:08:06 -07:00
55eb03165e Fixed migrations
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m2s
2026-01-20 11:36:52 -07:00
a4071d6e40 Fixed charts
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m3s
2026-01-20 11:24:41 -07:00
fff0e14a4b Fixed
Some checks failed
Docker Deploy / build-and-push (push) Failing after 3m7s
2026-01-20 11:10:31 -07:00
ad7dc18780 Switch to tags
Some checks failed
Docker Deploy / build-and-push (push) Has been cancelled
2026-01-20 11:09:09 -07:00
de5b1063b7 Migrate
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m24s
2026-01-20 10:47:43 -07:00
82b45fdfe4 O_O
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m2s
2026-01-20 10:32:14 -07:00
b5ac2e0608 Oops
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m0s
2026-01-20 01:21:56 -07:00
6bed4b4709 Last fix for the night...
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m9s
2026-01-20 01:06:06 -07:00
54cac49b70 OOOOOPS
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m56s
2026-01-19 23:39:00 -07:00
effc6ac37e oops
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m6s
2026-01-19 22:25:25 -07:00
df82a02f41 2.2.1 - Misc improvements and cleanup
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m3s
2026-01-19 21:08:46 -07:00
8a3932a013 Optimizations
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m5s
2026-01-19 20:55:47 -07:00
d4a2c5853b 2.2.0 Migrations
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m30s
2026-01-19 19:41:56 -07:00
ee9807e8e0 Passkeys!
Some checks failed
Docker Deploy / build-and-push (push) Has been cancelled
2026-01-19 15:53:05 -07:00
bf2a1816db Added custom ranges for report filtering + CSV exports
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m59s
2026-01-19 15:18:34 -07:00
1063bf99f1 2.1.0
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m24s
2026-01-19 10:06:23 -07:00
ea0a83f44d Added discounts to invoices
Some checks failed
Docker Deploy / build-and-push (push) Has been cancelled
2026-01-19 10:06:04 -07:00
fa2c92644a Forgot these...
All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m4s
2026-01-18 14:57:32 -07:00
82 changed files with 4768 additions and 2451 deletions

View File

@@ -10,11 +10,12 @@ import node from "@astrojs/node";
export default defineConfig({ export default defineConfig({
output: "server", output: "server",
integrations: [vue(), icon()], integrations: [vue(), icon()],
security: {
csp: process.env.NODE_ENV === "production",
},
vite: { vite: {
plugins: [tailwindcss()], plugins: [tailwindcss()],
}, },
adapter: node({ adapter: node({
mode: "standalone", mode: "standalone",
}), }),

View File

@@ -10,24 +10,23 @@ CREATE TABLE `api_tokens` (
); );
--> statement-breakpoint --> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_token_unique` ON `api_tokens` (`token`);--> statement-breakpoint CREATE UNIQUE INDEX `api_tokens_token_unique` ON `api_tokens` (`token`);--> statement-breakpoint
CREATE TABLE `categories` ( CREATE INDEX `api_tokens_user_id_idx` ON `api_tokens` (`user_id`);--> statement-breakpoint
`id` text PRIMARY KEY NOT NULL,
`organization_id` text NOT NULL,
`name` text NOT NULL,
`color` text,
`created_at` integer,
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE TABLE `clients` ( CREATE TABLE `clients` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`organization_id` text NOT NULL, `organization_id` text NOT NULL,
`name` text NOT NULL, `name` text NOT NULL,
`email` text, `email` text,
`phone` text,
`street` text,
`city` text,
`state` text,
`zip` text,
`country` text,
`created_at` integer, `created_at` integer,
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `clients_organization_id_idx` ON `clients` (`organization_id`);--> statement-breakpoint
CREATE TABLE `invoice_items` ( CREATE TABLE `invoice_items` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`invoice_id` text NOT NULL, `invoice_id` text NOT NULL,
@@ -38,6 +37,7 @@ CREATE TABLE `invoice_items` (
FOREIGN KEY (`invoice_id`) REFERENCES `invoices`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`invoice_id`) REFERENCES `invoices`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `invoice_items_invoice_id_idx` ON `invoice_items` (`invoice_id`);--> statement-breakpoint
CREATE TABLE `invoices` ( CREATE TABLE `invoices` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`organization_id` text NOT NULL, `organization_id` text NOT NULL,
@@ -50,6 +50,9 @@ CREATE TABLE `invoices` (
`notes` text, `notes` text,
`currency` text DEFAULT 'USD' NOT NULL, `currency` text DEFAULT 'USD' NOT NULL,
`subtotal` integer DEFAULT 0 NOT NULL, `subtotal` integer DEFAULT 0 NOT NULL,
`discount_value` real DEFAULT 0,
`discount_type` text DEFAULT 'percentage',
`discount_amount` integer DEFAULT 0,
`tax_rate` real DEFAULT 0, `tax_rate` real DEFAULT 0,
`tax_amount` integer DEFAULT 0 NOT NULL, `tax_amount` integer DEFAULT 0 NOT NULL,
`total` integer DEFAULT 0 NOT NULL, `total` integer DEFAULT 0 NOT NULL,
@@ -58,6 +61,8 @@ CREATE TABLE `invoices` (
FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `invoices_organization_id_idx` ON `invoices` (`organization_id`);--> statement-breakpoint
CREATE INDEX `invoices_client_id_idx` ON `invoices` (`client_id`);--> statement-breakpoint
CREATE TABLE `members` ( CREATE TABLE `members` (
`user_id` text NOT NULL, `user_id` text NOT NULL,
`organization_id` text NOT NULL, `organization_id` text NOT NULL,
@@ -68,6 +73,8 @@ CREATE TABLE `members` (
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `members_user_id_idx` ON `members` (`user_id`);--> statement-breakpoint
CREATE INDEX `members_organization_id_idx` ON `members` (`organization_id`);--> statement-breakpoint
CREATE TABLE `organizations` ( CREATE TABLE `organizations` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL, `name` text NOT NULL,
@@ -77,9 +84,33 @@ CREATE TABLE `organizations` (
`state` text, `state` text,
`zip` text, `zip` text,
`country` text, `country` text,
`default_tax_rate` real DEFAULT 0,
`default_currency` text DEFAULT 'USD',
`created_at` integer `created_at` integer
); );
--> statement-breakpoint --> statement-breakpoint
CREATE TABLE `passkey_challenges` (
`id` text PRIMARY KEY NOT NULL,
`challenge` text NOT NULL,
`user_id` text,
`expires_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `passkey_challenges_challenge_unique` ON `passkey_challenges` (`challenge`);--> statement-breakpoint
CREATE TABLE `passkeys` (
`id` text PRIMARY KEY NOT NULL,
`user_id` text NOT NULL,
`public_key` text NOT NULL,
`counter` integer NOT NULL,
`device_type` text NOT NULL,
`backed_up` integer NOT NULL,
`transports` text,
`last_used_at` integer,
`created_at` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `passkeys_user_id_idx` ON `passkeys` (`user_id`);--> statement-breakpoint
CREATE TABLE `sessions` ( CREATE TABLE `sessions` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`user_id` text NOT NULL, `user_id` text NOT NULL,
@@ -87,6 +118,7 @@ CREATE TABLE `sessions` (
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `sessions_user_id_idx` ON `sessions` (`user_id`);--> statement-breakpoint
CREATE TABLE `site_settings` ( CREATE TABLE `site_settings` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`key` text NOT NULL, `key` text NOT NULL,
@@ -100,27 +132,33 @@ CREATE TABLE `tags` (
`organization_id` text NOT NULL, `organization_id` text NOT NULL,
`name` text NOT NULL, `name` text NOT NULL,
`color` text, `color` text,
`rate` integer DEFAULT 0,
`created_at` integer, `created_at` integer,
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `tags_organization_id_idx` ON `tags` (`organization_id`);--> statement-breakpoint
CREATE TABLE `time_entries` ( CREATE TABLE `time_entries` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`user_id` text NOT NULL, `user_id` text NOT NULL,
`organization_id` text NOT NULL, `organization_id` text NOT NULL,
`client_id` text NOT NULL, `client_id` text NOT NULL,
`category_id` text NOT NULL,
`start_time` integer NOT NULL, `start_time` integer NOT NULL,
`end_time` integer, `end_time` integer,
`description` text, `description` text,
`invoice_id` text,
`is_manual` integer DEFAULT false, `is_manual` integer DEFAULT false,
`created_at` integer, `created_at` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON UPDATE no action ON DELETE no action
FOREIGN KEY (`category_id`) REFERENCES `categories`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `time_entries_user_id_idx` ON `time_entries` (`user_id`);--> statement-breakpoint
CREATE INDEX `time_entries_organization_id_idx` ON `time_entries` (`organization_id`);--> statement-breakpoint
CREATE INDEX `time_entries_client_id_idx` ON `time_entries` (`client_id`);--> statement-breakpoint
CREATE INDEX `time_entries_start_time_idx` ON `time_entries` (`start_time`);--> statement-breakpoint
CREATE INDEX `time_entries_invoice_id_idx` ON `time_entries` (`invoice_id`);--> statement-breakpoint
CREATE TABLE `time_entry_tags` ( CREATE TABLE `time_entry_tags` (
`time_entry_id` text NOT NULL, `time_entry_id` text NOT NULL,
`tag_id` text NOT NULL, `tag_id` text NOT NULL,
@@ -129,6 +167,8 @@ CREATE TABLE `time_entry_tags` (
FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
CREATE INDEX `time_entry_tags_time_entry_id_idx` ON `time_entry_tags` (`time_entry_id`);--> statement-breakpoint
CREATE INDEX `time_entry_tags_tag_id_idx` ON `time_entry_tags` (`tag_id`);--> statement-breakpoint
CREATE TABLE `users` ( CREATE TABLE `users` (
`id` text PRIMARY KEY NOT NULL, `id` text PRIMARY KEY NOT NULL,
`email` text NOT NULL, `email` text NOT NULL,

View File

@@ -0,0 +1,3 @@
DROP TABLE `time_entry_tags`;--> statement-breakpoint
ALTER TABLE `time_entries` ADD `tag_id` text REFERENCES tags(id);--> statement-breakpoint
CREATE INDEX `time_entries_tag_id_idx` ON `time_entries` (`tag_id`);

View File

@@ -1,6 +0,0 @@
ALTER TABLE `clients` ADD `phone` text;--> statement-breakpoint
ALTER TABLE `clients` ADD `street` text;--> statement-breakpoint
ALTER TABLE `clients` ADD `city` text;--> statement-breakpoint
ALTER TABLE `clients` ADD `state` text;--> statement-breakpoint
ALTER TABLE `clients` ADD `zip` text;--> statement-breakpoint
ALTER TABLE `clients` ADD `country` text;

View File

@@ -1,7 +1,7 @@
{ {
"version": "6", "version": "6",
"dialect": "sqlite", "dialect": "sqlite",
"id": "e1e0fee4-786a-4f9f-9ebe-659aae0a55be", "id": "8343b003-264b-444a-9782-07d736dd3407",
"prevId": "00000000-0000-0000-0000-000000000000", "prevId": "00000000-0000-0000-0000-000000000000",
"tables": { "tables": {
"api_tokens": { "api_tokens": {
@@ -65,6 +65,13 @@
"token" "token"
], ],
"isUnique": true "isUnique": true
},
"api_tokens_user_id_idx": {
"name": "api_tokens_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
} }
}, },
"foreignKeys": { "foreignKeys": {
@@ -86,65 +93,6 @@
"uniqueConstraints": {}, "uniqueConstraints": {},
"checkConstraints": {} "checkConstraints": {}
}, },
"categories": {
"name": "categories",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"organization_id": {
"name": "organization_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"categories_organization_id_organizations_id_fk": {
"name": "categories_organization_id_organizations_id_fk",
"tableFrom": "categories",
"tableTo": "organizations",
"columnsFrom": [
"organization_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"clients": { "clients": {
"name": "clients", "name": "clients",
"columns": { "columns": {
@@ -176,6 +124,48 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"phone": {
"name": "phone",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"street": {
"name": "street",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"city": {
"name": "city",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"zip": {
"name": "zip",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"country": {
"name": "country",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "integer", "type": "integer",
@@ -184,7 +174,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"clients_organization_id_idx": {
"name": "clients_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"clients_organization_id_organizations_id_fk": { "clients_organization_id_organizations_id_fk": {
"name": "clients_organization_id_organizations_id_fk", "name": "clients_organization_id_organizations_id_fk",
@@ -253,7 +251,15 @@
"default": 0 "default": 0
} }
}, },
"indexes": {}, "indexes": {
"invoice_items_invoice_id_idx": {
"name": "invoice_items_invoice_id_idx",
"columns": [
"invoice_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"invoice_items_invoice_id_invoices_id_fk": { "invoice_items_invoice_id_invoices_id_fk": {
"name": "invoice_items_invoice_id_invoices_id_fk", "name": "invoice_items_invoice_id_invoices_id_fk",
@@ -357,6 +363,30 @@
"autoincrement": false, "autoincrement": false,
"default": 0 "default": 0
}, },
"discount_value": {
"name": "discount_value",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"discount_type": {
"name": "discount_type",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'percentage'"
},
"discount_amount": {
"name": "discount_amount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"tax_rate": { "tax_rate": {
"name": "tax_rate", "name": "tax_rate",
"type": "real", "type": "real",
@@ -389,7 +419,22 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"invoices_organization_id_idx": {
"name": "invoices_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
},
"invoices_client_id_idx": {
"name": "invoices_client_id_idx",
"columns": [
"client_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"invoices_organization_id_organizations_id_fk": { "invoices_organization_id_organizations_id_fk": {
"name": "invoices_organization_id_organizations_id_fk", "name": "invoices_organization_id_organizations_id_fk",
@@ -455,7 +500,22 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"members_user_id_idx": {
"name": "members_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
},
"members_organization_id_idx": {
"name": "members_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"members_user_id_users_id_fk": { "members_user_id_users_id_fk": {
"name": "members_user_id_users_id_fk", "name": "members_user_id_users_id_fk",
@@ -555,6 +615,22 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"default_tax_rate": {
"name": "default_tax_rate",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"default_currency": {
"name": "default_currency",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'USD'"
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "integer", "type": "integer",
@@ -569,6 +645,147 @@
"uniqueConstraints": {}, "uniqueConstraints": {},
"checkConstraints": {} "checkConstraints": {}
}, },
"passkey_challenges": {
"name": "passkey_challenges",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"challenge": {
"name": "challenge",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"passkey_challenges_challenge_unique": {
"name": "passkey_challenges_challenge_unique",
"columns": [
"challenge"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"passkeys": {
"name": "passkeys",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"public_key": {
"name": "public_key",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"counter": {
"name": "counter",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"device_type": {
"name": "device_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"backed_up": {
"name": "backed_up",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"transports": {
"name": "transports",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_used_at": {
"name": "last_used_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"passkeys_user_id_idx": {
"name": "passkeys_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"passkeys_user_id_users_id_fk": {
"name": "passkeys_user_id_users_id_fk",
"tableFrom": "passkeys",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": { "sessions": {
"name": "sessions", "name": "sessions",
"columns": { "columns": {
@@ -594,7 +811,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"sessions_user_id_idx": {
"name": "sessions_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"sessions_user_id_users_id_fk": { "sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk", "name": "sessions_user_id_users_id_fk",
@@ -691,6 +916,14 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"rate": {
"name": "rate",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "integer", "type": "integer",
@@ -699,7 +932,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"tags_organization_id_idx": {
"name": "tags_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"tags_organization_id_organizations_id_fk": { "tags_organization_id_organizations_id_fk": {
"name": "tags_organization_id_organizations_id_fk", "name": "tags_organization_id_organizations_id_fk",
@@ -750,13 +991,6 @@
"notNull": true, "notNull": true,
"autoincrement": false "autoincrement": false
}, },
"category_id": {
"name": "category_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"start_time": { "start_time": {
"name": "start_time", "name": "start_time",
"type": "integer", "type": "integer",
@@ -778,6 +1012,13 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"invoice_id": {
"name": "invoice_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"is_manual": { "is_manual": {
"name": "is_manual", "name": "is_manual",
"type": "integer", "type": "integer",
@@ -794,7 +1035,43 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"time_entries_user_id_idx": {
"name": "time_entries_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
},
"time_entries_organization_id_idx": {
"name": "time_entries_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
},
"time_entries_client_id_idx": {
"name": "time_entries_client_id_idx",
"columns": [
"client_id"
],
"isUnique": false
},
"time_entries_start_time_idx": {
"name": "time_entries_start_time_idx",
"columns": [
"start_time"
],
"isUnique": false
},
"time_entries_invoice_id_idx": {
"name": "time_entries_invoice_id_idx",
"columns": [
"invoice_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"time_entries_user_id_users_id_fk": { "time_entries_user_id_users_id_fk": {
"name": "time_entries_user_id_users_id_fk", "name": "time_entries_user_id_users_id_fk",
@@ -834,19 +1111,6 @@
], ],
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
},
"time_entries_category_id_categories_id_fk": {
"name": "time_entries_category_id_categories_id_fk",
"tableFrom": "time_entries",
"tableTo": "categories",
"columnsFrom": [
"category_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
} }
}, },
"compositePrimaryKeys": {}, "compositePrimaryKeys": {},
@@ -871,7 +1135,22 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"time_entry_tags_time_entry_id_idx": {
"name": "time_entry_tags_time_entry_id_idx",
"columns": [
"time_entry_id"
],
"isUnique": false
},
"time_entry_tags_tag_id_idx": {
"name": "time_entry_tags_tag_id_idx",
"columns": [
"tag_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"time_entry_tags_time_entry_id_time_entries_id_fk": { "time_entry_tags_time_entry_id_time_entries_id_fk": {
"name": "time_entry_tags_time_entry_id_time_entries_id_fk", "name": "time_entry_tags_time_entry_id_time_entries_id_fk",

View File

@@ -1,8 +1,8 @@
{ {
"version": "6", "version": "6",
"dialect": "sqlite", "dialect": "sqlite",
"id": "5483c77e-e742-4fbd-8494-d6f9c6c9e28a", "id": "837a4e18-b319-465d-9e30-2614b4850fb5",
"prevId": "e1e0fee4-786a-4f9f-9ebe-659aae0a55be", "prevId": "8343b003-264b-444a-9782-07d736dd3407",
"tables": { "tables": {
"api_tokens": { "api_tokens": {
"name": "api_tokens", "name": "api_tokens",
@@ -65,6 +65,13 @@
"token" "token"
], ],
"isUnique": true "isUnique": true
},
"api_tokens_user_id_idx": {
"name": "api_tokens_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
} }
}, },
"foreignKeys": { "foreignKeys": {
@@ -86,65 +93,6 @@
"uniqueConstraints": {}, "uniqueConstraints": {},
"checkConstraints": {} "checkConstraints": {}
}, },
"categories": {
"name": "categories",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"organization_id": {
"name": "organization_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"color": {
"name": "color",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"categories_organization_id_organizations_id_fk": {
"name": "categories_organization_id_organizations_id_fk",
"tableFrom": "categories",
"tableTo": "organizations",
"columnsFrom": [
"organization_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"clients": { "clients": {
"name": "clients", "name": "clients",
"columns": { "columns": {
@@ -226,7 +174,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"clients_organization_id_idx": {
"name": "clients_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"clients_organization_id_organizations_id_fk": { "clients_organization_id_organizations_id_fk": {
"name": "clients_organization_id_organizations_id_fk", "name": "clients_organization_id_organizations_id_fk",
@@ -295,7 +251,15 @@
"default": 0 "default": 0
} }
}, },
"indexes": {}, "indexes": {
"invoice_items_invoice_id_idx": {
"name": "invoice_items_invoice_id_idx",
"columns": [
"invoice_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"invoice_items_invoice_id_invoices_id_fk": { "invoice_items_invoice_id_invoices_id_fk": {
"name": "invoice_items_invoice_id_invoices_id_fk", "name": "invoice_items_invoice_id_invoices_id_fk",
@@ -399,6 +363,30 @@
"autoincrement": false, "autoincrement": false,
"default": 0 "default": 0
}, },
"discount_value": {
"name": "discount_value",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"discount_type": {
"name": "discount_type",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'percentage'"
},
"discount_amount": {
"name": "discount_amount",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"tax_rate": { "tax_rate": {
"name": "tax_rate", "name": "tax_rate",
"type": "real", "type": "real",
@@ -431,7 +419,22 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"invoices_organization_id_idx": {
"name": "invoices_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
},
"invoices_client_id_idx": {
"name": "invoices_client_id_idx",
"columns": [
"client_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"invoices_organization_id_organizations_id_fk": { "invoices_organization_id_organizations_id_fk": {
"name": "invoices_organization_id_organizations_id_fk", "name": "invoices_organization_id_organizations_id_fk",
@@ -497,7 +500,22 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"members_user_id_idx": {
"name": "members_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
},
"members_organization_id_idx": {
"name": "members_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"members_user_id_users_id_fk": { "members_user_id_users_id_fk": {
"name": "members_user_id_users_id_fk", "name": "members_user_id_users_id_fk",
@@ -597,6 +615,22 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"default_tax_rate": {
"name": "default_tax_rate",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"default_currency": {
"name": "default_currency",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'USD'"
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "integer", "type": "integer",
@@ -611,6 +645,147 @@
"uniqueConstraints": {}, "uniqueConstraints": {},
"checkConstraints": {} "checkConstraints": {}
}, },
"passkey_challenges": {
"name": "passkey_challenges",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"challenge": {
"name": "challenge",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"passkey_challenges_challenge_unique": {
"name": "passkey_challenges_challenge_unique",
"columns": [
"challenge"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"passkeys": {
"name": "passkeys",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"public_key": {
"name": "public_key",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"counter": {
"name": "counter",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"device_type": {
"name": "device_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"backed_up": {
"name": "backed_up",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"transports": {
"name": "transports",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_used_at": {
"name": "last_used_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"passkeys_user_id_idx": {
"name": "passkeys_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": {
"passkeys_user_id_users_id_fk": {
"name": "passkeys_user_id_users_id_fk",
"tableFrom": "passkeys",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": { "sessions": {
"name": "sessions", "name": "sessions",
"columns": { "columns": {
@@ -636,7 +811,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"sessions_user_id_idx": {
"name": "sessions_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"sessions_user_id_users_id_fk": { "sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk", "name": "sessions_user_id_users_id_fk",
@@ -733,6 +916,14 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"rate": {
"name": "rate",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": 0
},
"created_at": { "created_at": {
"name": "created_at", "name": "created_at",
"type": "integer", "type": "integer",
@@ -741,7 +932,15 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"tags_organization_id_idx": {
"name": "tags_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"tags_organization_id_organizations_id_fk": { "tags_organization_id_organizations_id_fk": {
"name": "tags_organization_id_organizations_id_fk", "name": "tags_organization_id_organizations_id_fk",
@@ -792,11 +991,11 @@
"notNull": true, "notNull": true,
"autoincrement": false "autoincrement": false
}, },
"category_id": { "tag_id": {
"name": "category_id", "name": "tag_id",
"type": "text", "type": "text",
"primaryKey": false, "primaryKey": false,
"notNull": true, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"start_time": { "start_time": {
@@ -820,6 +1019,13 @@
"notNull": false, "notNull": false,
"autoincrement": false "autoincrement": false
}, },
"invoice_id": {
"name": "invoice_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"is_manual": { "is_manual": {
"name": "is_manual", "name": "is_manual",
"type": "integer", "type": "integer",
@@ -836,7 +1042,50 @@
"autoincrement": false "autoincrement": false
} }
}, },
"indexes": {}, "indexes": {
"time_entries_user_id_idx": {
"name": "time_entries_user_id_idx",
"columns": [
"user_id"
],
"isUnique": false
},
"time_entries_organization_id_idx": {
"name": "time_entries_organization_id_idx",
"columns": [
"organization_id"
],
"isUnique": false
},
"time_entries_client_id_idx": {
"name": "time_entries_client_id_idx",
"columns": [
"client_id"
],
"isUnique": false
},
"time_entries_tag_id_idx": {
"name": "time_entries_tag_id_idx",
"columns": [
"tag_id"
],
"isUnique": false
},
"time_entries_start_time_idx": {
"name": "time_entries_start_time_idx",
"columns": [
"start_time"
],
"isUnique": false
},
"time_entries_invoice_id_idx": {
"name": "time_entries_invoice_id_idx",
"columns": [
"invoice_id"
],
"isUnique": false
}
},
"foreignKeys": { "foreignKeys": {
"time_entries_user_id_users_id_fk": { "time_entries_user_id_users_id_fk": {
"name": "time_entries_user_id_users_id_fk", "name": "time_entries_user_id_users_id_fk",
@@ -877,60 +1126,9 @@
"onDelete": "no action", "onDelete": "no action",
"onUpdate": "no action" "onUpdate": "no action"
}, },
"time_entries_category_id_categories_id_fk": { "time_entries_tag_id_tags_id_fk": {
"name": "time_entries_category_id_categories_id_fk", "name": "time_entries_tag_id_tags_id_fk",
"tableFrom": "time_entries", "tableFrom": "time_entries",
"tableTo": "categories",
"columnsFrom": [
"category_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"time_entry_tags": {
"name": "time_entry_tags",
"columns": {
"time_entry_id": {
"name": "time_entry_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tag_id": {
"name": "tag_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"time_entry_tags_time_entry_id_time_entries_id_fk": {
"name": "time_entry_tags_time_entry_id_time_entries_id_fk",
"tableFrom": "time_entry_tags",
"tableTo": "time_entries",
"columnsFrom": [
"time_entry_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"time_entry_tags_tag_id_tags_id_fk": {
"name": "time_entry_tags_tag_id_tags_id_fk",
"tableFrom": "time_entry_tags",
"tableTo": "tags", "tableTo": "tags",
"columnsFrom": [ "columnsFrom": [
"tag_id" "tag_id"
@@ -942,15 +1140,7 @@
"onUpdate": "no action" "onUpdate": "no action"
} }
}, },
"compositePrimaryKeys": { "compositePrimaryKeys": {},
"time_entry_tags_time_entry_id_tag_id_pk": {
"columns": [
"time_entry_id",
"tag_id"
],
"name": "time_entry_tags_time_entry_id_tag_id_pk"
}
},
"uniqueConstraints": {}, "uniqueConstraints": {},
"checkConstraints": {} "checkConstraints": {}
}, },

View File

@@ -5,15 +5,15 @@
{ {
"idx": 0, "idx": 0,
"version": "6", "version": "6",
"when": 1768688193284, "when": 1768934194146,
"tag": "0000_motionless_king_cobra", "tag": "0000_lazy_rictor",
"breakpoints": true "breakpoints": true
}, },
{ {
"idx": 1, "idx": 1,
"version": "6", "version": "6",
"when": 1768690333269, "when": 1768935234392,
"tag": "0001_lazy_roughhouse", "tag": "0001_demonic_red_skull",
"breakpoints": true "breakpoints": true
} }
] ]

View File

@@ -1,7 +1,7 @@
{ {
"name": "chronus", "name": "chronus",
"type": "module", "type": "module",
"version": "2.0.0", "version": "2.3.0",
"scripts": { "scripts": {
"dev": "astro dev", "dev": "astro dev",
"build": "astro build", "build": "astro build",
@@ -12,23 +12,26 @@
"migrate": "node scripts/migrate.js" "migrate": "node scripts/migrate.js"
}, },
"dependencies": { "dependencies": {
"@astrojs/check": "^0.9.6", "@astrojs/check": "0.9.6",
"@astrojs/node": "^9.5.2", "@astrojs/node": "10.0.0-beta.0",
"@astrojs/vue": "^5.1.4", "@astrojs/vue": "6.0.0-beta.0",
"@ceereals/vue-pdf": "^0.2.1", "@ceereals/vue-pdf": "^0.2.1",
"@iconify/vue": "^5.0.0", "@iconify/vue": "^5.0.0",
"@libsql/client": "^0.17.0", "@libsql/client": "^0.17.0",
"@simplewebauthn/browser": "^13.2.2",
"@simplewebauthn/server": "^13.2.2",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
"astro": "^5.16.11", "astro": "6.0.0-beta.1",
"astro-icon": "^1.1.5", "astro-icon": "^1.1.5",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"chart.js": "^4.5.1", "chart.js": "^4.5.1",
"daisyui": "^5.5.14", "daisyui": "^5.5.14",
"dotenv": "^17.2.3",
"drizzle-orm": "0.45.1", "drizzle-orm": "0.45.1",
"nanoid": "^5.1.6", "nanoid": "^5.1.6",
"tailwindcss": "^4.1.18", "tailwindcss": "^4.1.18",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vue": "^3.5.26", "vue": "^3.5.27",
"vue-chartjs": "^5.3.3" "vue-chartjs": "^5.3.3"
}, },
"devDependencies": { "devDependencies": {

1247
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,64 +0,0 @@
<template>
<div style="position: relative; height: 100%; width: 100%;">
<Doughnut :data="chartData" :options="chartOptions" />
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { Doughnut } from 'vue-chartjs';
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
DoughnutController
} from 'chart.js';
ChartJS.register(ArcElement, Tooltip, Legend, DoughnutController);
interface CategoryData {
name: string;
totalTime: number;
color: string;
}
const props = defineProps<{
categories: CategoryData[];
}>();
const chartData = computed(() => ({
labels: props.categories.map(c => c.name),
datasets: [{
data: props.categories.map(c => c.totalTime),
backgroundColor: props.categories.map(c => c.color || '#3b82f6'),
borderWidth: 2,
borderColor: '#1e293b',
}]
}));
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom' as const,
labels: {
color: '#e2e8f0',
padding: 15,
font: { size: 12 }
}
},
tooltip: {
callbacks: {
label: function(context: any) {
const minutes = Math.round(context.raw / (1000 * 60));
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return ` ${context.label}: ${hours}h ${mins}m`;
}
}
}
}
};
</script>

View File

@@ -1,12 +1,12 @@
<template> <template>
<div style="position: relative; height: 100%; width: 100%;"> <div style="position: relative; height: 100%; width: 100%">
<Bar :data="chartData" :options="chartOptions" /> <Bar :data="chartData" :options="chartOptions" />
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from "vue";
import { Bar } from 'vue-chartjs'; import { Bar } from "vue-chartjs";
import { import {
Chart as ChartJS, Chart as ChartJS,
BarElement, BarElement,
@@ -14,10 +14,18 @@ import {
LinearScale, LinearScale,
Tooltip, Tooltip,
Legend, Legend,
BarController BarController,
} from 'chart.js'; type ChartOptions,
} from "chart.js";
ChartJS.register(BarElement, CategoryScale, LinearScale, Tooltip, Legend, BarController); ChartJS.register(
BarElement,
CategoryScale,
LinearScale,
Tooltip,
Legend,
BarController,
);
interface ClientData { interface ClientData {
name: string; name: string;
@@ -29,57 +37,61 @@ const props = defineProps<{
}>(); }>();
const chartData = computed(() => ({ const chartData = computed(() => ({
labels: props.clients.map(c => c.name), labels: props.clients.map((c) => c.name),
datasets: [{ datasets: [
label: 'Time Tracked', {
data: props.clients.map(c => c.totalTime / (1000 * 60)), // Convert to minutes label: "Time Tracked",
backgroundColor: '#6366f1', data: props.clients.map((c) => c.totalTime / (1000 * 60)), // Convert to minutes
borderColor: '#4f46e5', backgroundColor: "#6366f1",
borderWidth: 1, borderColor: "#4f46e5",
}] borderWidth: 1,
},
],
})); }));
const chartOptions = { const chartOptions: ChartOptions<"bar"> = {
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
scales: { scales: {
y: { y: {
beginAtZero: true, beginAtZero: true,
ticks: { ticks: {
color: '#e2e8f0', color: "#e2e8f0",
callback: function(value: number) { callback: function (value: string | number) {
const hours = Math.floor(value / 60); const numValue =
const mins = value % 60; typeof value === "string" ? parseFloat(value) : value;
const hours = Math.floor(numValue / 60);
const mins = Math.round(numValue % 60);
return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`; return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
} },
}, },
grid: { grid: {
color: '#334155' color: "#334155",
} },
}, },
x: { x: {
ticks: { ticks: {
color: '#e2e8f0' color: "#e2e8f0",
}, },
grid: { grid: {
display: false display: false,
} },
} },
}, },
plugins: { plugins: {
legend: { legend: {
display: false display: false,
}, },
tooltip: { tooltip: {
callbacks: { callbacks: {
label: function(context: any) { label: function (context) {
const minutes = Math.round(context.raw); const minutes = Math.round(context.raw as number);
const hours = Math.floor(minutes / 60); const hours = Math.floor(minutes / 60);
const mins = minutes % 60; const mins = minutes % 60;
return ` ${hours}h ${mins}m`; return ` ${hours}h ${mins}m`;
} },
} },
} },
} },
}; };
</script> </script>

View File

@@ -3,7 +3,6 @@ import { ref } from "vue";
const props = defineProps<{ const props = defineProps<{
clients: { id: string; name: string }[]; clients: { id: string; name: string }[];
categories: { id: string; name: string; color: string | null }[];
tags: { id: string; name: string; color: string | null }[]; tags: { id: string; name: string; color: string | null }[];
}>(); }>();
@@ -13,8 +12,7 @@ const emit = defineEmits<{
const description = ref(""); const description = ref("");
const selectedClientId = ref(""); const selectedClientId = ref("");
const selectedCategoryId = ref(""); const selectedTagId = ref<string | null>(null);
const selectedTags = ref<string[]>([]);
const startDate = ref(""); const startDate = ref("");
const startTime = ref(""); const startTime = ref("");
const endDate = ref(""); const endDate = ref("");
@@ -23,17 +21,15 @@ const isSubmitting = ref(false);
const error = ref(""); const error = ref("");
const success = ref(false); const success = ref(false);
// Set default dates to today
const today = new Date().toISOString().split("T")[0]; const today = new Date().toISOString().split("T")[0];
startDate.value = today; startDate.value = today;
endDate.value = today; endDate.value = today;
function toggleTag(tagId: string) { function toggleTag(tagId: string) {
const index = selectedTags.value.indexOf(tagId); if (selectedTagId.value === tagId) {
if (index > -1) { selectedTagId.value = null;
selectedTags.value.splice(index, 1);
} else { } else {
selectedTags.value.push(tagId); selectedTagId.value = tagId;
} }
} }
@@ -54,10 +50,6 @@ function validateForm(): string | null {
return "Please select a client"; return "Please select a client";
} }
if (!selectedCategoryId.value) {
return "Please select a category";
}
if (!startDate.value || !startTime.value) { if (!startDate.value || !startTime.value) {
return "Please enter start date and time"; return "Please enter start date and time";
} }
@@ -102,10 +94,9 @@ async function submitManualEntry() {
body: JSON.stringify({ body: JSON.stringify({
description: description.value, description: description.value,
clientId: selectedClientId.value, clientId: selectedClientId.value,
categoryId: selectedCategoryId.value,
startTime: startDateTime, startTime: startDateTime,
endTime: endDateTime, endTime: endDateTime,
tags: selectedTags.value, tagId: selectedTagId.value,
}), }),
}); });
@@ -114,22 +105,18 @@ async function submitManualEntry() {
if (res.ok) { if (res.ok) {
success.value = true; success.value = true;
// Calculate duration for success message
const start = new Date(startDateTime); const start = new Date(startDateTime);
const end = new Date(endDateTime); const end = new Date(endDateTime);
const duration = formatDuration(start, end); const duration = formatDuration(start, end);
// Reset form
description.value = ""; description.value = "";
selectedClientId.value = ""; selectedClientId.value = "";
selectedCategoryId.value = ""; selectedTagId.value = null;
selectedTags.value = [];
startDate.value = today; startDate.value = today;
endDate.value = today; endDate.value = today;
startTime.value = ""; startTime.value = "";
endTime.value = ""; endTime.value = "";
// Emit event and reload after a short delay
setTimeout(() => { setTimeout(() => {
emit("entryCreated"); emit("entryCreated");
window.location.reload(); window.location.reload();
@@ -148,8 +135,7 @@ async function submitManualEntry() {
function clearForm() { function clearForm() {
description.value = ""; description.value = "";
selectedClientId.value = ""; selectedClientId.value = "";
selectedCategoryId.value = ""; selectedTagId.value = null;
selectedTags.value = [];
startDate.value = today; startDate.value = today;
endDate.value = today; endDate.value = today;
startTime.value = ""; startTime.value = "";
@@ -212,59 +198,32 @@ function clearForm() {
<span>{{ error }}</span> <span>{{ error }}</span>
</div> </div>
<!-- Client and Category Row --> <!-- Client Row -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="form-control">
<div class="form-control"> <label class="label pb-2 font-medium" for="manual-client">
<label class="label pb-2"> Client <span class="label-text-alt text-error">*</span>
<span class="label-text font-medium">Client</span> </label>
<span class="label-text-alt text-error">*</span> <select
</label> id="manual-client"
<select v-model="selectedClientId"
v-model="selectedClientId" class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" :disabled="isSubmitting"
:disabled="isSubmitting" >
> <option value="">Select a client...</option>
<option value="">Select a client...</option> <option v-for="client in clients" :key="client.id" :value="client.id">
<option {{ client.name }}
v-for="client in clients" </option>
:key="client.id" </select>
:value="client.id"
>
{{ client.name }}
</option>
</select>
</div>
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium">Category</span>
<span class="label-text-alt text-error">*</span>
</label>
<select
v-model="selectedCategoryId"
class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
:disabled="isSubmitting"
>
<option value="">Select a category...</option>
<option
v-for="category in categories"
:key="category.id"
:value="category.id"
>
{{ category.name }}
</option>
</select>
</div>
</div> </div>
<!-- Start Date and Time --> <!-- Start Date and Time -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-start-date">
<span class="label-text font-medium">Start Date</span> Start Date <span class="label-text-alt text-error">*</span>
<span class="label-text-alt text-error">*</span>
</label> </label>
<input <input
id="manual-start-date"
v-model="startDate" v-model="startDate"
type="date" type="date"
class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
@@ -273,11 +232,11 @@ function clearForm() {
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-start-time">
<span class="label-text font-medium">Start Time</span> Start Time <span class="label-text-alt text-error">*</span>
<span class="label-text-alt text-error">*</span>
</label> </label>
<input <input
id="manual-start-time"
v-model="startTime" v-model="startTime"
type="time" type="time"
class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
@@ -289,11 +248,11 @@ function clearForm() {
<!-- End Date and Time --> <!-- End Date and Time -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-end-date">
<span class="label-text font-medium">End Date</span> End Date <span class="label-text-alt text-error">*</span>
<span class="label-text-alt text-error">*</span>
</label> </label>
<input <input
id="manual-end-date"
v-model="endDate" v-model="endDate"
type="date" type="date"
class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
@@ -302,11 +261,11 @@ function clearForm() {
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-end-time">
<span class="label-text font-medium">End Time</span> End Time <span class="label-text-alt text-error">*</span>
<span class="label-text-alt text-error">*</span>
</label> </label>
<input <input
id="manual-end-time"
v-model="endTime" v-model="endTime"
type="time" type="time"
class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" class="input input-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
@@ -317,10 +276,11 @@ function clearForm() {
<!-- Description Row --> <!-- Description Row -->
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-description">
<span class="label-text font-medium">Description</span> Description
</label> </label>
<input <input
id="manual-description"
v-model="description" v-model="description"
type="text" type="text"
placeholder="What did you work on?" placeholder="What did you work on?"
@@ -331,9 +291,7 @@ function clearForm() {
<!-- Tags Section --> <!-- Tags Section -->
<div v-if="tags.length > 0" class="form-control"> <div v-if="tags.length > 0" class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="manual-tags"> Tags </label>
<span class="label-text font-medium">Tags</span>
</label>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button <button
v-for="tag in tags" v-for="tag in tags"
@@ -341,7 +299,7 @@ function clearForm() {
@click="toggleTag(tag.id)" @click="toggleTag(tag.id)"
:class="[ :class="[
'badge badge-lg cursor-pointer transition-all hover:scale-105', 'badge badge-lg cursor-pointer transition-all hover:scale-105',
selectedTags.includes(tag.id) selectedTagId === tag.id
? 'badge-primary shadow-lg shadow-primary/20' ? 'badge-primary shadow-lg shadow-primary/20'
: 'badge-outline hover:bg-base-300/50', : 'badge-outline hover:bg-base-300/50',
]" ]"

View File

@@ -1,12 +1,12 @@
<template> <template>
<div style="position: relative; height: 100%; width: 100%;"> <div style="position: relative; height: 100%; width: 100%">
<Bar :data="chartData" :options="chartOptions" /> <Bar :data="chartData" :options="chartOptions" />
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from "vue";
import { Bar } from 'vue-chartjs'; import { Bar } from "vue-chartjs";
import { import {
Chart as ChartJS, Chart as ChartJS,
BarElement, BarElement,
@@ -14,10 +14,18 @@ import {
LinearScale, LinearScale,
Tooltip, Tooltip,
Legend, Legend,
BarController BarController,
} from 'chart.js'; type ChartOptions,
} from "chart.js";
ChartJS.register(BarElement, CategoryScale, LinearScale, Tooltip, Legend, BarController); ChartJS.register(
BarElement,
CategoryScale,
LinearScale,
Tooltip,
Legend,
BarController,
);
interface MemberData { interface MemberData {
name: string; name: string;
@@ -29,58 +37,62 @@ const props = defineProps<{
}>(); }>();
const chartData = computed(() => ({ const chartData = computed(() => ({
labels: props.members.map(m => m.name), labels: props.members.map((m) => m.name),
datasets: [{ datasets: [
label: 'Time Tracked', {
data: props.members.map(m => m.totalTime / (1000 * 60)), // Convert to minutes label: "Time Tracked",
backgroundColor: '#10b981', data: props.members.map((m) => m.totalTime / (1000 * 60)), // Convert to minutes
borderColor: '#059669', backgroundColor: "#10b981",
borderWidth: 1, borderColor: "#059669",
}] borderWidth: 1,
},
],
})); }));
const chartOptions = { const chartOptions: ChartOptions<"bar"> = {
indexAxis: 'y' as const, indexAxis: "y" as const,
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
scales: { scales: {
x: { x: {
beginAtZero: true, beginAtZero: true,
ticks: { ticks: {
color: '#e2e8f0', color: "#e2e8f0",
callback: function(value: number) { callback: function (value: string | number) {
const hours = Math.floor(value / 60); const numValue =
const mins = value % 60; typeof value === "string" ? parseFloat(value) : value;
const hours = Math.floor(numValue / 60);
const mins = Math.round(numValue % 60);
return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`; return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
} },
}, },
grid: { grid: {
color: '#334155' color: "#334155",
} },
}, },
y: { y: {
ticks: { ticks: {
color: '#e2e8f0' color: "#e2e8f0",
}, },
grid: { grid: {
display: false display: false,
} },
} },
}, },
plugins: { plugins: {
legend: { legend: {
display: false display: false,
}, },
tooltip: { tooltip: {
callbacks: { callbacks: {
label: function(context: any) { label: function (context) {
const minutes = Math.round(context.raw); const minutes = Math.round(context.raw as number);
const hours = Math.floor(minutes / 60); const hours = Math.floor(minutes / 60);
const mins = minutes % 60; const mins = minutes % 60;
return ` ${hours}h ${mins}m`; return ` ${hours}h ${mins}m`;
} },
} },
} },
} },
}; };
</script> </script>

View File

@@ -0,0 +1,67 @@
<template>
<div style="position: relative; height: 100%; width: 100%">
<Doughnut :data="chartData" :options="chartOptions" />
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { Doughnut } from "vue-chartjs";
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
type ChartOptions,
} from "chart.js";
ChartJS.register(ArcElement, Tooltip, Legend);
interface TagData {
name: string;
totalTime: number;
color: string;
}
const props = defineProps<{
tags: TagData[];
}>();
const chartData = computed(() => ({
labels: props.tags.map((t) => t.name),
datasets: [
{
data: props.tags.map((t) => t.totalTime / (1000 * 60)), // Convert to minutes
backgroundColor: props.tags.map((t) => t.color),
borderColor: "#1e293b", // Matches typical dark mode bg
borderWidth: 2,
},
],
}));
const chartOptions: ChartOptions<"doughnut"> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: "right",
labels: {
color: "#e2e8f0",
usePointStyle: true,
padding: 20,
},
},
tooltip: {
callbacks: {
label: function (context) {
const minutes = Math.round(context.raw as number);
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return ` ${hours}h ${mins}m`;
},
},
},
},
cutout: "70%",
};
</script>

View File

@@ -0,0 +1,34 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Icon } from '@iconify/vue';
const theme = ref('macchiato');
onMounted(() => {
const stored = localStorage.getItem('theme');
if (stored) {
theme.value = stored;
document.documentElement.setAttribute('data-theme', stored);
}
});
function toggleTheme() {
const newTheme = theme.value === 'macchiato' ? 'latte' : 'macchiato';
theme.value = newTheme;
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
</script>
<template>
<button
@click="toggleTheme"
class="btn btn-ghost btn-circle"
aria-label="Toggle Theme"
>
<Icon
:icon="theme === 'macchiato' ? 'heroicons:moon' : 'heroicons:sun'"
class="w-5 h-5"
/>
</button>
</template>

View File

@@ -7,10 +7,9 @@ const props = defineProps<{
startTime: number; startTime: number;
description: string | null; description: string | null;
clientId: string; clientId: string;
categoryId: string; tagId?: string;
} | null; } | null;
clients: { id: string; name: string }[]; clients: { id: string; name: string }[];
categories: { id: string; name: string; color: string | null }[];
tags: { id: string; name: string; color: string | null }[]; tags: { id: string; name: string; color: string | null }[];
}>(); }>();
@@ -19,8 +18,7 @@ const startTime = ref<number | null>(null);
const elapsedTime = ref(0); const elapsedTime = ref(0);
const description = ref(""); const description = ref("");
const selectedClientId = ref(""); const selectedClientId = ref("");
const selectedCategoryId = ref(""); const selectedTagId = ref<string | null>(null);
const selectedTags = ref<string[]>([]);
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
function formatTime(ms: number) { function formatTime(ms: number) {
@@ -31,7 +29,6 @@ function formatTime(ms: number) {
const timeStr = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`; const timeStr = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
// Calculate rounded version
const totalMinutes = Math.round(ms / 1000 / 60); const totalMinutes = Math.round(ms / 1000 / 60);
const roundedHours = Math.floor(totalMinutes / 60); const roundedHours = Math.floor(totalMinutes / 60);
const roundedMinutes = totalMinutes % 60; const roundedMinutes = totalMinutes % 60;
@@ -50,11 +47,10 @@ function formatTime(ms: number) {
} }
function toggleTag(tagId: string) { function toggleTag(tagId: string) {
const index = selectedTags.value.indexOf(tagId); if (selectedTagId.value === tagId) {
if (index > -1) { selectedTagId.value = null;
selectedTags.value.splice(index, 1);
} else { } else {
selectedTags.value.push(tagId); selectedTagId.value = tagId;
} }
} }
@@ -64,7 +60,7 @@ onMounted(() => {
startTime.value = props.initialRunningEntry.startTime; startTime.value = props.initialRunningEntry.startTime;
description.value = props.initialRunningEntry.description || ""; description.value = props.initialRunningEntry.description || "";
selectedClientId.value = props.initialRunningEntry.clientId; selectedClientId.value = props.initialRunningEntry.clientId;
selectedCategoryId.value = props.initialRunningEntry.categoryId; selectedTagId.value = props.initialRunningEntry.tagId || null;
elapsedTime.value = Date.now() - startTime.value; elapsedTime.value = Date.now() - startTime.value;
interval = setInterval(() => { interval = setInterval(() => {
elapsedTime.value = Date.now() - startTime.value!; elapsedTime.value = Date.now() - startTime.value!;
@@ -82,19 +78,13 @@ async function startTimer() {
return; return;
} }
if (!selectedCategoryId.value) {
alert("Please select a category");
return;
}
const res = await fetch("/api/time-entries/start", { const res = await fetch("/api/time-entries/start", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
description: description.value, description: description.value,
clientId: selectedClientId.value, clientId: selectedClientId.value,
categoryId: selectedCategoryId.value, tagId: selectedTagId.value,
tags: selectedTags.value,
}), }),
}); });
@@ -120,8 +110,7 @@ async function stopTimer() {
startTime.value = null; startTime.value = null;
description.value = ""; description.value = "";
selectedClientId.value = ""; selectedClientId.value = "";
selectedCategoryId.value = ""; selectedTagId.value = null;
selectedTags.value = [];
window.location.reload(); window.location.reload();
} }
} }
@@ -132,55 +121,31 @@ async function stopTimer() {
class="card bg-base-200/50 backdrop-blur-sm shadow-lg border border-base-300/50 mb-6 hover:border-base-300 transition-all duration-200" class="card bg-base-200/50 backdrop-blur-sm shadow-lg border border-base-300/50 mb-6 hover:border-base-300 transition-all duration-200"
> >
<div class="card-body gap-6"> <div class="card-body gap-6">
<!-- Client and Description Row --> <!-- Client Row -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="form-control">
<div class="form-control"> <label class="label pb-2 font-medium" for="timer-client">
<label class="label pb-2"> Client
<span class="label-text font-medium">Client</span> </label>
</label> <select
<select id="timer-client"
v-model="selectedClientId" v-model="selectedClientId"
class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors" class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
:disabled="isRunning" :disabled="isRunning"
> >
<option value="">Select a client...</option> <option value="">Select a client...</option>
<option <option v-for="client in clients" :key="client.id" :value="client.id">
v-for="client in clients" {{ client.name }}
:key="client.id" </option>
:value="client.id" </select>
>
{{ client.name }}
</option>
</select>
</div>
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium">Category</span>
</label>
<select
v-model="selectedCategoryId"
class="select select-bordered w-full bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors"
:disabled="isRunning"
>
<option value="">Select a category...</option>
<option
v-for="category in categories"
:key="category.id"
:value="category.id"
>
{{ category.name }}
</option>
</select>
</div>
</div> </div>
<!-- Description Row --> <!-- Description Row -->
<div class="form-control"> <div class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="timer-description">
<span class="label-text font-medium">Description</span> Description
</label> </label>
<input <input
id="timer-description"
v-model="description" v-model="description"
type="text" type="text"
placeholder="What are you working on?" placeholder="What are you working on?"
@@ -191,9 +156,7 @@ async function stopTimer() {
<!-- Tags Section --> <!-- Tags Section -->
<div v-if="tags.length > 0" class="form-control"> <div v-if="tags.length > 0" class="form-control">
<label class="label pb-2"> <label class="label pb-2 font-medium" for="timer-tags"> Tags </label>
<span class="label-text font-medium">Tags</span>
</label>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button <button
v-for="tag in tags" v-for="tag in tags"
@@ -201,7 +164,7 @@ async function stopTimer() {
@click="toggleTag(tag.id)" @click="toggleTag(tag.id)"
:class="[ :class="[
'badge badge-lg cursor-pointer transition-all hover:scale-105', 'badge badge-lg cursor-pointer transition-all hover:scale-105',
selectedTags.includes(tag.id) selectedTagId === tag.id
? 'badge-primary shadow-lg shadow-primary/20' ? 'badge-primary shadow-lg shadow-primary/20'
: 'badge-outline hover:bg-base-300/50', : 'badge-outline hover:bg-base-300/50',
]" ]"

View File

@@ -0,0 +1,72 @@
<script setup lang="ts">
import { ref } from "vue";
import { Icon } from "@iconify/vue";
import { startAuthentication } from "@simplewebauthn/browser";
const loading = ref(false);
const error = ref<string | null>(null);
async function handlePasskeyLogin() {
loading.value = true;
error.value = null;
try {
const resp = await fetch("/api/auth/passkey/login/start");
if (!resp.ok) {
throw new Error("Failed to start passkey login");
}
const options = await resp.json();
let asseResp;
try {
asseResp = await startAuthentication({ optionsJSON: options });
} catch (err) {
if ((err as any).name === "NotAllowedError") {
return;
}
console.error(err);
error.value = "Failed to authenticate with passkey";
return;
}
const verificationResp = await fetch("/api/auth/passkey/login/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(asseResp),
});
const verificationJSON = await verificationResp.json();
if (verificationJSON.verified) {
window.location.href = "/dashboard";
} else {
error.value = "Login failed. Please try again.";
}
} catch (err) {
console.error("Error during passkey login:", err);
error.value = "An error occurred during login";
} finally {
loading.value = false;
}
}
</script>
<template>
<div>
<button
class="btn btn-secondary w-full"
@click="handlePasskeyLogin"
:disabled="loading"
>
<span v-if="loading" class="loading loading-spinner loading-sm"></span>
<Icon v-else icon="heroicons:finger-print" class="w-5 h-5 mr-2" />
Sign in with Passkey
</button>
<div v-if="error" role="alert" class="alert alert-error mt-4">
<Icon icon="heroicons:exclamation-circle" class="w-6 h-6" />
<span>{{ error }}</span>
</div>
</div>
</template>

View File

@@ -0,0 +1,257 @@
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { Icon } from "@iconify/vue";
interface ApiToken {
id: string;
name: string;
lastUsedAt: string | null;
createdAt: string;
}
const props = defineProps<{
initialTokens: ApiToken[];
}>();
const tokens = ref<ApiToken[]>(props.initialTokens);
const createModalOpen = ref(false);
const showTokenModalOpen = ref(false);
const newTokenName = ref("");
const newTokenValue = ref("");
const loading = ref(false);
const isMounted = ref(false);
onMounted(() => {
isMounted.value = true;
});
function formatDate(dateString: string | null) {
if (!dateString) return "Never";
return new Date(dateString).toLocaleDateString();
}
async function createToken() {
if (!newTokenName.value) return;
loading.value = true;
try {
const response = await fetch("/api/user/tokens", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: newTokenName.value }),
});
if (response.ok) {
const data = await response.json();
const { token, ...tokenMeta } = data;
tokens.value.unshift({
id: tokenMeta.id,
name: tokenMeta.name,
lastUsedAt: tokenMeta.lastUsedAt,
createdAt: tokenMeta.createdAt,
});
newTokenValue.value = token;
createModalOpen.value = false;
showTokenModalOpen.value = true;
newTokenName.value = "";
} else {
alert("Failed to create token");
}
} catch (error) {
console.error("Error creating token:", error);
alert("An error occurred");
} finally {
loading.value = false;
}
}
async function deleteToken(id: string) {
if (
!confirm(
"Are you sure you want to revoke this token? Any applications using it will stop working.",
)
) {
return;
}
try {
const response = await fetch(`/api/user/tokens/${id}`, {
method: "DELETE",
});
if (response.ok) {
tokens.value = tokens.value.filter((t) => t.id !== id);
} else {
alert("Failed to delete token");
}
} catch (error) {
console.error("Error deleting token:", error);
alert("An error occurred");
}
}
function copyToken() {
navigator.clipboard.writeText(newTokenValue.value);
}
function closeShowTokenModal() {
showTokenModalOpen.value = false;
newTokenValue.value = "";
}
</script>
<template>
<div>
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body p-4 sm:p-6">
<div class="flex justify-between items-center mb-6">
<h2 class="card-title text-lg sm:text-xl">
<Icon
icon="heroicons:code-bracket-square"
class="w-5 h-5 sm:w-6 sm:h-6"
/>
API Tokens
</h2>
<button
class="btn btn-primary btn-sm"
@click="createModalOpen = true"
>
<Icon icon="heroicons:plus" class="w-4 h-4" />
Create Token
</button>
</div>
<div class="overflow-x-auto">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Last Used</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-if="tokens.length === 0">
<td colspan="4" class="text-center text-base-content/60 py-4">
No API tokens found. Create one to access the API.
</td>
</tr>
<tr v-else v-for="token in tokens" :key="token.id">
<td class="font-medium">{{ token.name }}</td>
<td class="text-sm">
<span v-if="isMounted">{{
formatDate(token.lastUsedAt)
}}</span>
<span v-else>{{ token.lastUsedAt || "Never" }}</span>
</td>
<td class="text-sm">
<span v-if="isMounted">{{
formatDate(token.createdAt)
}}</span>
<span v-else>{{ token.createdAt }}</span>
</td>
<td>
<button
class="btn btn-ghost btn-xs text-error"
@click="deleteToken(token.id)"
>
<Icon icon="heroicons:trash" class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Create Token Modal -->
<dialog class="modal" :class="{ 'modal-open': createModalOpen }">
<div class="modal-box">
<h3 class="font-bold text-lg">Create API Token</h3>
<p class="py-4 text-sm text-base-content/70">
API tokens allow you to authenticate with the API programmatically.
Give your token a descriptive name.
</p>
<form @submit.prevent="createToken" class="space-y-4">
<div class="form-control">
<label class="label pb-2 font-medium" for="token-name">
Token Name
</label>
<input
type="text"
id="token-name"
v-model="newTokenName"
placeholder="e.g. CI/CD Pipeline"
class="input input-bordered w-full"
required
/>
</div>
<div class="modal-action">
<button type="button" class="btn" @click="createModalOpen = false">
Cancel
</button>
<button type="submit" class="btn btn-primary" :disabled="loading">
<span
v-if="loading"
class="loading loading-spinner loading-sm"
></span>
Generate Token
</button>
</div>
</form>
</div>
<form
method="dialog"
class="modal-backdrop"
@click="createModalOpen = false"
>
<button>close</button>
</form>
</dialog>
<!-- Show Token Modal -->
<dialog class="modal" :class="{ 'modal-open': showTokenModalOpen }">
<div class="modal-box">
<h3 class="font-bold text-lg text-success flex items-center gap-2">
<Icon icon="heroicons:check-circle" class="w-6 h-6" />
Token Created
</h3>
<p class="py-4">
Make sure to copy your personal access token now. You won't be able to
see it again!
</p>
<div
class="bg-base-200 p-4 rounded-lg break-all font-mono text-sm relative group"
>
<span>{{ newTokenValue }}</span>
<button
class="absolute top-2 right-2 btn btn-xs btn-ghost opacity-0 group-hover:opacity-100 transition-opacity"
@click="copyToken"
title="Copy to clipboard"
>
<Icon icon="heroicons:clipboard" class="w-4 h-4" />
</button>
</div>
<div class="modal-action">
<button class="btn btn-primary" @click="closeShowTokenModal">
Done
</button>
</div>
</div>
<form method="dialog" class="modal-backdrop" @click="closeShowTokenModal">
<button>close</button>
</form>
</dialog>
</div>
</template>

View File

@@ -0,0 +1,169 @@
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { Icon } from "@iconify/vue";
import { startRegistration } from "@simplewebauthn/browser";
interface Passkey {
id: string;
deviceType: string;
backedUp: boolean;
lastUsedAt: string | null;
createdAt: string | null;
}
const props = defineProps<{
initialPasskeys: Passkey[];
}>();
const passkeys = ref<Passkey[]>(props.initialPasskeys);
const loading = ref(false);
const isMounted = ref(false);
onMounted(() => {
isMounted.value = true;
});
function formatDate(dateString: string | null) {
if (!dateString) return "N/A";
return new Date(dateString).toLocaleDateString();
}
async function registerPasskey() {
loading.value = true;
try {
const resp = await fetch("/api/auth/passkey/register/start");
if (!resp.ok) {
throw new Error("Failed to start registration");
}
const options = await resp.json();
let attResp;
try {
attResp = await startRegistration({ optionsJSON: options });
} catch (error) {
if ((error as any).name === "NotAllowedError") {
return;
}
console.error(error);
alert("Failed to register passkey: " + (error as any).message);
return;
}
const verificationResp = await fetch("/api/auth/passkey/register/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(attResp),
});
const verificationJSON = await verificationResp.json();
if (verificationJSON.verified) {
window.location.reload();
} else {
alert("Passkey registration failed");
}
} catch (error) {
console.error("Error registering passkey:", error);
alert("An error occurred");
} finally {
loading.value = false;
}
}
async function deletePasskey(id: string) {
if (!confirm("Are you sure you want to remove this passkey?")) {
return;
}
try {
const response = await fetch(`/api/auth/passkey/delete?id=${id}`, {
method: "DELETE",
});
if (response.ok) {
passkeys.value = passkeys.value.filter((pk) => pk.id !== id);
} else {
alert("Failed to delete passkey");
}
} catch (error) {
console.error("Error deleting passkey:", error);
alert("An error occurred");
}
}
</script>
<template>
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body p-4 sm:p-6">
<div class="flex justify-between items-center mb-6">
<h2 class="card-title text-lg sm:text-xl">
<Icon icon="heroicons:finger-print" class="w-5 h-5 sm:w-6 sm:h-6" />
Passkeys
</h2>
<button
class="btn btn-primary btn-sm"
@click="registerPasskey"
:disabled="loading"
>
<span
v-if="loading"
class="loading loading-spinner loading-xs"
></span>
<Icon v-else icon="heroicons:plus" class="w-4 h-4" />
Add Passkey
</button>
</div>
<div class="overflow-x-auto">
<table class="table">
<thead>
<tr>
<th>Device Type</th>
<th>Last Used</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-if="passkeys.length === 0">
<td colspan="4" class="text-center text-base-content/60 py-4">
No passkeys found. Add one to sign in without a password.
</td>
</tr>
<tr v-else v-for="pk in passkeys" :key="pk.id">
<td class="font-medium">
{{
pk.deviceType === "singleDevice"
? "This Device"
: "Cross-Platform (Phone/Key)"
}}
<span v-if="pk.backedUp" class="badge badge-xs badge-info ml-2"
>Backed Up</span
>
</td>
<td class="text-sm">
<span v-if="isMounted">
{{ pk.lastUsedAt ? formatDate(pk.lastUsedAt) : "Never" }}
</span>
<span v-else>{{ pk.lastUsedAt || "Never" }}</span>
</td>
<td class="text-sm">
<span v-if="isMounted">{{ formatDate(pk.createdAt) }}</span>
<span v-else>{{ pk.createdAt || "N/A" }}</span>
</td>
<td>
<button
class="btn btn-ghost btn-xs text-error"
@click="deletePasskey(pk.id)"
>
<Icon icon="heroicons:trash" class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,174 @@
<script setup lang="ts">
import { ref } from "vue";
import { Icon } from "@iconify/vue";
const currentPassword = ref("");
const newPassword = ref("");
const confirmPassword = ref("");
const loading = ref(false);
const message = ref<{ type: "success" | "error"; text: string } | null>(null);
async function changePassword() {
if (newPassword.value !== confirmPassword.value) {
message.value = { type: "error", text: "New passwords do not match" };
return;
}
if (newPassword.value.length < 8) {
message.value = {
type: "error",
text: "Password must be at least 8 characters",
};
return;
}
loading.value = true;
message.value = null;
try {
const response = await fetch("/api/user/change-password", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
currentPassword: currentPassword.value,
newPassword: newPassword.value,
confirmPassword: confirmPassword.value,
}),
});
if (response.ok) {
message.value = {
type: "success",
text: "Password changed successfully!",
};
currentPassword.value = "";
newPassword.value = "";
confirmPassword.value = "";
setTimeout(() => {
message.value = null;
}, 3000);
} else {
const data = await response.json().catch(() => ({}));
message.value = {
type: "error",
text: data.error || "Failed to change password",
};
}
} catch (error) {
message.value = { type: "error", text: "An error occurred" };
} finally {
loading.value = false;
}
}
</script>
<template>
<div>
<!-- Success/Error Message Display -->
<div
v-if="message"
:class="[
'alert mb-6',
message.type === 'success' ? 'alert-success' : 'alert-error',
]"
>
<Icon
:icon="
message.type === 'success'
? 'heroicons:check-circle'
: 'heroicons:exclamation-circle'
"
class="w-6 h-6 shrink-0"
/>
<span>{{ message.text }}</span>
</div>
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body p-4 sm:p-6">
<h2 class="card-title mb-6 text-lg sm:text-xl">
<Icon icon="heroicons:key" class="w-5 h-5 sm:w-6 sm:h-6" />
Change Password
</h2>
<form @submit.prevent="changePassword" class="space-y-5">
<div class="form-control">
<label
class="label pb-2 font-medium text-sm sm:text-base"
for="current-password"
>
Current Password
</label>
<input
type="password"
id="current-password"
v-model="currentPassword"
placeholder="Enter current password"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label
class="label pb-2 font-medium text-sm sm:text-base"
for="new-password"
>
New Password
</label>
<input
type="password"
id="new-password"
v-model="newPassword"
placeholder="Enter new password"
class="input input-bordered w-full"
required
minlength="8"
/>
<div class="label pt-2">
<span
class="label-text-alt text-base-content/60 text-xs sm:text-sm"
>Minimum 8 characters</span
>
</div>
</div>
<div class="form-control">
<label
class="label pb-2 font-medium text-sm sm:text-base"
for="confirm-password"
>
Confirm New Password
</label>
<input
type="password"
id="confirm-password"
v-model="confirmPassword"
placeholder="Confirm new password"
class="input input-bordered w-full"
required
minlength="8"
/>
</div>
<div class="flex justify-end pt-4">
<button
type="submit"
class="btn btn-primary w-full sm:w-auto"
:disabled="loading"
>
<span
v-if="loading"
class="loading loading-spinner loading-sm"
></span>
<Icon v-else icon="heroicons:lock-closed" class="w-5 h-5" />
Update Password
</button>
</div>
</form>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,139 @@
<script setup lang="ts">
import { ref } from "vue";
import { Icon } from "@iconify/vue";
const props = defineProps<{
user: {
id: string;
name: string;
email: string;
};
}>();
const name = ref(props.user.name);
const loading = ref(false);
const message = ref<{ type: "success" | "error"; text: string } | null>(null);
async function updateProfile() {
loading.value = true;
message.value = null;
try {
const response = await fetch("/api/user/update-profile", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: name.value }),
});
if (response.ok) {
message.value = {
type: "success",
text: "Profile updated successfully!",
};
setTimeout(() => {
message.value = null;
}, 3000);
} else {
const data = await response.json().catch(() => ({}));
message.value = {
type: "error",
text: data.error || "Failed to update profile",
};
}
} catch (error) {
message.value = { type: "error", text: "An error occurred" };
} finally {
loading.value = false;
}
}
</script>
<template>
<div>
<!-- Success/Error Message Display -->
<div
v-if="message"
:class="[
'alert mb-6',
message.type === 'success' ? 'alert-success' : 'alert-error',
]"
>
<Icon
:icon="
message.type === 'success'
? 'heroicons:check-circle'
: 'heroicons:exclamation-circle'
"
class="w-6 h-6 shrink-0"
/>
<span>{{ message.text }}</span>
</div>
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body p-4 sm:p-6">
<h2 class="card-title mb-6 text-lg sm:text-xl">
<Icon icon="heroicons:user-circle" class="w-5 h-5 sm:w-6 sm:h-6" />
Profile Information
</h2>
<form @submit.prevent="updateProfile" class="space-y-5">
<div class="form-control">
<label
class="label pb-2 font-medium text-sm sm:text-base"
for="profile-name"
>
Full Name
</label>
<input
type="text"
id="profile-name"
v-model="name"
placeholder="Your full name"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label
class="label pb-2 font-medium text-sm sm:text-base"
for="profile-email"
>
Email
</label>
<input
type="email"
id="profile-email"
:value="props.user.email"
class="input input-bordered w-full"
disabled
/>
<div class="label pt-2">
<span
class="label-text-alt text-base-content/60 text-xs sm:text-sm"
>Email cannot be changed</span
>
</div>
</div>
<div class="flex justify-end pt-4">
<button
type="submit"
class="btn btn-primary w-full sm:w-auto"
:disabled="loading"
>
<span
v-if="loading"
class="loading loading-spinner loading-sm"
></span>
<Icon v-else icon="heroicons:check" class="w-5 h-5" />
Save Changes
</button>
</div>
</form>
</div>
</div>
</div>
</template>

View File

@@ -4,7 +4,6 @@ import * as schema from "./schema";
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs";
// Define the database type based on the schema
type Database = ReturnType<typeof drizzle<typeof schema>>; type Database = ReturnType<typeof drizzle<typeof schema>>;
let _db: Database | null = null; let _db: Database | null = null;

View File

@@ -33,6 +33,8 @@ export const organizations = sqliteTable("organizations", {
state: text("state"), state: text("state"),
zip: text("zip"), zip: text("zip"),
country: text("country"), country: text("country"),
defaultTaxRate: real("default_tax_rate").default(0),
defaultCurrency: text("default_currency").default("USD"),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn( createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(), () => new Date(),
), ),
@@ -95,8 +97,8 @@ export const clients = sqliteTable(
}), }),
); );
export const categories = sqliteTable( export const tags = sqliteTable(
"categories", "tags",
{ {
id: text("id") id: text("id")
.primaryKey() .primaryKey()
@@ -104,6 +106,7 @@ export const categories = sqliteTable(
organizationId: text("organization_id").notNull(), organizationId: text("organization_id").notNull(),
name: text("name").notNull(), name: text("name").notNull(),
color: text("color"), color: text("color"),
rate: integer("rate").default(0),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn( createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(), () => new Date(),
), ),
@@ -113,7 +116,7 @@ export const categories = sqliteTable(
columns: [table.organizationId], columns: [table.organizationId],
foreignColumns: [organizations.id], foreignColumns: [organizations.id],
}), }),
organizationIdIdx: index("categories_organization_id_idx").on( organizationIdIdx: index("tags_organization_id_idx").on(
table.organizationId, table.organizationId,
), ),
}), }),
@@ -128,10 +131,11 @@ export const timeEntries = sqliteTable(
userId: text("user_id").notNull(), userId: text("user_id").notNull(),
organizationId: text("organization_id").notNull(), organizationId: text("organization_id").notNull(),
clientId: text("client_id").notNull(), clientId: text("client_id").notNull(),
categoryId: text("category_id").notNull(), tagId: text("tag_id"),
startTime: integer("start_time", { mode: "timestamp" }).notNull(), startTime: integer("start_time", { mode: "timestamp" }).notNull(),
endTime: integer("end_time", { mode: "timestamp" }), endTime: integer("end_time", { mode: "timestamp" }),
description: text("description"), description: text("description"),
invoiceId: text("invoice_id"),
isManual: integer("is_manual", { mode: "boolean" }).default(false), isManual: integer("is_manual", { mode: "boolean" }).default(false),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn( createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(), () => new Date(),
@@ -150,63 +154,18 @@ export const timeEntries = sqliteTable(
columns: [table.clientId], columns: [table.clientId],
foreignColumns: [clients.id], foreignColumns: [clients.id],
}), }),
categoryFk: foreignKey({ tagFk: foreignKey({
columns: [table.categoryId], columns: [table.tagId],
foreignColumns: [categories.id], foreignColumns: [tags.id],
}), }),
userIdIdx: index("time_entries_user_id_idx").on(table.userId), userIdIdx: index("time_entries_user_id_idx").on(table.userId),
organizationIdIdx: index("time_entries_organization_id_idx").on( organizationIdIdx: index("time_entries_organization_id_idx").on(
table.organizationId, table.organizationId,
), ),
clientIdIdx: index("time_entries_client_id_idx").on(table.clientId), clientIdIdx: index("time_entries_client_id_idx").on(table.clientId),
tagIdIdx: index("time_entries_tag_id_idx").on(table.tagId),
startTimeIdx: index("time_entries_start_time_idx").on(table.startTime), startTimeIdx: index("time_entries_start_time_idx").on(table.startTime),
}), invoiceIdIdx: index("time_entries_invoice_id_idx").on(table.invoiceId),
);
export const tags = sqliteTable(
"tags",
{
id: text("id")
.primaryKey()
.$defaultFn(() => nanoid()),
organizationId: text("organization_id").notNull(),
name: text("name").notNull(),
color: text("color"),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(),
),
},
(table: any) => ({
orgFk: foreignKey({
columns: [table.organizationId],
foreignColumns: [organizations.id],
}),
organizationIdIdx: index("tags_organization_id_idx").on(
table.organizationId,
),
}),
);
export const timeEntryTags = sqliteTable(
"time_entry_tags",
{
timeEntryId: text("time_entry_id").notNull(),
tagId: text("tag_id").notNull(),
},
(table: any) => ({
pk: primaryKey({ columns: [table.timeEntryId, table.tagId] }),
timeEntryFk: foreignKey({
columns: [table.timeEntryId],
foreignColumns: [timeEntries.id],
}),
tagFk: foreignKey({
columns: [table.tagId],
foreignColumns: [tags.id],
}),
timeEntryIdIdx: index("time_entry_tags_time_entry_id_idx").on(
table.timeEntryId,
),
tagIdIdx: index("time_entry_tags_tag_id_idx").on(table.tagId),
}), }),
); );
@@ -270,16 +229,19 @@ export const invoices = sqliteTable(
organizationId: text("organization_id").notNull(), organizationId: text("organization_id").notNull(),
clientId: text("client_id").notNull(), clientId: text("client_id").notNull(),
number: text("number").notNull(), number: text("number").notNull(),
type: text("type").notNull().default("invoice"), // 'invoice' or 'quote' type: text("type").notNull().default("invoice"),
status: text("status").notNull().default("draft"), // 'draft', 'sent', 'paid', 'void', 'accepted', 'declined' status: text("status").notNull().default("draft"),
issueDate: integer("issue_date", { mode: "timestamp" }).notNull(), issueDate: integer("issue_date", { mode: "timestamp" }).notNull(),
dueDate: integer("due_date", { mode: "timestamp" }).notNull(), dueDate: integer("due_date", { mode: "timestamp" }).notNull(),
notes: text("notes"), notes: text("notes"),
currency: text("currency").default("USD").notNull(), currency: text("currency").default("USD").notNull(),
subtotal: integer("subtotal").notNull().default(0), // in cents subtotal: integer("subtotal").notNull().default(0),
taxRate: real("tax_rate").default(0), // percentage discountValue: real("discount_value").default(0),
taxAmount: integer("tax_amount").notNull().default(0), // in cents discountType: text("discount_type").default("percentage"),
total: integer("total").notNull().default(0), // in cents discountAmount: integer("discount_amount").default(0),
taxRate: real("tax_rate").default(0),
taxAmount: integer("tax_amount").notNull().default(0),
total: integer("total").notNull().default(0),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn( createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(), () => new Date(),
), ),
@@ -309,8 +271,8 @@ export const invoiceItems = sqliteTable(
invoiceId: text("invoice_id").notNull(), invoiceId: text("invoice_id").notNull(),
description: text("description").notNull(), description: text("description").notNull(),
quantity: real("quantity").notNull().default(1), quantity: real("quantity").notNull().default(1),
unitPrice: integer("unit_price").notNull().default(0), // in cents unitPrice: integer("unit_price").notNull().default(0),
amount: integer("amount").notNull().default(0), // in cents amount: integer("amount").notNull().default(0),
}, },
(table: any) => ({ (table: any) => ({
invoiceFk: foreignKey({ invoiceFk: foreignKey({
@@ -320,3 +282,36 @@ export const invoiceItems = sqliteTable(
invoiceIdIdx: index("invoice_items_invoice_id_idx").on(table.invoiceId), invoiceIdIdx: index("invoice_items_invoice_id_idx").on(table.invoiceId),
}), }),
); );
export const passkeys = sqliteTable(
"passkeys",
{
id: text("id").primaryKey(),
userId: text("user_id").notNull(),
publicKey: text("public_key").notNull(),
counter: integer("counter").notNull(),
deviceType: text("device_type").notNull(),
backedUp: integer("backed_up", { mode: "boolean" }).notNull(),
transports: text("transports"),
lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(
() => new Date(),
),
},
(table: any) => ({
userFk: foreignKey({
columns: [table.userId],
foreignColumns: [users.id],
}),
userIdIdx: index("passkeys_user_id_idx").on(table.userId),
}),
);
export const passkeyChallenges = sqliteTable("passkey_challenges", {
id: text("id")
.primaryKey()
.$defaultFn(() => nanoid()),
challenge: text("challenge").notNull().unique(),
userId: text("user_id"),
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
});

View File

@@ -5,6 +5,7 @@ import { db } from '../db';
import { members, organizations } from '../db/schema'; import { members, organizations } from '../db/schema';
import { eq } from 'drizzle-orm'; import { eq } from 'drizzle-orm';
import Avatar from '../components/Avatar.astro'; import Avatar from '../components/Avatar.astro';
import ThemeToggle from '../components/ThemeToggle.vue';
import { ClientRouter } from "astro:transitions"; import { ClientRouter } from "astro:transitions";
interface Props { interface Props {
@@ -18,7 +19,6 @@ if (!user) {
return Astro.redirect('/login'); return Astro.redirect('/login');
} }
// Get user's team memberships
const userMemberships = await db.select({ const userMemberships = await db.select({
membership: members, membership: members,
organization: organizations, organization: organizations,
@@ -28,13 +28,12 @@ const userMemberships = await db.select({
.where(eq(members.userId, user.id)) .where(eq(members.userId, user.id))
.all(); .all();
// Get current team from cookie or use first membership
const currentTeamId = Astro.cookies.get('currentTeamId')?.value || userMemberships[0]?.organization.id; const currentTeamId = Astro.cookies.get('currentTeamId')?.value || userMemberships[0]?.organization.id;
const currentTeam = userMemberships.find(m => m.organization.id === currentTeamId); const currentTeam = userMemberships.find(m => m.organization.id === currentTeamId);
--- ---
<!doctype html> <!doctype html>
<html lang="en" data-theme="dark"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="description" content="Chronus Dashboard" /> <meta name="description" content="Chronus Dashboard" />
@@ -43,6 +42,10 @@ const currentTeam = userMemberships.find(m => m.organization.id === currentTeamI
<meta name="generator" content={Astro.generator} /> <meta name="generator" content={Astro.generator} />
<title>{title}</title> <title>{title}</title>
<ClientRouter /> <ClientRouter />
<script is:inline>
const theme = localStorage.getItem('theme') || 'macchiato';
document.documentElement.setAttribute('data-theme', theme);
</script>
</head> </head>
<body class="bg-base-100 h-screen flex flex-col overflow-hidden"> <body class="bg-base-100 h-screen flex flex-col overflow-hidden">
<div class="drawer lg:drawer-open flex-1 overflow-auto"> <div class="drawer lg:drawer-open flex-1 overflow-auto">
@@ -59,6 +62,9 @@ const currentTeam = userMemberships.find(m => m.organization.id === currentTeamI
<img src="/logo.webp" alt="Chronus" class="h-8 w-8" /> <img src="/logo.webp" alt="Chronus" class="h-8 w-8" />
<span class="text-xl font-bold text-primary">Chronus</span> <span class="text-xl font-bold text-primary">Chronus</span>
</div> </div>
<div class="flex-none">
<ThemeToggle client:load />
</div>
</div> </div>
<!-- Page content here --> <!-- Page content here -->
@@ -179,6 +185,13 @@ const currentTeam = userMemberships.find(m => m.organization.id === currentTeamI
</a> </a>
</li> </li>
<li>
<div class="flex justify-between items-center p-2 hover:bg-transparent">
<span class="font-semibold text-sm text-base-content/70 pl-2">Theme</span>
<ThemeToggle client:load />
</div>
</li>
<li> <li>
<form action="/api/auth/logout" method="POST" class="contents"> <form action="/api/auth/logout" method="POST" class="contents">
<button type="submit" class="flex w-full items-center gap-2 py-2 px-4 text-error hover:bg-error/10 rounded-lg transition-colors active:bg-base-300/50!"> <button type="submit" class="flex w-full items-center gap-2 py-2 px-4 text-error hover:bg-error/10 rounded-lg transition-colors active:bg-base-300/50!">

View File

@@ -10,7 +10,7 @@ const { title } = Astro.props;
--- ---
<!doctype html> <!doctype html>
<html lang="en" data-theme="dark"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="description" content="Chronus Time Tracking" /> <meta name="description" content="Chronus Time Tracking" />
@@ -19,6 +19,10 @@ const { title } = Astro.props;
<meta name="generator" content={Astro.generator} /> <meta name="generator" content={Astro.generator} />
<title>{title}</title> <title>{title}</title>
<ClientRouter /> <ClientRouter />
<script is:inline>
const theme = localStorage.getItem('theme') || 'macchiato';
document.documentElement.setAttribute('data-theme', theme);
</script>
</head> </head>
<body class="min-h-screen bg-base-100 text-base-content flex flex-col"> <body class="min-h-screen bg-base-100 text-base-content flex flex-col">
<div class="flex-1 flex flex-col"> <div class="flex-1 flex flex-col">

View File

@@ -24,7 +24,6 @@ export async function validateApiToken(token: string) {
return null; return null;
} }
// Update last used at
await db await db
.update(apiTokens) .update(apiTokens)
.set({ lastUsedAt: new Date() }) .set({ lastUsedAt: new Date() })

View File

@@ -4,7 +4,6 @@
* @returns Formatted string like "01:23:45 (1h 24m)" or "00:05:23 (5m)" * @returns Formatted string like "01:23:45 (1h 24m)" or "00:05:23 (5m)"
*/ */
export function formatDuration(ms: number): string { export function formatDuration(ms: number): string {
// Calculate rounded version for easy reading
const totalMinutes = Math.round(ms / 1000 / 60); const totalMinutes = Math.round(ms / 1000 / 60);
const hours = Math.floor(totalMinutes / 60); const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60; const minutes = totalMinutes % 60;

View File

@@ -1,63 +1,42 @@
import { db } from "../db"; import { db } from "../db";
import { clients, categories, tags as tagsTable } from "../db/schema"; import { clients, tags as tagsTable } from "../db/schema";
import { eq, and, inArray } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
export async function validateTimeEntryResources({ export async function validateTimeEntryResources({
organizationId, organizationId,
clientId, clientId,
categoryId, tagId,
tagIds,
}: { }: {
organizationId: string; organizationId: string;
clientId: string; clientId: string;
categoryId: string; tagId?: string | null;
tagIds?: string[];
}) { }) {
const [client, category] = await Promise.all([ const client = await db
db .select()
.select() .from(clients)
.from(clients) .where(
.where( and(eq(clients.id, clientId), eq(clients.organizationId, organizationId)),
and( )
eq(clients.id, clientId), .get();
eq(clients.organizationId, organizationId),
),
)
.get(),
db
.select()
.from(categories)
.where(
and(
eq(categories.id, categoryId),
eq(categories.organizationId, organizationId),
),
)
.get(),
]);
if (!client) { if (!client) {
return { valid: false, error: "Invalid client" }; return { valid: false, error: "Invalid client" };
} }
if (!category) { if (tagId) {
return { valid: false, error: "Invalid category" }; const validTag = await db
}
if (tagIds && tagIds.length > 0) {
const validTags = await db
.select() .select()
.from(tagsTable) .from(tagsTable)
.where( .where(
and( and(
inArray(tagsTable.id, tagIds), eq(tagsTable.id, tagId),
eq(tagsTable.organizationId, organizationId), eq(tagsTable.organizationId, organizationId),
), ),
) )
.all(); .get();
if (validTags.length !== tagIds.length) { if (!validTag) {
return { valid: false, error: "Invalid tags" }; return { valid: false, error: "Invalid tag" };
} }
} }

View File

@@ -40,18 +40,18 @@ const allUsers = await db.select().from(users).all();
<form method="POST" action="/api/admin/settings"> <form method="POST" action="/api/admin/settings">
<div class="form-control"> <div class="form-control">
<label class="label cursor-pointer"> <label for="registration_enabled" class="label pb-2 font-medium text-sm sm:text-base">
<span class="label-text flex-1 min-w-0 pr-4"> Allow New Registrations
<div class="font-semibold">Allow New Registrations</div>
<div class="text-sm text-gray-500">When disabled, only existing users can log in</div>
</span>
<input
type="checkbox"
name="registration_enabled"
class="toggle toggle-primary"
checked={registrationEnabled}
/>
</label> </label>
<br>
<input
type="checkbox"
name="registration_enabled"
class="toggle toggle-primary shrink-0 mt-1"
checked={registrationEnabled}
/>
</div> </div>
<div class="card-actions justify-end mt-6"> <div class="card-actions justify-end mt-6">

View File

@@ -0,0 +1,35 @@
import type { APIRoute } from "astro";
import { db } from "../../../../../db";
import { passkeys } from "../../../../../db/schema";
import { eq, and } from "drizzle-orm";
export const DELETE: APIRoute = async ({ request, locals }) => {
const user = locals.user;
if (!user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
const url = new URL(request.url);
const id = url.searchParams.get("id");
if (!id) {
return new Response(JSON.stringify({ error: "Passkey ID is required" }), {
status: 400,
});
}
try {
await db
.delete(passkeys)
.where(and(eq(passkeys.id, id), eq(passkeys.userId, user.id)));
return new Response(JSON.stringify({ success: true }));
} catch (error) {
return new Response(JSON.stringify({ error: "Failed to delete passkey" }), {
status: 500,
});
}
};

View File

@@ -0,0 +1,102 @@
import type { APIRoute } from "astro";
import { verifyAuthenticationResponse } from "@simplewebauthn/server";
import { db } from "../../../../../db";
import { users, passkeys, passkeyChallenges } from "../../../../../db/schema";
import { eq, and, gt } from "drizzle-orm";
import { createSession } from "../../../../../lib/auth";
export const POST: APIRoute = async ({ request, cookies }) => {
const body = await request.json();
const { id } = body;
const passkey = await db.query.passkeys.findFirst({
where: eq(passkeys.id, id),
});
if (!passkey) {
return new Response(JSON.stringify({ error: "Passkey not found" }), {
status: 400,
});
}
const user = await db.query.users.findFirst({
where: eq(users.id, passkey.userId),
});
if (!user) return new Response(null, { status: 400 });
const clientDataJSON = Buffer.from(
body.response.clientDataJSON,
"base64url",
).toString("utf-8");
const clientData = JSON.parse(clientDataJSON);
const challenge = clientData.challenge;
const dbChallenge = await db.query.passkeyChallenges.findFirst({
where: and(
eq(passkeyChallenges.challenge, challenge),
gt(passkeyChallenges.expiresAt, new Date()),
),
});
if (!dbChallenge) {
return new Response(
JSON.stringify({ error: "Invalid or expired challenge" }),
{
status: 400,
},
);
}
let verification;
try {
verification = await verifyAuthenticationResponse({
response: body,
expectedChallenge: challenge as string,
expectedOrigin: new URL(request.url).origin,
expectedRPID: new URL(request.url).hostname,
credential: {
id: passkey.id,
publicKey: new Uint8Array(Buffer.from(passkey.publicKey, "base64")),
counter: passkey.counter,
transports: passkey.transports
? JSON.parse(passkey.transports)
: undefined,
},
});
} catch (error) {
return new Response(JSON.stringify({ error: (error as Error).message }), {
status: 400,
});
}
if (verification.verified) {
const { authenticationInfo } = verification;
await db
.update(passkeys)
.set({
counter: authenticationInfo.newCounter,
lastUsedAt: new Date(),
})
.where(eq(passkeys.id, passkey.id));
const { sessionId, expiresAt } = await createSession(user.id);
cookies.set("session_id", sessionId, {
path: "/",
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: "lax",
expires: expiresAt,
});
await db
.delete(passkeyChallenges)
.where(eq(passkeyChallenges.challenge, challenge));
return new Response(JSON.stringify({ verified: true }));
}
return new Response(JSON.stringify({ verified: false }), { status: 400 });
};

View File

@@ -0,0 +1,18 @@
import type { APIRoute } from "astro";
import { generateAuthenticationOptions } from "@simplewebauthn/server";
import { db } from "../../../../../db";
import { passkeyChallenges } from "../../../../../db/schema";
export const GET: APIRoute = async ({ request }) => {
const options = await generateAuthenticationOptions({
rpID: new URL(request.url).hostname,
userVerification: "preferred",
});
await db.insert(passkeyChallenges).values({
challenge: options.challenge,
expiresAt: new Date(Date.now() + 5 * 60 * 1000),
});
return new Response(JSON.stringify(options));
};

View File

@@ -0,0 +1,81 @@
import type { APIRoute } from "astro";
import { verifyRegistrationResponse } from "@simplewebauthn/server";
import { db } from "../../../../../db";
import { passkeys, passkeyChallenges } from "../../../../../db/schema";
import { eq, and, gt } from "drizzle-orm";
export const POST: APIRoute = async ({ request, locals }) => {
const user = locals.user;
if (!user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
const body = await request.json();
const clientDataJSON = Buffer.from(
body.response.clientDataJSON,
"base64url",
).toString("utf-8");
const clientData = JSON.parse(clientDataJSON);
const challenge = clientData.challenge;
const dbChallenge = await db.query.passkeyChallenges.findFirst({
where: and(
eq(passkeyChallenges.challenge, challenge),
eq(passkeyChallenges.userId, user.id),
gt(passkeyChallenges.expiresAt, new Date()),
),
});
if (!dbChallenge) {
return new Response(
JSON.stringify({ error: "Invalid or expired challenge" }),
{
status: 400,
},
);
}
let verification;
try {
verification = await verifyRegistrationResponse({
response: body,
expectedChallenge: challenge,
expectedOrigin: new URL(request.url).origin,
expectedRPID: new URL(request.url).hostname,
});
} catch (error) {
return new Response(JSON.stringify({ error: (error as Error).message }), {
status: 400,
});
}
if (verification.verified && verification.registrationInfo) {
const { registrationInfo } = verification;
const { credential, credentialDeviceType, credentialBackedUp } =
registrationInfo;
await db.insert(passkeys).values({
id: credential.id,
userId: user.id,
publicKey: Buffer.from(credential.publicKey).toString("base64"),
counter: credential.counter,
deviceType: credentialDeviceType,
backedUp: credentialBackedUp,
transports: body.response.transports
? JSON.stringify(body.response.transports)
: undefined,
});
await db
.delete(passkeyChallenges)
.where(eq(passkeyChallenges.challenge, challenge));
return new Response(JSON.stringify({ verified: true }));
}
return new Response(JSON.stringify({ verified: false }), { status: 400 });
};

View File

@@ -0,0 +1,44 @@
import type { APIRoute } from "astro";
import { generateRegistrationOptions } from "@simplewebauthn/server";
import { db } from "../../../../../db";
import { passkeys, passkeyChallenges } from "../../../../../db/schema";
import { eq } from "drizzle-orm";
export const GET: APIRoute = async ({ request, locals }) => {
const user = locals.user;
if (!user) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
const userPasskeys = await db.query.passkeys.findMany({
where: eq(passkeys.userId, user.id),
});
const options = await generateRegistrationOptions({
rpName: "Chronus",
rpID: new URL(request.url).hostname,
userName: user.email,
attestationType: "none",
excludeCredentials: userPasskeys.map((passkey) => ({
id: passkey.id,
transports: passkey.transports
? JSON.parse(passkey.transports)
: undefined,
})),
authenticatorSelection: {
residentKey: "preferred",
userVerification: "preferred",
},
});
await db.insert(passkeyChallenges).values({
challenge: options.challenge,
userId: user.id,
expiresAt: new Date(Date.now() + 5 * 60 * 1000),
});
return new Response(JSON.stringify(options));
};

View File

@@ -1,67 +0,0 @@
import type { APIRoute } from "astro";
import { db } from "../../../../db";
import { categories, members, timeEntries } from "../../../../db/schema";
import { eq, and } from "drizzle-orm";
export const POST: APIRoute = async ({ request, locals, redirect, params }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
let redirectTo: string | undefined;
if (request.headers.get("Content-Type")?.includes("application/json")) {
const body = await request.json();
redirectTo = body.redirectTo;
} else {
const formData = await request.formData();
redirectTo = formData.get("redirectTo")?.toString();
}
const userOrg = await db
.select()
.from(members)
.where(eq(members.userId, user.id))
.get();
if (!userOrg) {
return new Response("No organization found", { status: 400 });
}
const isAdmin = userOrg.role === "owner" || userOrg.role === "admin";
if (!isAdmin) {
return new Response("Forbidden", { status: 403 });
}
const hasEntries = await db
.select()
.from(timeEntries)
.where(eq(timeEntries.categoryId, id!))
.get();
if (hasEntries) {
return new Response("Cannot delete category with time entries", {
status: 400,
});
}
await db
.delete(categories)
.where(
and(
eq(categories.id, id!),
eq(categories.organizationId, userOrg.organizationId),
),
);
if (locals.scopes) {
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
return redirect(redirectTo || "/dashboard/team/settings");
};

View File

@@ -1,72 +0,0 @@
import type { APIRoute } from "astro";
import { db } from "../../../../db";
import { categories, members } from "../../../../db/schema";
import { eq, and } from "drizzle-orm";
export const POST: APIRoute = async ({ request, locals, redirect, params }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
let name: string | undefined;
let color: string | undefined;
let redirectTo: string | undefined;
if (request.headers.get("Content-Type")?.includes("application/json")) {
const body = await request.json();
name = body.name;
color = body.color;
redirectTo = body.redirectTo;
} else {
const formData = await request.formData();
name = formData.get("name")?.toString();
color = formData.get("color")?.toString();
redirectTo = formData.get("redirectTo")?.toString();
}
if (!name) {
return new Response("Name is required", { status: 400 });
}
const userOrg = await db
.select()
.from(members)
.where(eq(members.userId, user.id))
.get();
if (!userOrg) {
return new Response("No organization found", { status: 400 });
}
const isAdmin = userOrg.role === "owner" || userOrg.role === "admin";
if (!isAdmin) {
return new Response("Forbidden", { status: 403 });
}
await db
.update(categories)
.set({
name,
color: color || null,
})
.where(
and(
eq(categories.id, id!),
eq(categories.organizationId, userOrg.organizationId),
),
);
if (locals.scopes) {
return new Response(
JSON.stringify({ success: true, id, name, color: color || null }),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
}
return redirect(redirectTo || "/dashboard/team/settings");
};

View File

@@ -1,59 +0,0 @@
import type { APIRoute } from "astro";
import { db } from "../../../db";
import { categories, members } from "../../../db/schema";
import { eq } from "drizzle-orm";
import { nanoid } from "nanoid";
export const POST: APIRoute = async ({ request, locals, redirect }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
let name: string | undefined;
let color: string | undefined;
let redirectTo: string | undefined;
if (request.headers.get("Content-Type")?.includes("application/json")) {
const body = await request.json();
name = body.name;
color = body.color;
redirectTo = body.redirectTo;
} else {
const formData = await request.formData();
name = formData.get("name")?.toString();
color = formData.get("color")?.toString();
redirectTo = formData.get("redirectTo")?.toString();
}
if (!name) {
return new Response("Name is required", { status: 400 });
}
const userOrg = await db
.select()
.from(members)
.where(eq(members.userId, user.id))
.get();
if (!userOrg) {
return new Response("No organization found", { status: 400 });
}
const id = nanoid();
await db.insert(categories).values({
id,
organizationId: userOrg.organizationId,
name,
color: color || null,
});
if (locals.scopes) {
return new Response(JSON.stringify({ id, name, color: color || null }), {
status: 201,
headers: { "Content-Type": "application/json" },
});
}
return redirect(redirectTo || "/dashboard/team/settings");
};

View File

@@ -1,12 +1,7 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { db } from "../../../../db"; import { db } from "../../../../db";
import { import { clients, members, timeEntries } from "../../../../db/schema";
clients, import { eq, and } from "drizzle-orm";
members,
timeEntries,
timeEntryTags,
} from "../../../../db/schema";
import { eq, and, inArray } from "drizzle-orm";
export const POST: APIRoute = async ({ params, locals, redirect }) => { export const POST: APIRoute = async ({ params, locals, redirect }) => {
const user = locals.user; const user = locals.user;
@@ -57,22 +52,7 @@ export const POST: APIRoute = async ({ params, locals, redirect }) => {
return new Response("Not authorized", { status: 403 }); return new Response("Not authorized", { status: 403 });
} }
const clientEntries = await db await db.delete(timeEntries).where(eq(timeEntries.clientId, id)).run();
.select({ id: timeEntries.id })
.from(timeEntries)
.where(eq(timeEntries.clientId, id))
.all();
const entryIds = clientEntries.map((e) => e.id);
if (entryIds.length > 0) {
await db
.delete(timeEntryTags)
.where(inArray(timeEntryTags.timeEntryId, entryIds))
.run();
await db.delete(timeEntries).where(eq(timeEntries.clientId, id)).run();
}
await db.delete(clients).where(eq(clients.id, id)).run(); await db.delete(clients).where(eq(clients.id, id)).run();

View File

@@ -14,7 +14,6 @@ export const POST: APIRoute = async ({ redirect, locals, params }) => {
return new Response("Invoice ID required", { status: 400 }); return new Response("Invoice ID required", { status: 400 });
} }
// Fetch invoice to verify existence
const invoice = await db const invoice = await db
.select() .select()
.from(invoices) .from(invoices)
@@ -31,7 +30,6 @@ export const POST: APIRoute = async ({ redirect, locals, params }) => {
}); });
} }
// Verify membership
const membership = await db const membership = await db
.select() .select()
.from(members) .from(members)
@@ -48,7 +46,6 @@ export const POST: APIRoute = async ({ redirect, locals, params }) => {
} }
try { try {
// Generate next invoice number
const lastInvoice = await db const lastInvoice = await db
.select() .select()
.from(invoices) .from(invoices)
@@ -74,11 +71,6 @@ export const POST: APIRoute = async ({ redirect, locals, params }) => {
} }
} }
// Convert quote to invoice:
// 1. Change type to 'invoice'
// 2. Set status to 'draft' (so user can review before sending)
// 3. Update number to next invoice sequence
// 4. Update issue date to today
await db await db
.update(invoices) .update(invoices)
.set({ .set({

View File

@@ -1,4 +1,5 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { renderToStream } from "@ceereals/vue-pdf";
import { db } from "../../../../db"; import { db } from "../../../../db";
import { import {
invoices, invoices,
@@ -8,101 +9,109 @@ import {
members, members,
} from "../../../../db/schema"; } from "../../../../db/schema";
import { eq, and } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
import { renderToStream } from "@ceereals/vue-pdf";
import { createInvoiceDocument } from "../../../../pdf/generateInvoicePDF"; import { createInvoiceDocument } from "../../../../pdf/generateInvoicePDF";
export const GET: APIRoute = async ({ params, locals }) => { export const GET: APIRoute = async ({ params, locals }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
if (!id) {
return new Response("Invoice ID is required", { status: 400 });
}
// Fetch invoice with related data
const invoiceResult = await db
.select({
invoice: invoices,
client: clients,
organization: organizations,
})
.from(invoices)
.leftJoin(clients, eq(invoices.clientId, clients.id))
.innerJoin(organizations, eq(invoices.organizationId, organizations.id))
.where(eq(invoices.id, id))
.get();
if (!invoiceResult) {
return new Response("Invoice not found", { status: 404 });
}
const { invoice, client, organization } = invoiceResult;
// Verify membership
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, invoice.organizationId),
),
)
.get();
if (!membership) {
return new Response("Not authorized", { status: 403 });
}
// Fetch items
const items = await db
.select()
.from(invoiceItems)
.where(eq(invoiceItems.invoiceId, invoice.id))
.all();
try { try {
const { id } = params; const document = createInvoiceDocument({
const user = locals.user; invoice: {
...invoice,
notes: invoice.notes || null,
// Ensure null safety for optional fields that might be undefined in some runtimes depending on driver
discountValue: invoice.discountValue ?? null,
discountType: invoice.discountType ?? null,
discountAmount: invoice.discountAmount ?? null,
taxRate: invoice.taxRate ?? null,
},
items,
client: {
name: client?.name || "Deleted Client",
email: client?.email || null,
street: client?.street || null,
city: client?.city || null,
state: client?.state || null,
zip: client?.zip || null,
country: client?.country || null,
},
organization: {
name: organization.name,
street: organization.street || null,
city: organization.city || null,
state: organization.state || null,
zip: organization.zip || null,
country: organization.country || null,
logoUrl: organization.logoUrl || null,
},
});
if (!user || !id) { const stream = await renderToStream(document);
return new Response("Unauthorized", { status: 401 }); const chunks: Uint8Array[] = [];
for await (const chunk of stream) {
chunks.push(chunk as Uint8Array);
} }
const buffer = Buffer.concat(chunks);
// Fetch invoice with related data return new Response(buffer, {
const invoiceResult = await db headers: {
.select({ "Content-Type": "application/pdf",
invoice: invoices, "Content-Disposition": `attachment; filename="${invoice.number}.pdf"`,
client: clients, },
organization: organizations, });
})
.from(invoices)
.leftJoin(clients, eq(invoices.clientId, clients.id))
.innerJoin(organizations, eq(invoices.organizationId, organizations.id))
.where(eq(invoices.id, id))
.get();
if (!invoiceResult) {
return new Response("Invoice not found", { status: 404 });
}
const { invoice, client, organization } = invoiceResult;
// Verify access
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, invoice.organizationId),
),
)
.get();
if (!membership) {
return new Response("Forbidden", { status: 403 });
}
// Fetch items
const items = await db
.select()
.from(invoiceItems)
.where(eq(invoiceItems.invoiceId, invoice.id))
.all();
if (!client) {
return new Response("Client not found", { status: 404 });
}
// Generate PDF using Vue PDF
// Suppress verbose logging from PDF renderer
const originalConsoleLog = console.log;
const originalConsoleWarn = console.warn;
console.log = () => {};
console.warn = () => {};
try {
const pdfDocument = createInvoiceDocument({
invoice,
items,
client,
organization,
});
const stream = await renderToStream(pdfDocument);
// Restore console.log
console.log = originalConsoleLog;
console.warn = originalConsoleWarn;
const filename = `${invoice.type}_${invoice.number.replace(/[^a-zA-Z0-9]/g, "_")}.pdf`;
return new Response(stream as any, {
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `attachment; filename="${filename}"`,
},
});
} catch (pdfError) {
// Restore console.log on error
console.log = originalConsoleLog;
console.warn = originalConsoleWarn;
throw pdfError;
}
} catch (error) { } catch (error) {
console.error("Error generating PDF:", error); console.error("Error generating PDF:", error);
return new Response("Error generating PDF", { status: 500 }); return new Response("Failed to generate PDF", { status: 500 });
} }
}; };

View File

@@ -0,0 +1,276 @@
import type { APIRoute } from "astro";
import { db } from "../../../../db";
import {
invoices,
invoiceItems,
timeEntries,
members,
tags,
} from "../../../../db/schema";
import {
eq,
and,
gte,
lte,
isNull,
isNotNull,
inArray,
sql,
desc,
} from "drizzle-orm";
import { nanoid } from "nanoid";
export const POST: APIRoute = async ({ request, params, locals, redirect }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
if (!id) {
return new Response("Invoice ID is required", { status: 400 });
}
const formData = await request.formData();
const startDateStr = formData.get("startDate") as string;
const endDateStr = formData.get("endDate") as string;
const groupByDay = formData.get("groupByDay") === "on";
if (!startDateStr || !endDateStr) {
return new Response("Start date and end date are required", {
status: 400,
});
}
const startDate = new Date(startDateStr);
const endDate = new Date(endDateStr);
// Set end date to end of day
endDate.setHours(23, 59, 59, 999);
const invoice = await db
.select()
.from(invoices)
.where(eq(invoices.id, id))
.get();
if (!invoice) {
return new Response("Invoice not found", { status: 404 });
}
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, invoice.organizationId),
),
)
.get();
if (!membership) {
return new Response("Not authorized", { status: 403 });
}
if (invoice.status !== "draft") {
return new Response("Can only import time into draft invoices", {
status: 400,
});
}
const entries = await db
.select({
entry: timeEntries,
tag: tags,
})
.from(timeEntries)
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(
and(
eq(timeEntries.organizationId, invoice.organizationId),
eq(timeEntries.clientId, invoice.clientId),
isNull(timeEntries.invoiceId),
isNotNull(timeEntries.endTime),
gte(timeEntries.startTime, startDate),
lte(timeEntries.startTime, endDate),
),
)
.orderBy(desc(timeEntries.startTime));
const processedEntries = new Map<
string,
{
entry: typeof timeEntries.$inferSelect;
rates: number[];
tagNames: string[];
}
>();
for (const { entry, tag } of entries) {
if (!processedEntries.has(entry.id)) {
processedEntries.set(entry.id, {
entry,
rates: [],
tagNames: [],
});
}
const current = processedEntries.get(entry.id)!;
if (tag) {
if (tag.rate && tag.rate > 0) {
current.rates.push(tag.rate);
}
current.tagNames.push(tag.name);
}
}
const newItems: {
id: string;
invoiceId: string;
description: string;
quantity: number;
unitPrice: number;
amount: number;
}[] = [];
const entryIdsToUpdate: string[] = [];
if (groupByDay) {
// Group by YYYY-MM-DD
const days = new Map<
string,
{
date: string;
totalDuration: number; // milliseconds
totalAmount: number; // cents
entries: string[]; // ids
}
>();
for (const { entry, rates } of processedEntries.values()) {
if (!entry.endTime) continue;
const dateKey = entry.startTime.toISOString().split("T")[0];
const duration = entry.endTime.getTime() - entry.startTime.getTime();
const hours = duration / (1000 * 60 * 60);
// Determine rate: max of tags, or 0
const rate = rates.length > 0 ? Math.max(...rates) : 0;
const amount = Math.round(hours * rate);
if (!days.has(dateKey)) {
days.set(dateKey, {
date: dateKey,
totalDuration: 0,
totalAmount: 0,
entries: [],
});
}
const day = days.get(dateKey)!;
day.totalDuration += duration;
day.totalAmount += amount;
day.entries.push(entry.id);
entryIdsToUpdate.push(entry.id);
}
for (const day of days.values()) {
const hours = day.totalDuration / (1000 * 60 * 60);
// Avoid division by zero
const unitPrice = hours > 0 ? Math.round(day.totalAmount / hours) : 0;
newItems.push({
id: nanoid(),
invoiceId: invoice.id,
description: `Time entries for ${day.date} (${day.entries.length} entries)`,
quantity: parseFloat(hours.toFixed(2)),
unitPrice,
amount: day.totalAmount,
});
}
} else {
// Individual items
for (const { entry, rates, tagNames } of processedEntries.values()) {
if (!entry.endTime) continue;
const duration = entry.endTime.getTime() - entry.startTime.getTime();
const hours = duration / (1000 * 60 * 60);
// Determine rate: max of tags, or 0
const rate = rates.length > 0 ? Math.max(...rates) : 0;
const amount = Math.round(hours * rate);
let description = entry.description || "Time Entry";
const dateStr = entry.startTime.toLocaleDateString();
description = `[${dateStr}] ${description}`;
if (tagNames.length > 0) {
description += ` (${tagNames.join(", ")})`;
}
newItems.push({
id: nanoid(),
invoiceId: invoice.id,
description,
quantity: parseFloat(hours.toFixed(2)),
unitPrice: rate,
amount,
});
entryIdsToUpdate.push(entry.id);
}
}
if (newItems.length === 0) {
return redirect(`/dashboard/invoices/${id}?error=no-entries`);
}
// Transaction-like operations
try {
await db.insert(invoiceItems).values(newItems);
if (entryIdsToUpdate.length > 0) {
await db
.update(timeEntries)
.set({ invoiceId: invoice.id })
.where(inArray(timeEntries.id, entryIdsToUpdate));
}
const allItems = await db
.select()
.from(invoiceItems)
.where(eq(invoiceItems.invoiceId, invoice.id));
const subtotal = allItems.reduce((sum, item) => sum + item.amount, 0);
let discountAmount = 0;
if (invoice.discountType === "percentage") {
discountAmount = Math.round(
subtotal * ((invoice.discountValue || 0) / 100),
);
} else {
discountAmount = Math.round((invoice.discountValue || 0) * 100);
if (invoice.discountValue && invoice.discountValue > 0) {
discountAmount = Math.round((invoice.discountValue || 0) * 100);
}
}
const taxableAmount = Math.max(0, subtotal - discountAmount);
const taxAmount = Math.round(
taxableAmount * ((invoice.taxRate || 0) / 100),
);
const total = subtotal - discountAmount + taxAmount;
await db
.update(invoices)
.set({
subtotal,
discountAmount,
taxAmount,
total,
})
.where(eq(invoices.id, invoice.id));
return redirect(`/dashboard/invoices/${id}?success=imported`);
} catch (error) {
console.error("Error importing time entries:", error);
return new Response("Failed to import time entries", { status: 500 });
}
};

View File

@@ -64,7 +64,6 @@ export const POST: APIRoute = async ({
const quantity = parseFloat(quantityStr); const quantity = parseFloat(quantityStr);
const unitPriceMajor = parseFloat(unitPriceStr); const unitPriceMajor = parseFloat(unitPriceStr);
// Convert to cents
const unitPrice = Math.round(unitPriceMajor * 100); const unitPrice = Math.round(unitPriceMajor * 100);
const amount = Math.round(quantity * unitPrice); const amount = Math.round(quantity * unitPrice);
@@ -77,7 +76,6 @@ export const POST: APIRoute = async ({
amount, amount,
}); });
// Update invoice totals
await recalculateInvoiceTotals(invoiceId); await recalculateInvoiceTotals(invoiceId);
return redirect(`/dashboard/invoices/${invoiceId}`); return redirect(`/dashboard/invoices/${invoiceId}`);

View File

@@ -20,7 +20,6 @@ export const POST: APIRoute = async ({
return new Response("Invoice ID required", { status: 400 }); return new Response("Invoice ID required", { status: 400 });
} }
// Fetch invoice to verify existence and check status
const invoice = await db const invoice = await db
.select() .select()
.from(invoices) .from(invoices)
@@ -31,7 +30,6 @@ export const POST: APIRoute = async ({
return new Response("Invoice not found", { status: 404 }); return new Response("Invoice not found", { status: 404 });
} }
// Verify membership
const membership = await db const membership = await db
.select() .select()
.from(members) .from(members)
@@ -47,7 +45,6 @@ export const POST: APIRoute = async ({
return new Response("Unauthorized", { status: 401 }); return new Response("Unauthorized", { status: 401 });
} }
// Only allow editing if draft
if (invoice.status !== "draft") { if (invoice.status !== "draft") {
return new Response("Cannot edit a finalized invoice", { status: 400 }); return new Response("Cannot edit a finalized invoice", { status: 400 });
} }
@@ -59,7 +56,6 @@ export const POST: APIRoute = async ({
return new Response("Item ID required", { status: 400 }); return new Response("Item ID required", { status: 400 });
} }
// Verify item belongs to invoice
const item = await db const item = await db
.select() .select()
.from(invoiceItems) .from(invoiceItems)
@@ -73,7 +69,6 @@ export const POST: APIRoute = async ({
try { try {
await db.delete(invoiceItems).where(eq(invoiceItems.id, itemId)); await db.delete(invoiceItems).where(eq(invoiceItems.id, itemId));
// Update invoice totals
await recalculateInvoiceTotals(invoiceId); await recalculateInvoiceTotals(invoiceId);
return redirect(`/dashboard/invoices/${invoiceId}`); return redirect(`/dashboard/invoices/${invoiceId}`);

View File

@@ -35,7 +35,6 @@ export const POST: APIRoute = async ({
return new Response("Invalid status", { status: 400 }); return new Response("Invalid status", { status: 400 });
} }
// Fetch invoice to verify existence and check ownership
const invoice = await db const invoice = await db
.select() .select()
.from(invoices) .from(invoices)
@@ -46,7 +45,6 @@ export const POST: APIRoute = async ({
return new Response("Invoice not found", { status: 404 }); return new Response("Invoice not found", { status: 404 });
} }
// Verify membership
const membership = await db const membership = await db
.select() .select()
.from(members) .from(members)

View File

@@ -20,7 +20,6 @@ export const POST: APIRoute = async ({
return new Response("Invoice ID required", { status: 400 }); return new Response("Invoice ID required", { status: 400 });
} }
// Fetch invoice to verify existence
const invoice = await db const invoice = await db
.select() .select()
.from(invoices) .from(invoices)
@@ -31,7 +30,6 @@ export const POST: APIRoute = async ({
return new Response("Invoice not found", { status: 404 }); return new Response("Invoice not found", { status: 404 });
} }
// Verify membership
const membership = await db const membership = await db
.select() .select()
.from(members) .from(members)

View File

@@ -4,12 +4,7 @@ import { invoices, members } from "../../../../db/schema";
import { eq, and } from "drizzle-orm"; import { eq, and } from "drizzle-orm";
import { recalculateInvoiceTotals } from "../../../../utils/invoice"; import { recalculateInvoiceTotals } from "../../../../utils/invoice";
export const POST: APIRoute = async ({ export const POST: APIRoute = async ({ request, redirect, locals, params }) => {
request,
redirect,
locals,
params,
}) => {
const user = locals.user; const user = locals.user;
if (!user) { if (!user) {
return redirect("/login"); return redirect("/login");
@@ -38,8 +33,8 @@ export const POST: APIRoute = async ({
.where( .where(
and( and(
eq(members.userId, user.id), eq(members.userId, user.id),
eq(members.organizationId, invoice.organizationId) eq(members.organizationId, invoice.organizationId),
) ),
) )
.get(); .get();
@@ -53,6 +48,8 @@ export const POST: APIRoute = async ({
const issueDateStr = formData.get("issueDate") as string; const issueDateStr = formData.get("issueDate") as string;
const dueDateStr = formData.get("dueDate") as string; const dueDateStr = formData.get("dueDate") as string;
const taxRateStr = formData.get("taxRate") as string; const taxRateStr = formData.get("taxRate") as string;
const discountType = (formData.get("discountType") as string) || "percentage";
const discountValueStr = formData.get("discountValue") as string;
const notes = formData.get("notes") as string; const notes = formData.get("notes") as string;
if (!number || !currency || !issueDateStr || !dueDateStr) { if (!number || !currency || !issueDateStr || !dueDateStr) {
@@ -64,6 +61,11 @@ export const POST: APIRoute = async ({
const dueDate = new Date(dueDateStr); const dueDate = new Date(dueDateStr);
const taxRate = taxRateStr ? parseFloat(taxRateStr) : 0; const taxRate = taxRateStr ? parseFloat(taxRateStr) : 0;
let discountValue = discountValueStr ? parseFloat(discountValueStr) : 0;
if (discountType === "fixed") {
discountValue = Math.round(discountValue * 100);
}
await db await db
.update(invoices) .update(invoices)
.set({ .set({
@@ -72,6 +74,8 @@ export const POST: APIRoute = async ({
issueDate, issueDate,
dueDate, dueDate,
taxRate, taxRate,
discountType: discountType as "percentage" | "fixed",
discountValue,
notes: notes || null, notes: notes || null,
}) })
.where(eq(invoices.id, invoiceId)); .where(eq(invoices.id, invoiceId));

View File

@@ -19,6 +19,8 @@ export const POST: APIRoute = async ({ request, locals, redirect }) => {
const state = formData.get("state") as string | null; const state = formData.get("state") as string | null;
const zip = formData.get("zip") as string | null; const zip = formData.get("zip") as string | null;
const country = formData.get("country") as string | null; const country = formData.get("country") as string | null;
const defaultTaxRate = formData.get("defaultTaxRate") as string | null;
const defaultCurrency = formData.get("defaultCurrency") as string | null;
const logo = formData.get("logo") as File | null; const logo = formData.get("logo") as File | null;
if (!organizationId || !name || name.trim().length === 0) { if (!organizationId || !name || name.trim().length === 0) {
@@ -96,6 +98,8 @@ export const POST: APIRoute = async ({ request, locals, redirect }) => {
state: state?.trim() || null, state: state?.trim() || null,
zip: zip?.trim() || null, zip: zip?.trim() || null,
country: country?.trim() || null, country: country?.trim() || null,
defaultTaxRate: defaultTaxRate ? parseFloat(defaultTaxRate) : 0,
defaultCurrency: defaultCurrency || "USD",
}; };
if (logoUrl) { if (logoUrl) {

View File

@@ -0,0 +1,162 @@
import type { APIRoute } from "astro";
import { db } from "../../../db";
import { timeEntries, members, users, clients, tags } from "../../../db/schema";
import { eq, and, gte, lte, desc } from "drizzle-orm";
export const GET: APIRoute = async ({ request, locals, cookies }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
// Get current team from cookie
const currentTeamId = cookies.get("currentTeamId")?.value;
const userMemberships = await db
.select()
.from(members)
.where(eq(members.userId, user.id))
.all();
if (userMemberships.length === 0) {
return new Response("No organization found", { status: 404 });
}
// Use current team or fallback to first membership
const userMembership = currentTeamId
? userMemberships.find((m) => m.organizationId === currentTeamId) ||
userMemberships[0]
: userMemberships[0];
const url = new URL(request.url);
const selectedMemberId = url.searchParams.get("member") || "";
const selectedClientId = url.searchParams.get("client") || "";
const timeRange = url.searchParams.get("range") || "week";
const customFrom = url.searchParams.get("from");
const customTo = url.searchParams.get("to");
const now = new Date();
let startDate = new Date();
let endDate = new Date();
switch (timeRange) {
case "today":
startDate.setHours(0, 0, 0, 0);
endDate.setHours(23, 59, 59, 999);
break;
case "week":
startDate.setDate(now.getDate() - 7);
break;
case "month":
startDate.setMonth(now.getMonth() - 1);
break;
case "mtd":
startDate = new Date(now.getFullYear(), now.getMonth(), 1);
break;
case "ytd":
startDate = new Date(now.getFullYear(), 0, 1);
break;
case "last-month":
startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
endDate = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
break;
case "custom":
if (customFrom) {
const parts = customFrom.split("-");
startDate = new Date(
parseInt(parts[0]),
parseInt(parts[1]) - 1,
parseInt(parts[2]),
0,
0,
0,
0,
);
}
if (customTo) {
const parts = customTo.split("-");
endDate = new Date(
parseInt(parts[0]),
parseInt(parts[1]) - 1,
parseInt(parts[2]),
23,
59,
59,
999,
);
}
break;
}
const conditions = [
eq(timeEntries.organizationId, userMembership.organizationId),
gte(timeEntries.startTime, startDate),
lte(timeEntries.startTime, endDate),
];
if (selectedMemberId) {
conditions.push(eq(timeEntries.userId, selectedMemberId));
}
if (selectedClientId) {
conditions.push(eq(timeEntries.clientId, selectedClientId));
}
const entries = await db
.select({
entry: timeEntries,
user: users,
client: clients,
tag: tags,
})
.from(timeEntries)
.innerJoin(users, eq(timeEntries.userId, users.id))
.innerJoin(clients, eq(timeEntries.clientId, clients.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and(...conditions))
.orderBy(desc(timeEntries.startTime))
.all();
// Generate CSV
const headers = [
"Date",
"Start Time",
"End Time",
"Duration (h)",
"Member",
"Client",
"Tag",
"Description",
];
const rows = entries.map((e) => {
const start = e.entry.startTime;
const end = e.entry.endTime;
let duration = 0;
if (end) {
duration = (end.getTime() - start.getTime()) / (1000 * 60 * 60); // Hours
}
const tagsStr = e.tag?.name || "";
return [
start.toLocaleDateString(),
start.toLocaleTimeString(),
end ? end.toLocaleTimeString() : "",
end ? duration.toFixed(2) : "Running",
`"${(e.user.name || "").replace(/"/g, '""')}"`,
`"${(e.client.name || "").replace(/"/g, '""')}"`,
`"${tagsStr.replace(/"/g, '""')}"`,
`"${(e.entry.description || "").replace(/"/g, '""')}"`,
].join(",");
});
const csvContent = [headers.join(","), ...rows].join("\n");
return new Response(csvContent, {
headers: {
"Content-Type": "text/csv",
"Content-Disposition": `attachment; filename="time-entries-${startDate.toISOString().split("T")[0]}-to-${endDate.toISOString().split("T")[0]}.csv"`,
},
});
};

View File

@@ -0,0 +1,57 @@
import type { APIRoute } from "astro";
import { db } from "../../../../db";
import { tags, members, timeEntries } from "../../../../db/schema";
import { eq, and } from "drizzle-orm";
export const POST: APIRoute = async ({ params, locals, redirect }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
if (!id) {
return new Response("Tag ID is required", { status: 400 });
}
// Get the tag to check organization
const tag = await db.select().from(tags).where(eq(tags.id, id)).get();
if (!tag) {
return new Response("Tag not found", { status: 404 });
}
// Verify membership and permissions
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, tag.organizationId),
),
)
.get();
if (!membership) {
return new Response("Not authorized", { status: 403 });
}
const isAdmin = membership.role === "owner" || membership.role === "admin";
if (!isAdmin) {
return new Response("Only owners and admins can manage tags", {
status: 403,
});
}
// Remove tag from time entries
await db
.update(timeEntries)
.set({ tagId: null })
.where(eq(timeEntries.tagId, id));
// Delete the tag
await db.delete(tags).where(eq(tags.id, id));
return redirect("/dashboard/team/settings?success=tags");
};

View File

@@ -0,0 +1,77 @@
import type { APIRoute } from "astro";
import { db } from "../../../../db";
import { tags, members } from "../../../../db/schema";
import { eq, and } from "drizzle-orm";
export const POST: APIRoute = async ({
request,
params,
locals,
redirect,
}) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const { id } = params;
if (!id) {
return new Response("Tag ID is required", { status: 400 });
}
let name: string | undefined;
let color: string | undefined;
let rate: number | undefined;
if (request.headers.get("Content-Type")?.includes("application/json")) {
const body = await request.json();
name = body.name;
color = body.color;
rate = body.rate !== undefined ? parseInt(body.rate) : undefined;
} else {
const formData = await request.formData();
name = formData.get("name")?.toString();
color = formData.get("color")?.toString();
const rateStr = formData.get("rate")?.toString();
rate = rateStr ? parseInt(rateStr) : undefined;
}
// Get the tag to check organization
const tag = await db.select().from(tags).where(eq(tags.id, id)).get();
if (!tag) {
return new Response("Tag not found", { status: 404 });
}
// Verify membership and permissions
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, tag.organizationId),
),
)
.get();
if (!membership) {
return new Response("Not authorized", { status: 403 });
}
const isAdmin = membership.role === "owner" || membership.role === "admin";
if (!isAdmin) {
return new Response("Only owners and admins can manage tags", {
status: 403,
});
}
const updateData: any = {};
if (name) updateData.name = name;
if (color) updateData.color = color;
if (rate !== undefined) updateData.rate = rate;
await db.update(tags).set(updateData).where(eq(tags.id, id));
return redirect("/dashboard/team/settings?success=tags");
};

View File

@@ -0,0 +1,72 @@
import type { APIRoute } from "astro";
import { db } from "../../../db";
import { tags, members } from "../../../db/schema";
import { eq, and } from "drizzle-orm";
import { nanoid } from "nanoid";
export const POST: APIRoute = async ({ request, locals, redirect }) => {
const user = locals.user;
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
let name: string | undefined;
let color: string | undefined;
let rate: number | undefined;
let organizationId: string | undefined;
if (request.headers.get("Content-Type")?.includes("application/json")) {
const body = await request.json();
name = body.name;
color = body.color;
rate = body.rate ? parseInt(body.rate) : 0;
organizationId = body.organizationId;
} else {
const formData = await request.formData();
name = formData.get("name")?.toString();
color = formData.get("color")?.toString();
const rateStr = formData.get("rate")?.toString();
rate = rateStr ? parseInt(rateStr) : 0;
organizationId = formData.get("organizationId")?.toString();
}
if (!name || !organizationId) {
return new Response("Name and Organization ID are required", {
status: 400,
});
}
// Verify membership and permissions
const membership = await db
.select()
.from(members)
.where(
and(
eq(members.userId, user.id),
eq(members.organizationId, organizationId),
),
)
.get();
if (!membership) {
return new Response("Not authorized", { status: 403 });
}
const isAdmin = membership.role === "owner" || membership.role === "admin";
if (!isAdmin) {
return new Response("Only owners and admins can manage tags", {
status: 403,
});
}
const id = nanoid();
await db.insert(tags).values({
id,
organizationId,
name,
color: color || null,
rate: rate || 0,
});
return redirect("/dashboard/team/settings?success=tags");
};

View File

@@ -1,6 +1,6 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { db } from "../../../db"; import { db } from "../../../db";
import { timeEntries, members, timeEntryTags } from "../../../db/schema"; import { timeEntries, members } from "../../../db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { import {
@@ -17,7 +17,7 @@ export const POST: APIRoute = async ({ request, locals }) => {
} }
const body = await request.json(); const body = await request.json();
const { description, clientId, categoryId, startTime, endTime, tags } = body; const { description, clientId, startTime, endTime, tagId } = body;
// Validation // Validation
if (!clientId) { if (!clientId) {
@@ -27,13 +27,6 @@ export const POST: APIRoute = async ({ request, locals }) => {
}); });
} }
if (!categoryId) {
return new Response(JSON.stringify({ error: "Category is required" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
if (!startTime) { if (!startTime) {
return new Response(JSON.stringify({ error: "Start time is required" }), { return new Response(JSON.stringify({ error: "Start time is required" }), {
status: 400, status: 400,
@@ -81,8 +74,7 @@ export const POST: APIRoute = async ({ request, locals }) => {
const resourceValidation = await validateTimeEntryResources({ const resourceValidation = await validateTimeEntryResources({
organizationId: member.organizationId, organizationId: member.organizationId,
clientId, clientId,
categoryId, tagId: tagId || null,
tagIds: Array.isArray(tags) ? tags : undefined,
}); });
if (!resourceValidation.valid) { if (!resourceValidation.valid) {
@@ -101,23 +93,13 @@ export const POST: APIRoute = async ({ request, locals }) => {
userId: locals.user.id, userId: locals.user.id,
organizationId: member.organizationId, organizationId: member.organizationId,
clientId, clientId,
categoryId, tagId: tagId || null,
startTime: startDate, startTime: startDate,
endTime: endDate, endTime: endDate,
description: description || null, description: description || null,
isManual: true, isManual: true,
}); });
// Insert tags if provided
if (tags && Array.isArray(tags) && tags.length > 0) {
await db.insert(timeEntryTags).values(
tags.map((tagId: string) => ({
timeEntryId: id,
tagId,
})),
);
}
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
success: true, success: true,

View File

@@ -1,6 +1,6 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { db } from "../../../db"; import { db } from "../../../db";
import { timeEntries, members, timeEntryTags } from "../../../db/schema"; import { timeEntries, members } from "../../../db/schema";
import { eq, and, isNull } from "drizzle-orm"; import { eq, and, isNull } from "drizzle-orm";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { validateTimeEntryResources } from "../../../lib/validation"; import { validateTimeEntryResources } from "../../../lib/validation";
@@ -11,17 +11,12 @@ export const POST: APIRoute = async ({ request, locals }) => {
const body = await request.json(); const body = await request.json();
const description = body.description || ""; const description = body.description || "";
const clientId = body.clientId; const clientId = body.clientId;
const categoryId = body.categoryId; const tagId = body.tagId || null;
const tags = body.tags || [];
if (!clientId) { if (!clientId) {
return new Response("Client is required", { status: 400 }); return new Response("Client is required", { status: 400 });
} }
if (!categoryId) {
return new Response("Category is required", { status: 400 });
}
const runningEntry = await db const runningEntry = await db
.select() .select()
.from(timeEntries) .from(timeEntries)
@@ -47,8 +42,7 @@ export const POST: APIRoute = async ({ request, locals }) => {
const validation = await validateTimeEntryResources({ const validation = await validateTimeEntryResources({
organizationId: member.organizationId, organizationId: member.organizationId,
clientId, clientId,
categoryId, tagId,
tagIds: tags,
}); });
if (!validation.valid) { if (!validation.valid) {
@@ -63,20 +57,11 @@ export const POST: APIRoute = async ({ request, locals }) => {
userId: locals.user.id, userId: locals.user.id,
organizationId: member.organizationId, organizationId: member.organizationId,
clientId, clientId,
categoryId, tagId,
startTime, startTime,
description, description,
isManual: false, isManual: false,
}); });
if (tags.length > 0) {
await db.insert(timeEntryTags).values(
tags.map((tagId: string) => ({
timeEntryId: id,
tagId,
})),
);
}
return new Response(JSON.stringify({ id, startTime }), { status: 200 }); return new Response(JSON.stringify({ id, startTime }), { status: 200 });
}; };

View File

@@ -1,61 +1,104 @@
import type { APIRoute } from 'astro'; import type { APIRoute } from "astro";
import { db } from '../../../db'; import { db } from "../../../db";
import { users } from '../../../db/schema'; import { users } from "../../../db/schema";
import { eq } from 'drizzle-orm'; import { eq } from "drizzle-orm";
import bcrypt from 'bcryptjs'; import bcrypt from "bcryptjs";
export const POST: APIRoute = async ({ request, locals, redirect }) => { export const POST: APIRoute = async ({ request, locals, redirect }) => {
const user = locals.user; const user = locals.user;
const contentType = request.headers.get("content-type");
const isJson = contentType?.includes("application/json");
if (!user) { if (!user) {
return redirect('/login'); if (isJson) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
return redirect("/login");
} }
const formData = await request.formData(); let currentPassword, newPassword, confirmPassword;
const currentPassword = formData.get('currentPassword') as string;
const newPassword = formData.get('newPassword') as string; if (isJson) {
const confirmPassword = formData.get('confirmPassword') as string; const body = await request.json();
currentPassword = body.currentPassword;
newPassword = body.newPassword;
confirmPassword = body.confirmPassword;
} else {
const formData = await request.formData();
currentPassword = formData.get("currentPassword") as string;
newPassword = formData.get("newPassword") as string;
confirmPassword = formData.get("confirmPassword") as string;
}
if (!currentPassword || !newPassword || !confirmPassword) { if (!currentPassword || !newPassword || !confirmPassword) {
return new Response('All fields are required', { status: 400 }); const msg = "All fields are required";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 400 });
return new Response(msg, { status: 400 });
} }
if (newPassword !== confirmPassword) { if (newPassword !== confirmPassword) {
return new Response('New passwords do not match', { status: 400 }); const msg = "New passwords do not match";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 400 });
return new Response(msg, { status: 400 });
} }
if (newPassword.length < 8) { if (newPassword.length < 8) {
return new Response('Password must be at least 8 characters', { status: 400 }); const msg = "Password must be at least 8 characters";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 400 });
return new Response(msg, { status: 400 });
} }
try { try {
// Get current user from database // Get current user from database
const dbUser = await db.select() const dbUser = await db
.select()
.from(users) .from(users)
.where(eq(users.id, user.id)) .where(eq(users.id, user.id))
.get(); .get();
if (!dbUser) { if (!dbUser) {
return new Response('User not found', { status: 404 }); const msg = "User not found";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 404 });
return new Response(msg, { status: 404 });
} }
// Verify current password // Verify current password
const passwordMatch = await bcrypt.compare(currentPassword, dbUser.passwordHash); const passwordMatch = await bcrypt.compare(
currentPassword,
dbUser.passwordHash,
);
if (!passwordMatch) { if (!passwordMatch) {
return new Response('Current password is incorrect', { status: 400 }); const msg = "Current password is incorrect";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 400 });
return new Response(msg, { status: 400 });
} }
// Hash new password // Hash new password
const hashedPassword = await bcrypt.hash(newPassword, 10); const hashedPassword = await bcrypt.hash(newPassword, 10);
// Update password // Update password
await db.update(users) await db
.update(users)
.set({ passwordHash: hashedPassword }) .set({ passwordHash: hashedPassword })
.where(eq(users.id, user.id)) .where(eq(users.id, user.id))
.run(); .run();
return redirect('/dashboard/settings?success=password'); if (isJson) {
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
return redirect("/dashboard/settings?success=password");
} catch (error) { } catch (error) {
console.error('Error changing password:', error); console.error("Error changing password:", error);
return new Response('Failed to change password', { status: 500 }); const msg = "Failed to change password";
if (isJson)
return new Response(JSON.stringify({ error: msg }), { status: 500 });
return new Response(msg, { status: 500 });
} }
}; };

View File

@@ -12,8 +12,16 @@ export const POST: APIRoute = async ({ request, locals }) => {
}); });
} }
const formData = await request.formData(); let name: string | undefined;
const name = formData.get("name")?.toString();
const contentType = request.headers.get("content-type");
if (contentType?.includes("application/json")) {
const body = await request.json();
name = body.name;
} else {
const formData = await request.formData();
name = formData.get("name")?.toString();
}
if (!name) { if (!name) {
return new Response(JSON.stringify({ error: "Name is required" }), { return new Response(JSON.stringify({ error: "Name is required" }), {

View File

@@ -1,30 +1,58 @@
import type { APIRoute } from 'astro'; import type { APIRoute } from "astro";
import { db } from '../../../db'; import { db } from "../../../db";
import { users } from '../../../db/schema'; import { users } from "../../../db/schema";
import { eq } from 'drizzle-orm'; import { eq } from "drizzle-orm";
export const POST: APIRoute = async ({ request, locals, redirect }) => { export const POST: APIRoute = async ({ request, locals, redirect }) => {
const user = locals.user; const user = locals.user;
const contentType = request.headers.get("content-type");
const isJson = contentType?.includes("application/json");
if (!user) { if (!user) {
return redirect('/login'); if (isJson) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
});
}
return redirect("/login");
} }
const formData = await request.formData(); let name: string | undefined;
const name = formData.get('name') as string;
if (isJson) {
const body = await request.json();
name = body.name;
} else {
const formData = await request.formData();
name = formData.get("name") as string;
}
if (!name || name.trim().length === 0) { if (!name || name.trim().length === 0) {
return new Response('Name is required', { status: 400 }); const msg = "Name is required";
if (isJson) {
return new Response(JSON.stringify({ error: msg }), { status: 400 });
}
return new Response(msg, { status: 400 });
} }
try { try {
await db.update(users) await db
.update(users)
.set({ name: name.trim() }) .set({ name: name.trim() })
.where(eq(users.id, user.id)) .where(eq(users.id, user.id))
.run(); .run();
return redirect('/dashboard/settings?success=profile'); if (isJson) {
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
return redirect("/dashboard/settings?success=profile");
} catch (error) { } catch (error) {
console.error('Error updating profile:', error); console.error("Error updating profile:", error);
return new Response('Failed to update profile', { status: 500 }); const msg = "Failed to update profile";
if (isJson) {
return new Response(JSON.stringify({ error: msg }), { status: 500 });
}
return new Response(msg, { status: 500 });
} }
}; };

View File

@@ -1,62 +0,0 @@
---
import DashboardLayout from '../../layouts/DashboardLayout.astro';
import { db } from '../../db';
import { categories, members } from '../../db/schema';
import { eq } from 'drizzle-orm';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
// Get current team from cookie
const currentTeamId = Astro.cookies.get('currentTeamId')?.value;
const userMemberships = await db.select()
.from(members)
.where(eq(members.userId, user.id))
.all();
if (userMemberships.length === 0) return Astro.redirect('/dashboard');
// Use current team or fallback to first membership
const userMembership = currentTeamId
? userMemberships.find(m => m.organizationId === currentTeamId) || userMemberships[0]
: userMemberships[0];
const allCategories = await db.select()
.from(categories)
.where(eq(categories.organizationId, userMembership.organizationId))
.all();
---
<DashboardLayout title="Categories - Chronus">
<div class="flex justify-between items-center mb-6">
<h1 class="text-3xl font-bold">Categories</h1>
<a href="/dashboard/categories/new" class="btn btn-primary">Add Category</a>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{allCategories.map(category => (
<div class="card bg-base-200 shadow-xl border border-base-300">
<div class="card-body">
<h2 class="card-title">
{category.color && (
<span class="w-4 h-4 rounded-full" style={`background-color: ${category.color}`}></span>
)}
{category.name}
</h2>
<p class="text-xs text-base-content/60">Created {category.createdAt?.toLocaleDateString() ?? 'N/A'}</p>
<div class="card-actions justify-end mt-4">
<a href={`/dashboard/categories/${category.id}/edit`} class="btn btn-sm btn-primary">Edit</a>
</div>
</div>
</div>
))}
</div>
{allCategories.length === 0 && (
<div class="text-center py-12">
<p class="text-base-content/60 mb-4">No categories yet</p>
<a href="/dashboard/categories/new" class="btn btn-primary">Add Your First Category</a>
</div>
)}
</DashboardLayout>

View File

@@ -1,99 +0,0 @@
---
import DashboardLayout from '../../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components';
import { db } from '../../../../db';
import { categories, members } from '../../../../db/schema';
import { eq, and } from 'drizzle-orm';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
const { id } = Astro.params;
// Get current team from cookie
const currentTeamId = Astro.cookies.get('currentTeamId')?.value;
const userMemberships = await db.select()
.from(members)
.where(eq(members.userId, user.id))
.all();
if (userMemberships.length === 0) return Astro.redirect('/dashboard');
// Use current team or fallback to first membership
const userMembership = currentTeamId
? userMemberships.find(m => m.organizationId === currentTeamId) || userMemberships[0]
: userMemberships[0];
const isAdmin = userMembership.role === 'owner' || userMembership.role === 'admin';
if (!isAdmin) return Astro.redirect('/dashboard/categories');
const category = await db.select()
.from(categories)
.where(and(
eq(categories.id, id!),
eq(categories.organizationId, userMembership.organizationId)
))
.get();
if (!category) return Astro.redirect('/dashboard/categories');
---
<DashboardLayout title="Edit Category - Chronus">
<div class="max-w-2xl mx-auto">
<div class="flex items-center gap-3 mb-6">
<a href="/dashboard/categories" class="btn btn-ghost btn-sm">
<Icon name="heroicons:arrow-left" class="w-5 h-5" />
</a>
<h1 class="text-3xl font-bold">Edit Category</h1>
</div>
<div class="card bg-base-200 shadow-xl border border-base-300">
<div class="card-body">
<form id="update-form" method="POST" action={`/api/categories/${id}/update`}>
<input type="hidden" name="redirectTo" value="/dashboard/categories" />
<div class="form-control">
<label class="label pb-2" for="name">
<span class="label-text font-medium">Category Name</span>
</label>
<input
type="text"
id="name"
name="name"
value={category.name}
placeholder="Development"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control mt-4">
<label class="label pb-2" for="color">
<span class="label-text font-medium">Color (optional)</span>
</label>
<input
type="color"
id="color"
name="color"
value={category.color || '#3b82f6'}
class="input input-bordered w-full h-12"
/>
</div>
</form>
<div class="card-actions justify-between mt-6">
<form method="POST" action={`/api/categories/${id}/delete`} onsubmit="return confirm('Are you sure you want to delete this category?');">
<input type="hidden" name="redirectTo" value="/dashboard/categories" />
<button type="submit" class="btn btn-error btn-outline">Delete Category</button>
</form>
<div class="flex gap-2">
<a href="/dashboard/categories" class="btn btn-ghost">Cancel</a>
<button type="submit" form="update-form" class="btn btn-primary">Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</DashboardLayout>

View File

@@ -1,54 +0,0 @@
---
import DashboardLayout from '../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
---
<DashboardLayout title="New Category - Chronus">
<div class="max-w-2xl mx-auto">
<div class="flex items-center gap-3 mb-6">
<a href="/dashboard/categories" class="btn btn-ghost btn-sm">
<Icon name="heroicons:arrow-left" class="w-5 h-5" />
</a>
<h1 class="text-3xl font-bold">Add New Category</h1>
</div>
<form method="POST" action="/api/categories/create" class="card bg-base-200 shadow-xl border border-base-300">
<input type="hidden" name="redirectTo" value="/dashboard/categories" />
<div class="card-body">
<div class="form-control">
<label class="label pb-2" for="name">
<span class="label-text font-medium">Category Name</span>
</label>
<input
type="text"
id="name"
name="name"
placeholder="Development"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label class="label pb-2" for="color">
<span class="label-text font-medium">Color (optional)</span>
</label>
<input
type="color"
id="color"
name="color"
class="input input-bordered w-full h-12"
/>
</div>
<div class="card-actions justify-end mt-6">
<a href="/dashboard/categories" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">Create Category</button>
</div>
</div>
</form>
</div>
</DashboardLayout>

View File

@@ -50,7 +50,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="card-body"> <div class="card-body">
<div class="form-control"> <div class="form-control">
<label class="label" for="name"> <label class="label" for="name">
<span class="label-text">Client Name</span> Client Name
</label> </label>
<input <input
type="text" type="text"
@@ -65,7 +65,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="form-control"> <div class="form-control">
<label class="label" for="email"> <label class="label" for="email">
<span class="label-text">Email (optional)</span> Email (optional)
</label> </label>
<input <input
type="email" type="email"
@@ -79,7 +79,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="form-control"> <div class="form-control">
<label class="label" for="phone"> <label class="label" for="phone">
<span class="label-text">Phone (optional)</span> Phone (optional)
</label> </label>
<input <input
type="tel" type="tel"
@@ -95,7 +95,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="form-control"> <div class="form-control">
<label class="label" for="street"> <label class="label" for="street">
<span class="label-text">Street Address (optional)</span> Street Address (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -110,7 +110,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label" for="city"> <label class="label" for="city">
<span class="label-text">City (optional)</span> City (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -124,7 +124,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="form-control"> <div class="form-control">
<label class="label" for="state"> <label class="label" for="state">
<span class="label-text">State / Province (optional)</span> State / Province (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -140,7 +140,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label" for="zip"> <label class="label" for="zip">
<span class="label-text">Zip / Postal Code (optional)</span> Zip / Postal Code (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -154,7 +154,7 @@ if (!client) return Astro.redirect('/dashboard/clients');
<div class="form-control"> <div class="form-control">
<label class="label" for="country"> <label class="label" for="country">
<span class="label-text">Country (optional)</span> Country (optional)
</label> </label>
<input <input
type="text" type="text"

View File

@@ -2,7 +2,7 @@
import DashboardLayout from '../../../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../../../db'; import { db } from '../../../../db';
import { clients, timeEntries, members, categories, users } from '../../../../db/schema'; import { clients, timeEntries, members, tags, users } from '../../../../db/schema';
import { eq, and, desc, sql } from 'drizzle-orm'; import { eq, and, desc, sql } from 'drizzle-orm';
import { formatTimeRange } from '../../../../lib/formatTime'; import { formatTimeRange } from '../../../../lib/formatTime';
@@ -40,12 +40,12 @@ if (!client) return Astro.redirect('/dashboard/clients');
// Get recent activity // Get recent activity
const recentEntries = await db.select({ const recentEntries = await db.select({
entry: timeEntries, entry: timeEntries,
category: categories,
user: users, user: users,
tag: tags,
}) })
.from(timeEntries) .from(timeEntries)
.leftJoin(categories, eq(timeEntries.categoryId, categories.id))
.leftJoin(users, eq(timeEntries.userId, users.id)) .leftJoin(users, eq(timeEntries.userId, users.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(eq(timeEntries.clientId, client.id)) .where(eq(timeEntries.clientId, client.id))
.orderBy(desc(timeEntries.startTime)) .orderBy(desc(timeEntries.startTime))
.limit(10) .limit(10)
@@ -181,21 +181,23 @@ const totalEntriesCount = totalEntriesResult?.count || 0;
<thead> <thead>
<tr> <tr>
<th>Description</th> <th>Description</th>
<th>Category</th> <th>Tag</th>
<th>User</th> <th>User</th>
<th>Date</th> <th>Date</th>
<th>Duration</th> <th>Duration</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{recentEntries.map(({ entry, category, user: entryUser }) => ( {recentEntries.map(({ entry, tag, user: entryUser }) => (
<tr> <tr>
<td>{entry.description || '-'}</td> <td>{entry.description || '-'}</td>
<td> <td>
{category ? ( {tag ? (
<div class="flex items-center gap-2"> <div class="badge badge-sm badge-outline flex items-center gap-1">
<span class="w-2 h-2 rounded-full" style={`background-color: ${category.color}`}></span> {tag.color && (
<span>{category.name}</span> <span class="w-2 h-2 rounded-full" style={`background-color: ${tag.color}`}></span>
)}
<span>{tag.name}</span>
</div> </div>
) : '-'} ) : '-'}
</td> </td>

View File

@@ -13,7 +13,7 @@ if (!user) return Astro.redirect('/login');
<div class="card-body"> <div class="card-body">
<div class="form-control"> <div class="form-control">
<label class="label" for="name"> <label class="label" for="name">
<span class="label-text">Client Name</span> Client Name
</label> </label>
<input <input
type="text" type="text"
@@ -27,7 +27,7 @@ if (!user) return Astro.redirect('/login');
<div class="form-control"> <div class="form-control">
<label class="label" for="email"> <label class="label" for="email">
<span class="label-text">Email (optional)</span> Email (optional)
</label> </label>
<input <input
type="email" type="email"
@@ -40,7 +40,7 @@ if (!user) return Astro.redirect('/login');
<div class="form-control"> <div class="form-control">
<label class="label" for="phone"> <label class="label" for="phone">
<span class="label-text">Phone (optional)</span> Phone (optional)
</label> </label>
<input <input
type="tel" type="tel"
@@ -55,7 +55,7 @@ if (!user) return Astro.redirect('/login');
<div class="form-control"> <div class="form-control">
<label class="label" for="street"> <label class="label" for="street">
<span class="label-text">Street Address (optional)</span> Street Address (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -69,7 +69,7 @@ if (!user) return Astro.redirect('/login');
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label" for="city"> <label class="label" for="city">
<span class="label-text">City (optional)</span> City (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -82,7 +82,7 @@ if (!user) return Astro.redirect('/login');
<div class="form-control"> <div class="form-control">
<label class="label" for="state"> <label class="label" for="state">
<span class="label-text">State / Province (optional)</span> State / Province (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -97,7 +97,7 @@ if (!user) return Astro.redirect('/login');
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label" for="zip"> <label class="label" for="zip">
<span class="label-text">Zip / Postal Code (optional)</span> Zip / Postal Code (optional)
</label> </label>
<input <input
type="text" type="text"
@@ -110,7 +110,7 @@ if (!user) return Astro.redirect('/login');
<div class="form-control"> <div class="form-control">
<label class="label" for="country"> <label class="label" for="country">
<span class="label-text">Country (optional)</span> Country (optional)
</label> </label>
<input <input
type="text" type="text"

View File

@@ -2,7 +2,7 @@
import DashboardLayout from '../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../db'; import { db } from '../../db';
import { organizations, members, timeEntries, clients, categories } from '../../db/schema'; import { organizations, members, timeEntries, clients, tags } from '../../db/schema';
import { eq, desc, and, isNull, gte, sql } from 'drizzle-orm'; import { eq, desc, and, isNull, gte, sql } from 'drizzle-orm';
import { formatDuration } from '../../lib/formatTime'; import { formatDuration } from '../../lib/formatTime';
@@ -87,11 +87,11 @@ if (currentOrg) {
stats.recentEntries = await db.select({ stats.recentEntries = await db.select({
entry: timeEntries, entry: timeEntries,
client: clients, client: clients,
category: categories, tag: tags,
}) })
.from(timeEntries) .from(timeEntries)
.innerJoin(clients, eq(timeEntries.clientId, clients.id)) .innerJoin(clients, eq(timeEntries.clientId, clients.id))
.innerJoin(categories, eq(timeEntries.categoryId, categories.id)) .leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(eq(timeEntries.organizationId, currentOrg.organizationId)) .where(eq(timeEntries.organizationId, currentOrg.organizationId))
.orderBy(desc(timeEntries.startTime)) .orderBy(desc(timeEntries.startTime))
.limit(5) .limit(5)
@@ -205,11 +205,16 @@ const hasMembership = userOrgs.length > 0;
</h2> </h2>
{stats.recentEntries.length > 0 ? ( {stats.recentEntries.length > 0 ? (
<ul class="space-y-3 mt-4"> <ul class="space-y-3 mt-4">
{stats.recentEntries.map(({ entry, client, category }) => ( {stats.recentEntries.map(({ entry, client, tag }) => (
<li class="p-3 rounded-lg bg-base-200 border-l-4 hover:bg-base-300 transition-colors" style={`border-color: ${category.color || '#3b82f6'}`}> <li class="p-3 rounded-lg bg-base-200 border-l-4 hover:bg-base-300 transition-colors" style={`border-color: ${tag?.color || '#3b82f6'}`}>
<div class="font-semibold text-sm">{client.name}</div> <div class="font-semibold text-sm">{client.name}</div>
<div class="text-xs text-base-content/60 mt-1"> <div class="text-xs text-base-content/60 mt-1 flex flex-wrap gap-2 items-center">
{category.name} • {entry.endTime ? formatDuration(entry.endTime.getTime() - entry.startTime.getTime()) : 'Running...'} <span class="flex gap-1 flex-wrap">
{tag ? (
<span class="badge badge-xs badge-outline">{tag.name}</span>
) : <span class="italic opacity-50">No tag</span>}
</span>
<span>• {entry.endTime ? formatDuration(entry.endTime.getTime() - entry.startTime.getTime()) : 'Running...'}</span>
</div> </div>
</li> </li>
))} ))}

View File

@@ -263,20 +263,27 @@ const isDraft = invoice.status === 'draft';
<!-- Add Item Form (Only if Draft) --> <!-- Add Item Form (Only if Draft) -->
{isDraft && ( {isDraft && (
<div class="flex justify-end mb-4">
<button onclick="document.getElementById('import_time_modal').showModal()" class="btn btn-sm btn-outline gap-2">
<Icon name="heroicons:clock" class="w-4 h-4" />
Import Time
</button>
</div>
<form method="POST" action={`/api/invoices/${invoice.id}/items/add`} class="bg-base-200/50 p-4 rounded-lg mb-8 border border-base-300/50"> <form method="POST" action={`/api/invoices/${invoice.id}/items/add`} class="bg-base-200/50 p-4 rounded-lg mb-8 border border-base-300/50">
<h4 class="text-sm font-bold mb-3">Add Item</h4> <h4 class="text-sm font-bold mb-3">Add Item</h4>
<div class="grid grid-cols-1 sm:grid-cols-12 gap-4 items-end"> <div class="grid grid-cols-1 sm:grid-cols-12 gap-4 items-end">
<div class="sm:col-span-6"> <div class="sm:col-span-6">
<label class="label label-text text-xs pt-0">Description</label> <label class="label text-xs pt-0" for="item-description">Description</label>
<input type="text" name="description" class="input input-sm input-bordered w-full" required placeholder="Service or product..." /> <input type="text" id="item-description" name="description" class="input input-sm input-bordered w-full" required placeholder="Service or product..." />
</div> </div>
<div class="sm:col-span-2"> <div class="sm:col-span-2">
<label class="label label-text text-xs pt-0">Qty</label> <label class="label text-xs pt-0" for="item-quantity">Qty</label>
<input type="number" name="quantity" step="0.01" class="input input-sm input-bordered w-full" required value="1" /> <input type="number" id="item-quantity" name="quantity" step="0.01" class="input input-sm input-bordered w-full" required value="1" />
</div> </div>
<div class="sm:col-span-3"> <div class="sm:col-span-3">
<label class="label label-text text-xs pt-0">Unit Price ({invoice.currency})</label> <label class="label text-xs pt-0" for="item-unit-price">Unit Price ({invoice.currency})</label>
<input type="number" name="unitPrice" step="0.01" class="input input-sm input-bordered w-full" required placeholder="0.00" /> <input type="number" id="item-unit-price" name="unitPrice" step="0.01" class="input input-sm input-bordered w-full" required placeholder="0.00" />
</div> </div>
<div class="sm:col-span-1"> <div class="sm:col-span-1">
<button type="submit" class="btn btn-sm btn-primary w-full"> <button type="submit" class="btn btn-sm btn-primary w-full">
@@ -294,6 +301,15 @@ const isDraft = invoice.status === 'draft';
<span class="text-base-content/60">Subtotal</span> <span class="text-base-content/60">Subtotal</span>
<span class="font-medium">{formatCurrency(invoice.subtotal)}</span> <span class="font-medium">{formatCurrency(invoice.subtotal)}</span>
</div> </div>
{(invoice.discountAmount && invoice.discountAmount > 0) && (
<div class="flex justify-between text-sm">
<span class="text-base-content/60">
Discount
{invoice.discountType === 'percentage' && ` (${invoice.discountValue}%)`}
</span>
<span class="font-medium text-success">-{formatCurrency(invoice.discountAmount)}</span>
</div>
)}
{((invoice.taxRate ?? 0) > 0 || isDraft) && ( {((invoice.taxRate ?? 0) > 0 || isDraft) && (
<div class="flex justify-between text-sm items-center group"> <div class="flex justify-between text-sm items-center group">
<span class="text-base-content/60 flex items-center gap-2"> <span class="text-base-content/60 flex items-center gap-2">
@@ -340,11 +356,12 @@ const isDraft = invoice.status === 'draft';
<p class="py-4">Enter the tax percentage to apply to the subtotal.</p> <p class="py-4">Enter the tax percentage to apply to the subtotal.</p>
<form method="POST" action={`/api/invoices/${invoice.id}/update-tax`}> <form method="POST" action={`/api/invoices/${invoice.id}/update-tax`}>
<div class="form-control mb-6"> <div class="form-control mb-6">
<label class="label"> <label class="label" for="tax-rate">
<span class="label-text">Tax Rate (%)</span> Tax Rate (%)
</label> </label>
<input <input
type="number" type="number"
id="tax-rate"
name="taxRate" name="taxRate"
step="0.01" step="0.01"
min="0" min="0"
@@ -364,4 +381,39 @@ const isDraft = invoice.status === 'draft';
<button>close</button> <button>close</button>
</form> </form>
</dialog> </dialog>
<!-- Import Time Modal -->
<dialog id="import_time_modal" class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg">Import Time Entries</h3>
<p class="py-4">Import billable time entries for this client.</p>
<form method="POST" action={`/api/invoices/${invoice.id}/import-time`}>
<div class="grid grid-cols-2 gap-4 mb-4">
<div class="form-control">
<label class="label" for="start-date">Start Date</label>
<input type="date" id="start-date" name="startDate" class="input input-bordered" required />
</div>
<div class="form-control">
<label class="label" for="end-date">End Date</label>
<input type="date" id="end-date" name="endDate" class="input input-bordered" required />
</div>
</div>
<div class="form-control mb-6">
<label class="label cursor-pointer justify-start gap-4">
<input type="checkbox" name="groupByDay" class="checkbox" />
<span class="label-text">Group entries by day</span>
</label>
</div>
<div class="modal-action">
<button type="button" class="btn" onclick="document.getElementById('import_time_modal').close()">Cancel</button>
<button type="submit" class="btn btn-primary">Import</button>
</div>
</form>
</div>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
</DashboardLayout> </DashboardLayout>

View File

@@ -38,6 +38,10 @@ if (!membership) {
// Format dates for input[type="date"] // Format dates for input[type="date"]
const issueDateStr = invoice.issueDate.toISOString().split('T')[0]; const issueDateStr = invoice.issueDate.toISOString().split('T')[0];
const dueDateStr = invoice.dueDate.toISOString().split('T')[0]; const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
const discountValueDisplay = invoice.discountType === 'fixed'
? (invoice.discountValue || 0) / 100
: (invoice.discountValue || 0);
--- ---
<DashboardLayout title={`Edit ${invoice.number} - Chronus`}> <DashboardLayout title={`Edit ${invoice.number} - Chronus`}>
@@ -56,11 +60,12 @@ const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
<div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Number --> <!-- Number -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-number">
<span class="label-text font-semibold">Number</span> Number
</label> </label>
<input <input
type="text" type="text"
id="invoice-number"
name="number" name="number"
class="input input-bordered font-mono" class="input input-bordered font-mono"
value={invoice.number} value={invoice.number}
@@ -70,10 +75,10 @@ const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
<!-- Currency --> <!-- Currency -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-currency">
<span class="label-text font-semibold">Currency</span> Currency
</label> </label>
<select name="currency" class="select select-bordered w-full"> <select id="invoice-currency" name="currency" class="select select-bordered w-full">
<option value="USD" selected={invoice.currency === 'USD'}>USD ($)</option> <option value="USD" selected={invoice.currency === 'USD'}>USD ($)</option>
<option value="EUR" selected={invoice.currency === 'EUR'}>EUR (€)</option> <option value="EUR" selected={invoice.currency === 'EUR'}>EUR (€)</option>
<option value="GBP" selected={invoice.currency === 'GBP'}>GBP (£)</option> <option value="GBP" selected={invoice.currency === 'GBP'}>GBP (£)</option>
@@ -84,11 +89,12 @@ const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
<!-- Issue Date --> <!-- Issue Date -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-issue-date">
<span class="label-text font-semibold">Issue Date</span> Issue Date
</label> </label>
<input <input
type="date" type="date"
id="invoice-issue-date"
name="issueDate" name="issueDate"
class="input input-bordered" class="input input-bordered"
value={issueDateStr} value={issueDateStr}
@@ -98,13 +104,12 @@ const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
<!-- Due Date --> <!-- Due Date -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-due-date">
<span class="label-text font-semibold"> {invoice.type === 'quote' ? 'Valid Until' : 'Due Date'}
{invoice.type === 'quote' ? 'Valid Until' : 'Due Date'}
</span>
</label> </label>
<input <input
type="date" type="date"
id="invoice-due-date"
name="dueDate" name="dueDate"
class="input input-bordered" class="input input-bordered"
value={dueDateStr} value={dueDateStr}
@@ -112,29 +117,53 @@ const dueDateStr = invoice.dueDate.toISOString().split('T')[0];
/> />
</div> </div>
<!-- Discount -->
<div class="form-control">
<label class="label font-semibold" for="invoice-discount-type">
Discount
</label>
<div class="join w-full">
<select id="invoice-discount-type" name="discountType" class="select select-bordered join-item">
<option value="percentage" selected={!invoice.discountType || invoice.discountType === 'percentage'}>%</option>
<option value="fixed" selected={invoice.discountType === 'fixed'}>Fixed</option>
</select>
<input
type="number"
id="invoice-discount-value"
name="discountValue"
step="0.01"
min="0"
class="input input-bordered join-item w-full"
value={discountValueDisplay}
/>
</div>
</div>
<!-- Tax Rate --> <!-- Tax Rate -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-tax-rate">
<span class="label-text font-semibold">Tax Rate (%)</span> Tax Rate (%)
</label> </label>
<input <input
type="number" type="number"
name="taxRate" id="invoice-tax-rate"
step="0.01" name="taxRate"
min="0" step="0.01"
max="100" min="0"
class="input input-bordered" max="100"
value={invoice.taxRate} class="input input-bordered"
/> value={invoice.taxRate}
</div> />
</div>
</div> </div>
<!-- Notes --> <!-- Notes -->
<div class="form-control flex flex-col"> <div class="form-control flex flex-col">
<label class="label"> <label class="label font-semibold" for="invoice-notes">
<span class="label-text font-semibold">Notes / Terms</span> Notes / Terms
</label> </label>
<textarea <textarea
id="invoice-notes"
name="notes" name="notes"
class="textarea textarea-bordered h-32 font-mono text-sm" class="textarea textarea-bordered h-32 font-mono text-sm"
placeholder="Payment terms, bank details, or thank you notes..." placeholder="Payment terms, bank details, or thank you notes..."

View File

@@ -3,7 +3,7 @@ import DashboardLayout from '../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../../db'; import { db } from '../../../db';
import { invoices, clients, members } from '../../../db/schema'; import { invoices, clients, members } from '../../../db/schema';
import { eq, desc, and } from 'drizzle-orm'; import { eq, desc, and, gte, lte, sql } from 'drizzle-orm';
const user = Astro.locals.user; const user = Astro.locals.user;
if (!user) return Astro.redirect('/login'); if (!user) return Astro.redirect('/login');
@@ -25,17 +25,77 @@ const userMembership = currentTeamId
const currentTeamIdResolved = userMembership.organizationId; const currentTeamIdResolved = userMembership.organizationId;
// Fetch invoices and quotes // Get filter parameters
const allInvoices = await db.select({ const currentYear = new Date().getFullYear();
const yearParam = Astro.url.searchParams.get('year');
const selectedYear = yearParam === 'current' || !yearParam ? 'current' : parseInt(yearParam);
const selectedType = Astro.url.searchParams.get('type') || 'all';
const selectedStatus = Astro.url.searchParams.get('status') || 'all';
const sortBy = Astro.url.searchParams.get('sort') || 'date-desc';
// Fetch all invoices for the organization (for year dropdown)
const allInvoicesRaw = await db.select({
invoice: invoices, invoice: invoices,
client: clients, client: clients,
}) })
.from(invoices) .from(invoices)
.leftJoin(clients, eq(invoices.clientId, clients.id)) .leftJoin(clients, eq(invoices.clientId, clients.id))
.where(eq(invoices.organizationId, currentTeamIdResolved)) .where(eq(invoices.organizationId, currentTeamIdResolved))
.orderBy(desc(invoices.issueDate))
.all(); .all();
// Get unique years from invoices
const availableYears = [...new Set(allInvoicesRaw.map(i => i.invoice.issueDate.getFullYear()))].sort((a, b) => b - a);
// Ensure current year is in the list
if (!availableYears.includes(currentYear)) {
availableYears.unshift(currentYear);
}
// Filter by year
const yearStart = selectedYear === 'current' ? new Date(currentYear, 0, 1) : new Date(selectedYear, 0, 1);
const yearEnd = selectedYear === 'current' ? new Date() : new Date(selectedYear, 11, 31, 23, 59, 59);
let filteredInvoices = allInvoicesRaw.filter(i => {
const issueDate = i.invoice.issueDate;
return issueDate >= yearStart && issueDate <= yearEnd;
});
// Filter by type
if (selectedType !== 'all') {
filteredInvoices = filteredInvoices.filter(i => i.invoice.type === selectedType);
}
// Filter by status
if (selectedStatus !== 'all') {
filteredInvoices = filteredInvoices.filter(i => i.invoice.status === selectedStatus);
}
// Sort invoices
const allInvoices = filteredInvoices.sort((a, b) => {
switch (sortBy) {
case 'date-desc':
return b.invoice.issueDate.getTime() - a.invoice.issueDate.getTime();
case 'date-asc':
return a.invoice.issueDate.getTime() - b.invoice.issueDate.getTime();
case 'amount-desc':
return b.invoice.total - a.invoice.total;
case 'amount-asc':
return a.invoice.total - b.invoice.total;
case 'number-desc':
return b.invoice.number.localeCompare(a.invoice.number);
case 'number-asc':
return a.invoice.number.localeCompare(b.invoice.number);
default:
return b.invoice.issueDate.getTime() - a.invoice.issueDate.getTime();
}
});
// Calculate stats for the selected year
const yearInvoices = allInvoicesRaw.filter(i => {
const issueDate = i.invoice.issueDate;
return issueDate >= yearStart && issueDate <= yearEnd;
});
const formatCurrency = (amount: number, currency: string) => { const formatCurrency = (amount: number, currency: string) => {
return new Intl.NumberFormat('en-US', { return new Intl.NumberFormat('en-US', {
style: 'currency', style: 'currency',
@@ -75,8 +135,8 @@ const getStatusColor = (status: string) => {
<Icon name="heroicons:document-text" class="w-8 h-8" /> <Icon name="heroicons:document-text" class="w-8 h-8" />
</div> </div>
<div class="stat-title">Total Invoices</div> <div class="stat-title">Total Invoices</div>
<div class="stat-value text-primary">{allInvoices.filter(i => i.invoice.type === 'invoice').length}</div> <div class="stat-value text-primary">{yearInvoices.filter(i => i.invoice.type === 'invoice').length}</div>
<div class="stat-desc">All time</div> <div class="stat-desc">{selectedYear === 'current' ? `${currentYear} (YTD)` : selectedYear}</div>
</div> </div>
</div> </div>
@@ -86,7 +146,7 @@ const getStatusColor = (status: string) => {
<Icon name="heroicons:clipboard-document-list" class="w-8 h-8" /> <Icon name="heroicons:clipboard-document-list" class="w-8 h-8" />
</div> </div>
<div class="stat-title">Open Quotes</div> <div class="stat-title">Open Quotes</div>
<div class="stat-value text-secondary">{allInvoices.filter(i => i.invoice.type === 'quote' && i.invoice.status === 'sent').length}</div> <div class="stat-value text-secondary">{yearInvoices.filter(i => i.invoice.type === 'quote' && i.invoice.status === 'sent').length}</div>
<div class="stat-desc">Waiting for approval</div> <div class="stat-desc">Waiting for approval</div>
</div> </div>
</div> </div>
@@ -98,17 +158,92 @@ const getStatusColor = (status: string) => {
</div> </div>
<div class="stat-title">Total Revenue</div> <div class="stat-title">Total Revenue</div>
<div class="stat-value text-success"> <div class="stat-value text-success">
{formatCurrency(allInvoices {formatCurrency(yearInvoices
.filter(i => i.invoice.type === 'invoice' && i.invoice.status === 'paid') .filter(i => i.invoice.type === 'invoice' && i.invoice.status === 'paid')
.reduce((acc, curr) => acc + curr.invoice.total, 0), 'USD')} .reduce((acc, curr) => acc + curr.invoice.total, 0), 'USD')}
</div> </div>
<div class="stat-desc">Paid invoices</div> <div class="stat-desc">Paid invoices ({selectedYear === 'current' ? `${currentYear} YTD` : selectedYear})</div>
</div> </div>
</div> </div>
</div> </div>
<!-- Filters -->
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body">
<form method="GET" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Year</span>
</label>
<select name="year" class="select select-bordered w-full" onchange="this.form.submit()">
<option value="current" selected={selectedYear === 'current'}>Current Year to Date ({currentYear})</option>
{availableYears.map(year => (
<option value={year} selected={year === selectedYear}>{year}</option>
))}
</select>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Type</span>
</label>
<select name="type" class="select select-bordered w-full" onchange="this.form.submit()">
<option value="all" selected={selectedType === 'all'}>All Types</option>
<option value="invoice" selected={selectedType === 'invoice'}>Invoices</option>
<option value="quote" selected={selectedType === 'quote'}>Quotes</option>
</select>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Status</span>
</label>
<select name="status" class="select select-bordered w-full" onchange="this.form.submit()">
<option value="all" selected={selectedStatus === 'all'}>All Statuses</option>
<option value="draft" selected={selectedStatus === 'draft'}>Draft</option>
<option value="sent" selected={selectedStatus === 'sent'}>Sent</option>
<option value="paid" selected={selectedStatus === 'paid'}>Paid</option>
<option value="accepted" selected={selectedStatus === 'accepted'}>Accepted</option>
<option value="declined" selected={selectedStatus === 'declined'}>Declined</option>
<option value="void" selected={selectedStatus === 'void'}>Void</option>
</select>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Sort By</span>
</label>
<select name="sort" class="select select-bordered w-full" onchange="this.form.submit()">
<option value="date-desc" selected={sortBy === 'date-desc'}>Date (Newest First)</option>
<option value="date-asc" selected={sortBy === 'date-asc'}>Date (Oldest First)</option>
<option value="amount-desc" selected={sortBy === 'amount-desc'}>Amount (High to Low)</option>
<option value="amount-asc" selected={sortBy === 'amount-asc'}>Amount (Low to High)</option>
<option value="number-desc" selected={sortBy === 'number-desc'}>Number (Z-A)</option>
<option value="number-asc" selected={sortBy === 'number-asc'}>Number (A-Z)</option>
</select>
</div>
</form>
{(selectedYear !== 'current' || selectedType !== 'all' || selectedStatus !== 'all' || sortBy !== 'date-desc') && (
<div class="mt-4">
<a href="/dashboard/invoices" class="btn btn-ghost btn-sm">
<Icon name="heroicons:x-mark" class="w-4 h-4" />
Clear Filters
</a>
</div>
)}
</div>
</div>
<div class="card bg-base-100 shadow-xl border border-base-200"> <div class="card bg-base-100 shadow-xl border border-base-200">
<div class="card-body p-0"> <div class="card-body p-0">
<div class="px-6 py-4 border-b border-base-200 bg-base-200/30">
<p class="text-sm text-base-content/70">
Showing <span class="font-semibold text-base-content">{allInvoices.length}</span>
{allInvoices.length === 1 ? 'result' : 'results'}
{selectedYear === 'current' ? ` for ${currentYear} (year to date)` : ` for ${selectedYear}`}
</p>
</div>
<div class="overflow-x-auto md:overflow-visible pb-32 md:pb-0"> <div class="overflow-x-auto md:overflow-visible pb-32 md:pb-0">
<table class="table table-zebra"> <table class="table table-zebra">
<thead> <thead>

View File

@@ -2,7 +2,7 @@
import DashboardLayout from '../../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../../db'; import { db } from '../../../db';
import { clients, members, invoices } from '../../../db/schema'; import { clients, members, invoices, organizations } from '../../../db/schema';
import { eq, desc, and } from 'drizzle-orm'; import { eq, desc, and } from 'drizzle-orm';
const user = Astro.locals.user; const user = Astro.locals.user;
@@ -25,6 +25,11 @@ const userMembership = currentTeamId
const currentTeamIdResolved = userMembership.organizationId; const currentTeamIdResolved = userMembership.organizationId;
const currentOrganization = await db.select()
.from(organizations)
.where(eq(organizations.id, currentTeamIdResolved))
.get();
// Fetch clients for dropdown // Fetch clients for dropdown
const teamClients = await db.select() const teamClients = await db.select()
.from(clients) .from(clients)
@@ -108,17 +113,17 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<!-- Document Type --> <!-- Document Type -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="document-type-invoice">
<span class="label-text font-semibold">Document Type</span> Document Type
</label> </label>
<div class="flex gap-4"> <div class="flex gap-4">
<label class="label cursor-pointer justify-start gap-2 border border-base-300 rounded-lg p-3 flex-1 hover:border-primary has-checked:border-primary has-checked:bg-primary/5 transition-all"> <label class="label cursor-pointer justify-start gap-2 border border-base-300 rounded-lg p-3 flex-1 hover:border-primary has-checked:border-primary has-checked:bg-primary/5 transition-all font-medium" for="document-type-invoice">
<input type="radio" name="type" value="invoice" class="radio radio-primary" checked /> <input type="radio" id="document-type-invoice" name="type" value="invoice" class="radio radio-primary" checked />
<span class="label-text font-medium">Invoice</span> Invoice
</label> </label>
<label class="label cursor-pointer justify-start gap-2 border border-base-300 rounded-lg p-3 flex-1 hover:border-primary has-checked:border-primary has-checked:bg-primary/5 transition-all"> <label class="label cursor-pointer justify-start gap-2 border border-base-300 rounded-lg p-3 flex-1 hover:border-primary has-checked:border-primary has-checked:bg-primary/5 transition-all font-medium" for="document-type-quote">
<input type="radio" name="type" value="quote" class="radio radio-primary" /> <input type="radio" id="document-type-quote" name="type" value="quote" class="radio radio-primary" />
<span class="label-text font-medium">Quote / Estimate</span> Quote / Estimate
</label> </label>
</div> </div>
</div> </div>
@@ -126,10 +131,10 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Client --> <!-- Client -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-client">
<span class="label-text font-semibold">Client</span> Client
</label> </label>
<select name="clientId" class="select select-bordered w-full" required> <select id="invoice-client" name="clientId" class="select select-bordered w-full" required>
<option value="" disabled selected>Select a client...</option> <option value="" disabled selected>Select a client...</option>
{teamClients.map(client => ( {teamClients.map(client => (
<option value={client.id}>{client.name}</option> <option value={client.id}>{client.name}</option>
@@ -139,8 +144,8 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<!-- Number --> <!-- Number -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="documentNumber">
<span class="label-text font-semibold">Number</span> Number
</label> </label>
<input <input
type="text" type="text"
@@ -156,11 +161,12 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<!-- Issue Date --> <!-- Issue Date -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-issue-date">
<span class="label-text font-semibold">Issue Date</span> Issue Date
</label> </label>
<input <input
type="date" type="date"
id="invoice-issue-date"
name="issueDate" name="issueDate"
class="input input-bordered" class="input input-bordered"
value={today} value={today}
@@ -170,11 +176,12 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<!-- Due Date --> <!-- Due Date -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-due-date" id="dueDateLabel">
<span class="label-text font-semibold" id="dueDateLabel">Due Date</span> Due Date
</label> </label>
<input <input
type="date" type="date"
id="invoice-due-date"
name="dueDate" name="dueDate"
class="input input-bordered" class="input input-bordered"
value={defaultDueDate} value={defaultDueDate}
@@ -184,15 +191,15 @@ const defaultDueDate = nextMonth.toISOString().split('T')[0];
<!-- Currency --> <!-- Currency -->
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-semibold" for="invoice-currency">
<span class="label-text font-semibold">Currency</span> Currency
</label> </label>
<select name="currency" class="select select-bordered w-full"> <select id="invoice-currency" name="currency" class="select select-bordered w-full">
<option value="USD">USD ($)</option> <option value="USD" selected={currentOrganization?.defaultCurrency === 'USD'}>USD ($)</option>
<option value="EUR">EUR (€)</option> <option value="EUR" selected={currentOrganization?.defaultCurrency === 'EUR'}>EUR (€)</option>
<option value="GBP">GBP (£)</option> <option value="GBP" selected={currentOrganization?.defaultCurrency === 'GBP'}>GBP (£)</option>
<option value="CAD">CAD ($)</option> <option value="CAD" selected={currentOrganization?.defaultCurrency === 'CAD'}>CAD ($)</option>
<option value="AUD">AUD ($)</option> <option value="AUD" selected={currentOrganization?.defaultCurrency === 'AUD'}>AUD ($)</option>
</select> </select>
</div> </div>
</div> </div>

View File

@@ -17,7 +17,7 @@ if (!user) return Astro.redirect('/login');
</a> </a>
<h1 class="text-3xl font-bold">Create New Team</h1> <h1 class="text-3xl font-bold">Create New Team</h1>
</div> </div>
<form method="POST" action="/api/organizations/create" class="card bg-base-200 shadow-xl border border-base-300"> <form method="POST" action="/api/organizations/create" class="card bg-base-200 shadow-xl border border-base-300">
<div class="card-body"> <div class="card-body">
<div class="alert alert-info mb-4"> <div class="alert alert-info mb-4">
@@ -26,16 +26,16 @@ if (!user) return Astro.redirect('/login');
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label pb-2" for="name"> <label class="label pb-2 font-medium" for="name">
<span class="label-text font-medium">Team Name</span> Team Name
</label> </label>
<input <input
type="text" type="text"
id="name" id="name"
name="name" name="name"
placeholder="Acme Corp" placeholder="Acme Corp"
class="input input-bordered w-full" class="input input-bordered w-full"
required required
/> />
</div> </div>

View File

@@ -1,11 +1,11 @@
--- ---
import DashboardLayout from '../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import CategoryChart from '../../components/CategoryChart.vue'; import TagChart from '../../components/TagChart.vue';
import ClientChart from '../../components/ClientChart.vue'; import ClientChart from '../../components/ClientChart.vue';
import MemberChart from '../../components/MemberChart.vue'; import MemberChart from '../../components/MemberChart.vue';
import { db } from '../../db'; import { db } from '../../db';
import { timeEntries, members, users, clients, categories, invoices } from '../../db/schema'; import { timeEntries, members, users, clients, tags, invoices } from '../../db/schema';
import { eq, and, gte, lte, sql, desc } from 'drizzle-orm'; import { eq, and, gte, lte, sql, desc } from 'drizzle-orm';
import { formatDuration, formatTimeRange } from '../../lib/formatTime'; import { formatDuration, formatTimeRange } from '../../lib/formatTime';
@@ -37,9 +37,9 @@ const teamMembers = await db.select({
.where(eq(members.organizationId, userMembership.organizationId)) .where(eq(members.organizationId, userMembership.organizationId))
.all(); .all();
const allCategories = await db.select() const allTags = await db.select()
.from(categories) .from(tags)
.where(eq(categories.organizationId, userMembership.organizationId)) .where(eq(tags.organizationId, userMembership.organizationId))
.all(); .all();
const allClients = await db.select() const allClients = await db.select()
@@ -49,9 +49,11 @@ const allClients = await db.select()
const url = new URL(Astro.request.url); const url = new URL(Astro.request.url);
const selectedMemberId = url.searchParams.get('member') || ''; const selectedMemberId = url.searchParams.get('member') || '';
const selectedCategoryId = url.searchParams.get('category') || ''; const selectedTagId = url.searchParams.get('tag') || '';
const selectedClientId = url.searchParams.get('client') || ''; const selectedClientId = url.searchParams.get('client') || '';
const timeRange = url.searchParams.get('range') || 'week'; const timeRange = url.searchParams.get('range') || 'week';
const customFrom = url.searchParams.get('from');
const customTo = url.searchParams.get('to');
const now = new Date(); const now = new Date();
let startDate = new Date(); let startDate = new Date();
@@ -78,6 +80,16 @@ switch (timeRange) {
startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1); startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
endDate = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999); endDate = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
break; break;
case 'custom':
if (customFrom) {
const parts = customFrom.split('-');
startDate = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 0, 0, 0, 0);
}
if (customTo) {
const parts = customTo.split('-');
endDate = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]), 23, 59, 59, 999);
}
break;
} }
const conditions = [ const conditions = [
@@ -90,8 +102,8 @@ if (selectedMemberId) {
conditions.push(eq(timeEntries.userId, selectedMemberId)); conditions.push(eq(timeEntries.userId, selectedMemberId));
} }
if (selectedCategoryId) { if (selectedTagId) {
conditions.push(eq(timeEntries.categoryId, selectedCategoryId)); conditions.push(eq(timeEntries.tagId, selectedTagId));
} }
if (selectedClientId) { if (selectedClientId) {
@@ -102,12 +114,12 @@ const entries = await db.select({
entry: timeEntries, entry: timeEntries,
user: users, user: users,
client: clients, client: clients,
category: categories, tag: tags,
}) })
.from(timeEntries) .from(timeEntries)
.innerJoin(users, eq(timeEntries.userId, users.id)) .innerJoin(users, eq(timeEntries.userId, users.id))
.innerJoin(clients, eq(timeEntries.clientId, clients.id)) .innerJoin(clients, eq(timeEntries.clientId, clients.id))
.innerJoin(categories, eq(timeEntries.categoryId, categories.id)) .leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and(...conditions)) .where(and(...conditions))
.orderBy(desc(timeEntries.startTime)) .orderBy(desc(timeEntries.startTime))
.all(); .all();
@@ -128,9 +140,9 @@ const statsByMember = teamMembers.map(member => {
}; };
}).sort((a, b) => b.totalTime - a.totalTime); }).sort((a, b) => b.totalTime - a.totalTime);
const statsByCategory = allCategories.map(category => { const statsByTag = allTags.map(tag => {
const categoryEntries = entries.filter(e => e.category.id === category.id); const tagEntries = entries.filter(e => e.tag?.id === tag.id);
const totalTime = categoryEntries.reduce((sum, e) => { const totalTime = tagEntries.reduce((sum, e) => {
if (e.entry.endTime) { if (e.entry.endTime) {
return sum + (e.entry.endTime.getTime() - e.entry.startTime.getTime()); return sum + (e.entry.endTime.getTime() - e.entry.startTime.getTime());
} }
@@ -138,9 +150,9 @@ const statsByCategory = allCategories.map(category => {
}, 0); }, 0);
return { return {
category, tag,
totalTime, totalTime,
entryCount: categoryEntries.length, entryCount: tagEntries.length,
}; };
}).sort((a, b) => b.totalTime - a.totalTime); }).sort((a, b) => b.totalTime - a.totalTime);
@@ -250,6 +262,7 @@ function getTimeRangeLabel(range: string) {
case 'mtd': return 'Month to Date'; case 'mtd': return 'Month to Date';
case 'ytd': return 'Year to Date'; case 'ytd': return 'Year to Date';
case 'last-month': return 'Last Month'; case 'last-month': return 'Last Month';
case 'custom': return 'Custom Range';
default: return 'Last 7 Days'; default: return 'Last 7 Days';
} }
} }
@@ -263,24 +276,56 @@ function getTimeRangeLabel(range: string) {
<div class="card-body"> <div class="card-body">
<form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"> <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="reports-range">
<span class="label-text font-medium">Time Range</span> Time Range
</label> </label>
<select name="range" class="select select-bordered" onchange="this.form.submit()"> <select id="reports-range" name="range" class="select select-bordered" onchange="this.form.submit()">
<option value="today" selected={timeRange === 'today'}>Today</option> <option value="today" selected={timeRange === 'today'}>Today</option>
<option value="week" selected={timeRange === 'week'}>Last 7 Days</option> <option value="week" selected={timeRange === 'week'}>Last 7 Days</option>
<option value="month" selected={timeRange === 'month'}>Last 30 Days</option> <option value="month" selected={timeRange === 'month'}>Last 30 Days</option>
<option value="mtd" selected={timeRange === 'mtd'}>Month to Date</option> <option value="mtd" selected={timeRange === 'mtd'}>Month to Date</option>
<option value="ytd" selected={timeRange === 'ytd'}>Year to Date</option> <option value="ytd" selected={timeRange === 'ytd'}>Year to Date</option>
<option value="last-month" selected={timeRange === 'last-month'}>Last Month</option> <option value="last-month" selected={timeRange === 'last-month'}>Last Month</option>
<option value="custom" selected={timeRange === 'custom'}>Custom Range</option>
</select> </select>
</div> </div>
{timeRange === 'custom' && (
<>
<div class="form-control">
<label class="label font-medium" for="reports-from">
From Date
</label>
<input
type="date"
id="reports-from"
name="from"
class="input input-bordered w-full"
value={customFrom || (startDate.getFullYear() + '-' + String(startDate.getMonth() + 1).padStart(2, '0') + '-' + String(startDate.getDate()).padStart(2, '0'))}
onchange="this.form.submit()"
/>
</div>
<div class="form-control">
<label class="label font-medium" for="reports-to">
To Date
</label>
<input
type="date"
id="reports-to"
name="to"
class="input input-bordered w-full"
value={customTo || (endDate.getFullYear() + '-' + String(endDate.getMonth() + 1).padStart(2, '0') + '-' + String(endDate.getDate()).padStart(2, '0'))}
onchange="this.form.submit()"
/>
</div>
</>
)}
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="reports-member">
<span class="label-text font-medium">Team Member</span> Team Member
</label> </label>
<select name="member" class="select select-bordered" onchange="this.form.submit()"> <select id="reports-member" name="member" class="select select-bordered" onchange="this.form.submit()">
<option value="">All Members</option> <option value="">All Members</option>
{teamMembers.map(member => ( {teamMembers.map(member => (
<option value={member.id} selected={selectedMemberId === member.id}> <option value={member.id} selected={selectedMemberId === member.id}>
@@ -291,24 +336,24 @@ function getTimeRangeLabel(range: string) {
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="reports-tag">
<span class="label-text font-medium">Category</span> Tag
</label> </label>
<select name="category" class="select select-bordered" onchange="this.form.submit()"> <select id="reports-tag" name="tag" class="select select-bordered" onchange="this.form.submit()">
<option value="">All Categories</option> <option value="">All Tags</option>
{allCategories.map(category => ( {allTags.map(tag => (
<option value={category.id} selected={selectedCategoryId === category.id}> <option value={tag.id} selected={selectedTagId === tag.id}>
{category.name} {tag.name}
</option> </option>
))} ))}
</select> </select>
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="reports-client">
<span class="label-text font-medium">Client</span> Client
</label> </label>
<select name="client" class="select select-bordered" onchange="this.form.submit()"> <select id="reports-client" name="client" class="select select-bordered" onchange="this.form.submit()">
<option value="">All Clients</option> <option value="">All Clients</option>
{allClients.map(client => ( {allClients.map(client => (
<option value={client.id} selected={selectedClientId === client.id}> <option value={client.id} selected={selectedClientId === client.id}>
@@ -328,7 +373,7 @@ function getTimeRangeLabel(range: string) {
width: 100%; width: 100%;
} }
} }
select { select, input {
width: 100%; width: 100%;
} }
</style> </style>
@@ -501,21 +546,21 @@ function getTimeRangeLabel(range: string) {
{totalTime > 0 && ( {totalTime > 0 && (
<> <>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
{/* Category Distribution Chart - Only show when no category filter */} {/* Tag Distribution Chart - Only show when no tag filter */}
{!selectedCategoryId && statsByCategory.filter(s => s.totalTime > 0).length > 0 && ( {!selectedTagId && statsByTag.filter(s => s.totalTime > 0).length > 0 && (
<div class="card bg-base-100 shadow-xl border border-base-200"> <div class="card bg-base-100 shadow-xl border border-base-200">
<div class="card-body"> <div class="card-body">
<h2 class="card-title mb-4"> <h2 class="card-title mb-4">
<Icon name="heroicons:chart-pie" class="w-6 h-6" /> <Icon name="heroicons:chart-pie" class="w-6 h-6" />
Category Distribution Tag Distribution
</h2> </h2>
<div class="h-64 w-full"> <div class="h-64 w-full">
<CategoryChart <TagChart
client:load client:visible
categories={statsByCategory.filter(s => s.totalTime > 0).map(s => ({ tags={statsByTag.filter(s => s.totalTime > 0).map(s => ({
name: s.category.name, name: s.tag.name,
totalTime: s.totalTime, totalTime: s.totalTime,
color: s.category.color || '#3b82f6' color: s.tag.color || '#3b82f6'
}))} }))}
/> />
</div> </div>
@@ -533,7 +578,7 @@ function getTimeRangeLabel(range: string) {
</h2> </h2>
<div class="h-64 w-full"> <div class="h-64 w-full">
<ClientChart <ClientChart
client:load client:visible
clients={statsByClient.filter(s => s.totalTime > 0).map(s => ({ clients={statsByClient.filter(s => s.totalTime > 0).map(s => ({
name: s.client.name, name: s.client.name,
totalTime: s.totalTime totalTime: s.totalTime
@@ -555,7 +600,7 @@ function getTimeRangeLabel(range: string) {
</h2> </h2>
<div class="h-64 w-full"> <div class="h-64 w-full">
<MemberChart <MemberChart
client:load client:visible
members={statsByMember.filter(s => s.totalTime > 0).map(s => ({ members={statsByMember.filter(s => s.totalTime > 0).map(s => ({
name: s.member.name, name: s.member.name,
totalTime: s.totalTime totalTime: s.totalTime
@@ -609,33 +654,33 @@ function getTimeRangeLabel(range: string) {
</div> </div>
)} )}
{/* Stats by Category - Only show if there's data and no category filter */} {/* Stats by Tag - Only show if there's data and no tag filter */}
{!selectedCategoryId && statsByCategory.filter(s => s.totalTime > 0).length > 0 && ( {!selectedTagId && statsByTag.filter(s => s.totalTime > 0).length > 0 && (
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6"> <div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body"> <div class="card-body">
<h2 class="card-title mb-4"> <h2 class="card-title mb-4">
<Icon name="heroicons:tag" class="w-6 h-6" /> <Icon name="heroicons:tag" class="w-6 h-6" />
By Category By Tag
</h2> </h2>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Category</th> <th>Tag</th>
<th>Total Time</th> <th>Total Time</th>
<th>Entries</th> <th>Entries</th>
<th>% of Total</th> <th>% of Total</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{statsByCategory.filter(s => s.totalTime > 0).map(stat => ( {statsByTag.filter(s => s.totalTime > 0).map(stat => (
<tr> <tr>
<td> <td>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
{stat.category.color && ( {stat.tag.color && (
<span class="w-4 h-4 rounded-full" style={`background-color: ${stat.category.color}`}></span> <span class="w-4 h-4 rounded-full" style={`background-color: ${stat.tag.color}`}></span>
)} )}
<span>{stat.category.name}</span> <span>{stat.tag.name}</span>
</div> </div>
</td> </td>
<td class="font-mono">{formatDuration(stat.totalTime)}</td> <td class="font-mono">{formatDuration(stat.totalTime)}</td>
@@ -709,10 +754,18 @@ function getTimeRangeLabel(range: string) {
{/* Detailed Entries */} {/* Detailed Entries */}
<div class="card bg-base-100 shadow-xl border border-base-200"> <div class="card bg-base-100 shadow-xl border border-base-200">
<div class="card-body"> <div class="card-body">
<h2 class="card-title mb-4"> <div class="flex justify-between items-center mb-4">
<Icon name="heroicons:document-text" class="w-6 h-6" /> <h2 class="card-title">
Detailed Entries ({entries.length}) <Icon name="heroicons:document-text" class="w-6 h-6" />
</h2> Detailed Entries ({entries.length})
</h2>
{entries.length > 0 && (
<a href={`/api/reports/export${url.search}`} class="btn btn-sm btn-outline" target="_blank">
<Icon name="heroicons:arrow-down-tray" class="w-4 h-4" />
Export CSV
</a>
)}
</div>
{entries.length > 0 ? ( {entries.length > 0 ? (
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table table-zebra"> <table class="table table-zebra">
@@ -721,7 +774,7 @@ function getTimeRangeLabel(range: string) {
<th>Date</th> <th>Date</th>
<th>Member</th> <th>Member</th>
<th>Client</th> <th>Client</th>
<th>Category</th> <th>Tag</th>
<th>Description</th> <th>Description</th>
<th>Duration</th> <th>Duration</th>
</tr> </tr>
@@ -738,12 +791,16 @@ function getTimeRangeLabel(range: string) {
<td>{e.user.name}</td> <td>{e.user.name}</td>
<td>{e.client.name}</td> <td>{e.client.name}</td>
<td> <td>
<div class="flex items-center gap-2"> {e.tag ? (
{e.category.color && ( <div class="badge badge-sm badge-outline flex items-center gap-1">
<span class="w-3 h-3 rounded-full" style={`background-color: ${e.category.color}`}></span> {e.tag.color && (
)} <span class="w-2 h-2 rounded-full" style={`background-color: ${e.tag.color}`}></span>
<span>{e.category.name}</span> )}
</div> <span>{e.tag.name}</span>
</div>
) : (
<span class="opacity-50">-</span>
)}
</td> </td>
<td>{e.entry.description || '-'}</td> <td>{e.entry.description || '-'}</td>
<td class="font-mono"> <td class="font-mono">

View File

@@ -2,8 +2,12 @@
import DashboardLayout from '../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../db'; import { db } from '../../db';
import { apiTokens } from '../../db/schema'; import { apiTokens, passkeys } from '../../db/schema';
import { eq, desc } from 'drizzle-orm'; import { eq, desc } from 'drizzle-orm';
import ProfileForm from '../../components/settings/ProfileForm.vue';
import PasswordForm from '../../components/settings/PasswordForm.vue';
import ApiTokenManager from '../../components/settings/ApiTokenManager.vue';
import PasskeyManager from '../../components/settings/PasskeyManager.vue';
const user = Astro.locals.user; const user = Astro.locals.user;
if (!user) return Astro.redirect('/login'); if (!user) return Astro.redirect('/login');
@@ -16,6 +20,12 @@ const userTokens = await db.select()
.where(eq(apiTokens.userId, user.id)) .where(eq(apiTokens.userId, user.id))
.orderBy(desc(apiTokens.createdAt)) .orderBy(desc(apiTokens.createdAt))
.all(); .all();
const userPasskeys = await db.select()
.from(passkeys)
.where(eq(passkeys.userId, user.id))
.orderBy(desc(passkeys.createdAt))
.all();
--- ---
<DashboardLayout title="Account Settings - Chronus"> <DashboardLayout title="Account Settings - Chronus">
@@ -40,177 +50,25 @@ const userTokens = await db.select()
)} )}
<!-- Profile Information --> <!-- Profile Information -->
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6"> <ProfileForm client:load user={user} />
<div class="card-body p-4 sm:p-6">
<h2 class="card-title mb-6 text-lg sm:text-xl">
<Icon name="heroicons:user-circle" class="w-5 h-5 sm:w-6 sm:h-6" />
Profile Information
</h2>
<form action="/api/user/update-profile" method="POST" class="space-y-5">
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium text-sm sm:text-base">Full Name</span>
</label>
<input
type="text"
name="name"
value={user.name}
placeholder="Your full name"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium text-sm sm:text-base">Email</span>
</label>
<input
type="email"
name="email"
value={user.email}
placeholder="your@email.com"
class="input input-bordered w-full"
disabled
/>
<div class="label pt-2">
<span class="label-text-alt text-base-content/60 text-xs sm:text-sm">Email cannot be changed</span>
</div>
</div>
<div class="flex justify-end pt-4">
<button type="submit" class="btn btn-primary w-full sm:w-auto">
<Icon name="heroicons:check" class="w-5 h-5" />
Save Changes
</button>
</div>
</form>
</div>
</div>
<!-- Change Password --> <!-- Change Password -->
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6"> <PasswordForm client:load />
<div class="card-body p-4 sm:p-6">
<h2 class="card-title mb-6 text-lg sm:text-xl">
<Icon name="heroicons:key" class="w-5 h-5 sm:w-6 sm:h-6" />
Change Password
</h2>
<form action="/api/user/change-password" method="POST" class="space-y-5"> <!-- Passkeys -->
<div class="form-control"> <PasskeyManager client:idle initialPasskeys={userPasskeys.map(pk => ({
<label class="label pb-2"> ...pk,
<span class="label-text font-medium text-sm sm:text-base">Current Password</span> lastUsedAt: pk.lastUsedAt ? pk.lastUsedAt.toISOString() : null,
</label> createdAt: pk.createdAt ? pk.createdAt.toISOString() : null
<input }))} />
type="password"
name="currentPassword"
placeholder="Enter current password"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium text-sm sm:text-base">New Password</span>
</label>
<input
type="password"
name="newPassword"
placeholder="Enter new password"
class="input input-bordered w-full"
required
minlength="8"
/>
<div class="label pt-2">
<span class="label-text-alt text-base-content/60 text-xs sm:text-sm">Minimum 8 characters</span>
</div>
</div>
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium text-sm sm:text-base">Confirm New Password</span>
</label>
<input
type="password"
name="confirmPassword"
placeholder="Confirm new password"
class="input input-bordered w-full"
required
minlength="8"
/>
</div>
<div class="flex justify-end pt-4">
<button type="submit" class="btn btn-primary w-full sm:w-auto">
<Icon name="heroicons:lock-closed" class="w-5 h-5" />
Update Password
</button>
</div>
</form>
</div>
</div>
<!-- API Tokens --> <!-- API Tokens -->
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6"> <ApiTokenManager client:idle initialTokens={userTokens.map(t => ({
<div class="card-body p-4 sm:p-6"> ...t,
<div class="flex justify-between items-center mb-6"> lastUsedAt: t.lastUsedAt ? t.lastUsedAt.toISOString() : null,
<h2 class="card-title text-lg sm:text-xl"> createdAt: t.createdAt ? t.createdAt.toISOString() : ''
<Icon name="heroicons:code-bracket-square" class="w-5 h-5 sm:w-6 sm:h-6" /> }))} />
API Tokens
</h2>
<button class="btn btn-primary btn-sm" onclick="createTokenModal.showModal()">
<Icon name="heroicons:plus" class="w-4 h-4" />
Create Token
</button>
</div>
<div class="overflow-x-auto">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Last Used</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{userTokens.length === 0 ? (
<tr>
<td colspan="4" class="text-center text-base-content/60 py-4">
No API tokens found. Create one to access the API.
</td>
</tr>
) : (
userTokens.map(token => (
<tr>
<td class="font-medium">{token.name}</td>
<td class="text-sm">
{token.lastUsedAt ? token.lastUsedAt.toLocaleDateString() : 'Never'}
</td>
<td class="text-sm">
{token.createdAt ? token.createdAt.toLocaleDateString() : 'N/A'}
</td>
<td>
<button
class="btn btn-ghost btn-xs text-error"
onclick={`deleteToken('${token.id}')`}
>
<Icon name="heroicons:trash" class="w-4 h-4" />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
<!-- Account Info -->
<div class="card bg-base-100 shadow-xl border border-base-200"> <div class="card bg-base-100 shadow-xl border border-base-200">
<div class="card-body p-4 sm:p-6"> <div class="card-body p-4 sm:p-6">
<h2 class="card-title mb-6 text-lg sm:text-xl"> <h2 class="card-title mb-6 text-lg sm:text-xl">
@@ -238,132 +96,5 @@ const userTokens = await db.select()
</div> </div>
</div> </div>
<!-- Create Token Modal -->
<dialog id="createTokenModal" class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg">Create API Token</h3>
<p class="py-4 text-sm text-base-content/70">
API tokens allow you to authenticate with the API programmatically.
Give your token a descriptive name.
</p>
<form id="createTokenForm" method="dialog" class="space-y-4">
<div class="form-control">
<label class="label pb-2">
<span class="label-text font-medium">Token Name</span>
</label>
<input
type="text"
name="name"
id="tokenName"
placeholder="e.g. CI/CD Pipeline"
class="input input-bordered w-full"
required
/>
</div>
<div class="modal-action">
<button type="button" class="btn" onclick="createTokenModal.close()">Cancel</button>
<button type="submit" class="btn btn-primary">Generate Token</button>
</div>
</form>
</div>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
<!-- Show Token Modal -->
<dialog id="showTokenModal" class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg text-success flex items-center gap-2">
<Icon name="heroicons:check-circle" class="w-6 h-6" />
Token Created
</h3>
<p class="py-4">
Make sure to copy your personal access token now. You won't be able to see it again!
</p>
<div class="bg-base-200 p-4 rounded-lg break-all font-mono text-sm relative group">
<span id="newTokenDisplay"></span>
<button
class="absolute top-2 right-2 btn btn-xs btn-ghost opacity-0 group-hover:opacity-100 transition-opacity"
onclick="copyToken()"
title="Copy to clipboard"
>
<Icon name="heroicons:clipboard" class="w-4 h-4" />
</button>
</div>
<div class="modal-action">
<button class="btn btn-primary" onclick="closeShowTokenModal()">Done</button>
</div>
</div>
</dialog>
<script is:inline>
// Handle Token Creation
const createTokenForm = document.getElementById('createTokenForm');
createTokenForm.addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('tokenName').value;
const formData = new FormData();
formData.append('name', name);
try {
const response = await fetch('/api/user/tokens', {
method: 'POST',
body: formData
});
if (response.ok) {
const data = await response.json();
document.getElementById('createTokenModal').close();
document.getElementById('newTokenDisplay').innerText = data.token;
document.getElementById('showTokenModal').showModal();
document.getElementById('tokenName').value = ''; // Reset form
} else {
alert('Failed to create token');
}
} catch (error) {
console.error('Error creating token:', error);
alert('An error occurred');
}
});
// Handle Token Copy
function copyToken() {
const token = document.getElementById('newTokenDisplay').innerText;
navigator.clipboard.writeText(token);
}
// Handle Closing Show Token Modal (refresh page to show new token in list)
function closeShowTokenModal() {
document.getElementById('showTokenModal').close();
window.location.reload();
}
// Handle Token Deletion
async function deleteToken(id) {
if (!confirm('Are you sure you want to revoke this token? Any applications using it will stop working.')) {
return;
}
try {
const response = await fetch(`/api/user/tokens/${id}`, {
method: 'DELETE'
});
if (response.ok) {
window.location.reload();
} else {
alert('Failed to delete token');
}
} catch (error) {
console.error('Error deleting token:', error);
alert('An error occurred');
}
}
</script>
</DashboardLayout> </DashboardLayout>

View File

@@ -34,13 +34,13 @@ if (!isAdmin) return Astro.redirect('/dashboard/team');
<form method="POST" action="/api/team/invite" class="card bg-base-100 shadow-xl border border-base-200"> <form method="POST" action="/api/team/invite" class="card bg-base-100 shadow-xl border border-base-200">
<div class="card-body"> <div class="card-body">
<div class="alert alert-info mb-4"> <div class="alert alert-info mb-4">
<Icon name="heroicons:information-circle" class="w-6 h-6" /> <Icon name="heroicons:information-circle" class="w-6 h-6 shrink-0" />
<span>The user must already have an account. They'll be added to your organization.</span> <span>The user must already have an account. They'll be added to your organization.</span>
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label" for="email"> <label class="label" for="email">
<span class="label-text">Email Address</span> Email Address
</label> </label>
<input <input
type="email" type="email"
@@ -54,13 +54,13 @@ if (!isAdmin) return Astro.redirect('/dashboard/team');
<div class="form-control"> <div class="form-control">
<label class="label" for="role"> <label class="label" for="role">
<span class="label-text">Role</span> Role
</label> </label>
<select id="role" name="role" class="select select-bordered" required> <select id="role" name="role" class="select select-bordered" required>
<option value="member">Member</option> <option value="member">Member</option>
<option value="admin">Admin</option> <option value="admin">Admin</option>
</select> </select>
<label class="label"> <label class="label h-auto block">
<span class="label-text-alt">Members can track time. Admins can manage team and clients.</span> <span class="label-text-alt">Members can track time. Admins can manage team and clients.</span>
</label> </label>
</div> </div>

View File

@@ -2,7 +2,7 @@
import DashboardLayout from '../../../layouts/DashboardLayout.astro'; import DashboardLayout from '../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import { db } from '../../../db'; import { db } from '../../../db';
import { categories, members, organizations } from '../../../db/schema'; import { members, organizations, tags } from '../../../db/schema';
import { eq } from 'drizzle-orm'; import { eq } from 'drizzle-orm';
const user = Astro.locals.user; const user = Astro.locals.user;
@@ -35,9 +35,11 @@ const organization = await db.select()
if (!organization) return Astro.redirect('/dashboard'); if (!organization) return Astro.redirect('/dashboard');
const allCategories = await db.select()
.from(categories)
.where(eq(categories.organizationId, orgId)) const allTags = await db.select()
.from(tags)
.where(eq(tags.organizationId, orgId))
.all(); .all();
const url = new URL(Astro.request.url); const url = new URL(Astro.request.url);
@@ -112,12 +114,13 @@ const successType = url.searchParams.get('success');
</div> </div>
</div> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-name">
<span class="label-text font-medium">Team Name</span> Team Name
</div> </label>
<input <input
type="text" type="text"
id="team-name"
name="name" name="name"
value={organization.name} value={organization.name}
placeholder="Organization name" placeholder="Organization name"
@@ -127,77 +130,119 @@ const successType = url.searchParams.get('success');
<div class="label"> <div class="label">
<span class="label-text-alt text-base-content/60">This name is visible to all team members</span> <span class="label-text-alt text-base-content/60">This name is visible to all team members</span>
</div> </div>
</label> </div>
<div class="divider">Address Information</div> <div class="divider">Address Information</div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-street">
<span class="label-text font-medium">Street Address</span> Street Address
</div> </label>
<input <input
type="text" type="text"
id="team-street"
name="street" name="street"
value={organization.street || ''} value={organization.street || ''}
placeholder="123 Main Street" placeholder="123 Main Street"
class="input input-bordered w-full" class="input input-bordered w-full"
/> />
</label> </div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-city">
<span class="label-text font-medium">City</span> City
</div> </label>
<input <input
type="text" type="text"
id="team-city"
name="city" name="city"
value={organization.city || ''} value={organization.city || ''}
placeholder="City" placeholder="City"
class="input input-bordered w-full" class="input input-bordered w-full"
/> />
</label> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-state">
<span class="label-text font-medium">State/Province</span> State/Province
</div> </label>
<input <input
type="text" type="text"
id="team-state"
name="state" name="state"
value={organization.state || ''} value={organization.state || ''}
placeholder="State/Province" placeholder="State/Province"
class="input input-bordered w-full" class="input input-bordered w-full"
/> />
</label> </div>
</div> </div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-zip">
<span class="label-text font-medium">Postal Code</span> Postal Code
</div> </label>
<input <input
type="text" type="text"
id="team-zip"
name="zip" name="zip"
value={organization.zip || ''} value={organization.zip || ''}
placeholder="12345" placeholder="12345"
class="input input-bordered w-full" class="input input-bordered w-full"
/> />
</label> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="team-country">
<span class="label-text font-medium">Country</span> Country
</div> </label>
<input <input
type="text" type="text"
id="team-country"
name="country" name="country"
value={organization.country || ''} value={organization.country || ''}
placeholder="Country" placeholder="Country"
class="input input-bordered w-full" class="input input-bordered w-full"
/> />
</label> </div>
</div>
<div class="divider">Defaults</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="form-control">
<label class="label font-medium" for="default-tax-rate">
Default Tax Rate (%)
</label>
<input
type="number"
id="default-tax-rate"
name="defaultTaxRate"
step="0.01"
min="0"
max="100"
value={organization.defaultTaxRate || 0}
class="input input-bordered w-full"
/>
</div>
<div class="form-control">
<label class="label font-medium" for="default-currency">
Default Currency
</label>
<select
id="default-currency"
name="defaultCurrency"
class="select select-bordered w-full"
>
<option value="USD" selected={!organization.defaultCurrency || organization.defaultCurrency === 'USD'}>USD ($)</option>
<option value="EUR" selected={organization.defaultCurrency === 'EUR'}>EUR (€)</option>
<option value="GBP" selected={organization.defaultCurrency === 'GBP'}>GBP (£)</option>
<option value="CAD" selected={organization.defaultCurrency === 'CAD'}>CAD ($)</option>
<option value="AUD" selected={organization.defaultCurrency === 'AUD'}>AUD ($)</option>
</select>
</div>
</div> </div>
<div class="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6"> <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6">
@@ -214,60 +259,159 @@ const successType = url.searchParams.get('success');
</div> </div>
</div> </div>
<!-- Categories Section --> <!-- Tags Section -->
<div class="card bg-base-100 shadow-xl border border-base-200 mb-6"> <div class="card bg-base-100 shadow-xl border border-base-200 mb-6">
<div class="card-body"> <div class="card-body">
<div class="flex justify-between items-center mb-4"> <div class="flex justify-between items-center mb-4">
<h2 class="card-title"> <h2 class="card-title">
<Icon name="heroicons:tag" class="w-6 h-6" /> <Icon name="heroicons:tag" class="w-6 h-6" />
Work Categories Tags & Rates
</h2> </h2>
<a href="/dashboard/team/settings/categories/new" class="btn btn-primary btn-sm"> {/* We'll use a simple form submission for now or client-side JS for better UX later */}
<button onclick="document.getElementById('new_tag_modal').showModal()" class="btn btn-primary btn-sm">
<Icon name="heroicons:plus" class="w-5 h-5" /> <Icon name="heroicons:plus" class="w-5 h-5" />
Add Category Add Tag
</a> </button>
</div> </div>
<p class="text-base-content/70 mb-4"> <p class="text-base-content/70 mb-4">
Categories help organize time tracking by type of work. All team members use the same categories. Tags can be used to categorize time entries. You can also associate an hourly rate with a tag for billing purposes.
</p> </p>
{allCategories.length === 0 ? ( {allTags.length === 0 ? (
<div class="alert alert-info"> <div class="alert alert-info">
<Icon name="heroicons:information-circle" class="w-6 h-6" /> <Icon name="heroicons:information-circle" class="w-6 h-6" />
<div> <div>
<div class="font-bold">No categories yet</div> <div class="font-bold">No tags yet</div>
<div class="text-sm">Create your first category to start organizing time entries.</div> <div class="text-sm">Create tags to add context and rates to your time entries.</div>
</div> </div>
</div> </div>
) : ( ) : (
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div class="overflow-x-auto">
{allCategories.map(category => ( <table class="table">
<div class="card bg-base-200 border border-base-300"> <thead>
<div class="card-body p-4"> <tr>
<div class="flex items-center gap-3"> <th>Name</th>
{category.color && ( <th>Rate / Hr</th>
<span class="w-4 h-4 rounded-full shrink-0" style={`background-color: ${category.color}`}></span> <th class="w-20"></th>
)} </tr>
<div class="grow min-w-0"> </thead>
<h3 class="font-semibold truncate">{category.name}</h3> <tbody>
<p class="text-xs text-base-content/60"> {allTags.map(tag => (
Created {category.createdAt?.toLocaleDateString() ?? 'N/A'} <tr>
</p> <td>
</div> <div class="flex items-center gap-2">
<a {tag.color && (
href={`/dashboard/team/settings/categories/${category.id}/edit`} <div class="w-3 h-3 rounded-full" style={`background-color: ${tag.color}`}></div>
class="btn btn-ghost btn-xs" )}
> <span class="font-medium">{tag.name}</span>
<Icon name="heroicons:pencil" class="w-4 h-4" /> </div>
</a> </td>
</div> <td>
</div> {tag.rate ? (
</div> <span class="font-mono">{new Intl.NumberFormat('en-US', { style: 'currency', currency: organization.defaultCurrency || 'USD' }).format(tag.rate / 100)}</span>
))} ) : (
<span class="text-base-content/40 text-xs italic">No rate</span>
)}
</td>
<td>
<div class="flex gap-2">
<button
onclick={`document.getElementById('edit_tag_modal_${tag.id}').showModal()`}
class="btn btn-ghost btn-xs btn-square"
>
<Icon name="heroicons:pencil" class="w-4 h-4" />
</button>
<form method="POST" action={`/api/tags/${tag.id}/delete`} onsubmit="return confirm('Are you sure you want to delete this tag?');">
<button class="btn btn-ghost btn-xs btn-square text-error">
<Icon name="heroicons:trash" class="w-4 h-4" />
</button>
</form>
</div>
{/* Edit Modal */}
<dialog id={`edit_tag_modal_${tag.id}`} class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg">Edit Tag</h3>
<form method="POST" action={`/api/tags/${tag.id}/update`}>
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text">Name</span>
</label>
<input type="text" name="name" value={tag.name} class="input input-bordered w-full" required />
</div>
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text">Color</span>
</label>
<input type="color" name="color" value={tag.color || '#3b82f6'} class="input input-bordered w-full h-12 p-1" />
</div>
<div class="form-control w-full mb-6">
<label class="label">
<span class="label-text">Hourly Rate (cents)</span>
</label>
<input type="number" name="rate" value={tag.rate || 0} min="0" class="input input-bordered w-full" />
<label class="label">
<span class="label-text-alt text-base-content/60">Enter rate in cents (e.g. 5000 = $50.00)</span>
</label>
</div>
<div class="modal-action">
<button type="button" class="btn" onclick={`document.getElementById('edit_tag_modal_${tag.id}').close()`}>Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
</td>
</tr>
))}
</tbody>
</table>
</div> </div>
)} )}
</div> </div>
</div> </div>
<dialog id="new_tag_modal" class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg">New Tag</h3>
<form method="POST" action="/api/tags/create">
<input type="hidden" name="organizationId" value={organization.id} />
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text">Name</span>
</label>
<input type="text" name="name" class="input input-bordered w-full" required placeholder="e.g. Billable, Rush" />
</div>
<div class="form-control w-full mb-4">
<label class="label">
<span class="label-text">Color</span>
</label>
<input type="color" name="color" value="#3b82f6" class="input input-bordered w-full h-12 p-1" />
</div>
<div class="form-control w-full mb-6">
<label class="label">
<span class="label-text">Hourly Rate (cents)</span>
</label>
<input type="number" name="rate" value="0" min="0" class="input input-bordered w-full" />
<label class="label">
<span class="label-text-alt text-base-content/60">Enter rate in cents (e.g. 5000 = $50.00)</span>
</label>
</div>
<div class="modal-action">
<button type="button" class="btn" onclick="document.getElementById('new_tag_modal').close()">Cancel</button>
<button type="submit" class="btn btn-primary">Create Tag</button>
</div>
</form>
</div>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
</DashboardLayout> </DashboardLayout>

View File

@@ -1,93 +0,0 @@
---
import DashboardLayout from '../../../../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components';
import { db } from '../../../../../../db';
import { categories, members } from '../../../../../../db/schema';
import { eq, and } from 'drizzle-orm';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
const { id } = Astro.params;
// Get current team from cookie
const currentTeamId = Astro.cookies.get('currentTeamId')?.value;
const userMemberships = await db.select()
.from(members)
.where(eq(members.userId, user.id))
.all();
if (userMemberships.length === 0) return Astro.redirect('/dashboard');
// Use current team or fallback to first membership
const userMembership = currentTeamId
? userMemberships.find(m => m.organizationId === currentTeamId) || userMemberships[0]
: userMemberships[0];
const isAdmin = userMembership.role === 'owner' || userMembership.role === 'admin';
if (!isAdmin) return Astro.redirect('/dashboard/team/settings');
const category = await db.select()
.from(categories)
.where(and(
eq(categories.id, id!),
eq(categories.organizationId, userMembership.organizationId)
))
.get();
if (!category) return Astro.redirect('/dashboard/team/settings');
---
<DashboardLayout title="Edit Category - Chronus">
<div class="max-w-2xl mx-auto">
<div class="flex items-center gap-3 mb-6">
<a href="/dashboard/team/settings" class="btn btn-ghost btn-sm">
<Icon name="heroicons:arrow-left" class="w-5 h-5" />
</a>
<h1 class="text-3xl font-bold">Edit Category</h1>
</div>
<form method="POST" action={`/api/categories/${id}/update`} class="card bg-base-200 shadow-xl border border-base-300">
<div class="card-body">
<div class="form-control">
<label class="label pb-2" for="name">
<span class="label-text font-medium">Category Name</span>
</label>
<input
type="text"
id="name"
name="name"
value={category.name}
placeholder="Development"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label class="label pb-2" for="color">
<span class="label-text font-medium">Color (optional)</span>
</label>
<input
type="color"
id="color"
name="color"
value={category.color || '#3b82f6'}
class="input input-bordered w-full h-12"
/>
</div>
<div class="card-actions justify-between mt-6">
<form method="POST" action={`/api/categories/${id}/delete`}>
<button type="submit" class="btn btn-error btn-outline">Delete Category</button>
</form>
<div class="flex gap-2">
<a href="/dashboard/team/settings" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
</div>
</div>
</form>
</div>
</DashboardLayout>

View File

@@ -1,53 +0,0 @@
---
import DashboardLayout from '../../../../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
---
<DashboardLayout title="New Category - Chronus">
<div class="max-w-2xl mx-auto">
<div class="flex items-center gap-3 mb-6">
<a href="/dashboard/team/settings" class="btn btn-ghost btn-sm">
<Icon name="heroicons:arrow-left" class="w-5 h-5" />
</a>
<h1 class="text-3xl font-bold">Add New Category</h1>
</div>
<form method="POST" action="/api/categories/create" class="card bg-base-200 shadow-xl border border-base-300">
<div class="card-body">
<div class="form-control">
<label class="label pb-2" for="name">
<span class="label-text font-medium">Category Name</span>
</label>
<input
type="text"
id="name"
name="name"
placeholder="Development"
class="input input-bordered w-full"
required
/>
</div>
<div class="form-control">
<label class="label pb-2" for="color">
<span class="label-text font-medium">Color (optional)</span>
</label>
<input
type="color"
id="color"
name="color"
class="input input-bordered w-full h-12"
/>
</div>
<div class="card-actions justify-end mt-6">
<a href="/dashboard/team/settings" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">Create Category</button>
</div>
</div>
</form>
</div>
</DashboardLayout>

View File

@@ -4,7 +4,7 @@ import { Icon } from 'astro-icon/components';
import Timer from '../../components/Timer.vue'; import Timer from '../../components/Timer.vue';
import ManualEntry from '../../components/ManualEntry.vue'; import ManualEntry from '../../components/ManualEntry.vue';
import { db } from '../../db'; import { db } from '../../db';
import { timeEntries, clients, members, tags, timeEntryTags, categories, users } from '../../db/schema'; import { timeEntries, clients, members, tags, users } from '../../db/schema';
import { eq, desc, asc, and, sql, or, like } from 'drizzle-orm'; import { eq, desc, asc, and, sql, or, like } from 'drizzle-orm';
import { formatTimeRange } from '../../lib/formatTime'; import { formatTimeRange } from '../../lib/formatTime';
@@ -33,11 +33,6 @@ const allClients = await db.select()
.where(eq(clients.organizationId, organizationId)) .where(eq(clients.organizationId, organizationId))
.all(); .all();
const allCategories = await db.select()
.from(categories)
.where(eq(categories.organizationId, organizationId))
.all();
const allTags = await db.select() const allTags = await db.select()
.from(tags) .from(tags)
.where(eq(tags.organizationId, organizationId)) .where(eq(tags.organizationId, organizationId))
@@ -50,7 +45,7 @@ const pageSize = 20;
const offset = (page - 1) * pageSize; const offset = (page - 1) * pageSize;
const filterClient = url.searchParams.get('client') || ''; const filterClient = url.searchParams.get('client') || '';
const filterCategory = url.searchParams.get('category') || '';
const filterStatus = url.searchParams.get('status') || ''; const filterStatus = url.searchParams.get('status') || '';
const filterType = url.searchParams.get('type') || ''; const filterType = url.searchParams.get('type') || '';
const sortBy = url.searchParams.get('sort') || 'start-desc'; const sortBy = url.searchParams.get('sort') || 'start-desc';
@@ -62,10 +57,6 @@ if (filterClient) {
conditions.push(eq(timeEntries.clientId, filterClient)); conditions.push(eq(timeEntries.clientId, filterClient));
} }
if (filterCategory) {
conditions.push(eq(timeEntries.categoryId, filterCategory));
}
if (filterStatus === 'completed') { if (filterStatus === 'completed') {
conditions.push(sql`${timeEntries.endTime} IS NOT NULL`); conditions.push(sql`${timeEntries.endTime} IS NOT NULL`);
} else if (filterStatus === 'running') { } else if (filterStatus === 'running') {
@@ -107,13 +98,13 @@ switch (sortBy) {
const entries = await db.select({ const entries = await db.select({
entry: timeEntries, entry: timeEntries,
client: clients, client: clients,
category: categories,
user: users, user: users,
tag: tags,
}) })
.from(timeEntries) .from(timeEntries)
.leftJoin(clients, eq(timeEntries.clientId, clients.id)) .leftJoin(clients, eq(timeEntries.clientId, clients.id))
.leftJoin(categories, eq(timeEntries.categoryId, categories.id))
.leftJoin(users, eq(timeEntries.userId, users.id)) .leftJoin(users, eq(timeEntries.userId, users.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and(...conditions)) .where(and(...conditions))
.orderBy(orderBy) .orderBy(orderBy)
.limit(pageSize) .limit(pageSize)
@@ -123,9 +114,11 @@ const entries = await db.select({
const runningEntry = await db.select({ const runningEntry = await db.select({
entry: timeEntries, entry: timeEntries,
client: clients, client: clients,
tag: tags,
}) })
.from(timeEntries) .from(timeEntries)
.leftJoin(clients, eq(timeEntries.clientId, clients.id)) .leftJoin(clients, eq(timeEntries.clientId, clients.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and( .where(and(
eq(timeEntries.userId, user.id), eq(timeEntries.userId, user.id),
sql`${timeEntries.endTime} IS NULL` sql`${timeEntries.endTime} IS NULL`
@@ -169,12 +162,6 @@ const paginationPages = getPaginationPages(page, totalPages);
<span class="flex-1 text-center sm:text-left">You need to create a client before tracking time.</span> <span class="flex-1 text-center sm:text-left">You need to create a client before tracking time.</span>
<a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a> <a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a>
</div> </div>
) : allCategories.length === 0 ? (
<div class="alert alert-warning flex flex-col sm:flex-row items-center gap-4">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
<span class="flex-1 text-center sm:text-left">You need to create a category before tracking time.</span>
<a href="/dashboard/team/settings" class="btn btn-sm btn-primary whitespace-nowrap">Team Settings</a>
</div>
) : ( ) : (
<Timer <Timer
client:load client:load
@@ -182,10 +169,9 @@ const paginationPages = getPaginationPages(page, totalPages);
startTime: runningEntry.entry.startTime.getTime(), startTime: runningEntry.entry.startTime.getTime(),
description: runningEntry.entry.description, description: runningEntry.entry.description,
clientId: runningEntry.entry.clientId, clientId: runningEntry.entry.clientId,
categoryId: runningEntry.entry.categoryId, tagId: runningEntry.tag?.id,
} : null} } : null}
clients={allClients.map(c => ({ id: c.id, name: c.name }))} clients={allClients.map(c => ({ id: c.id, name: c.name }))}
categories={allCategories.map(c => ({ id: c.id, name: c.name, color: c.color }))}
tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))} tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))}
/> />
)} )}
@@ -199,17 +185,10 @@ const paginationPages = getPaginationPages(page, totalPages);
<span class="flex-1 text-center sm:text-left">You need to create a client before adding time entries.</span> <span class="flex-1 text-center sm:text-left">You need to create a client before adding time entries.</span>
<a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a> <a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a>
</div> </div>
) : allCategories.length === 0 ? (
<div class="alert alert-warning flex flex-col sm:flex-row items-center gap-4">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
<span class="flex-1 text-center sm:text-left">You need to create a category before adding time entries.</span>
<a href="/dashboard/team/settings" class="btn btn-sm btn-primary whitespace-nowrap">Team Settings</a>
</div>
) : ( ) : (
<ManualEntry <ManualEntry
client:load client:idle
clients={allClients.map(c => ({ id: c.id, name: c.name }))} clients={allClients.map(c => ({ id: c.id, name: c.name }))}
categories={allCategories.map(c => ({ id: c.id, name: c.name, color: c.color }))}
tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))} tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))}
/> />
)} )}
@@ -225,11 +204,12 @@ const paginationPages = getPaginationPages(page, totalPages);
<div class="card-body"> <div class="card-body">
<form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4"> <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="tracker-search">
<span class="label-text font-medium">Search</span> Search
</label> </label>
<input <input
type="text" type="text"
id="tracker-search"
name="search" name="search"
placeholder="Search descriptions..." placeholder="Search descriptions..."
class="input input-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" class="input input-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full"
@@ -238,10 +218,10 @@ const paginationPages = getPaginationPages(page, totalPages);
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="tracker-client">
<span class="label-text font-medium">Client</span> Client
</label> </label>
<select name="client" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()"> <select id="tracker-client" name="client" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="">All Clients</option> <option value="">All Clients</option>
{allClients.map(client => ( {allClients.map(client => (
<option value={client.id} selected={filterClient === client.id}> <option value={client.id} selected={filterClient === client.id}>
@@ -251,25 +231,13 @@ const paginationPages = getPaginationPages(page, totalPages);
</select> </select>
</div> </div>
<div class="form-control">
<label class="label">
<span class="label-text font-medium">Category</span>
</label>
<select name="category" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="">All Categories</option>
{allCategories.map(category => (
<option value={category.id} selected={filterCategory === category.id}>
{category.name}
</option>
))}
</select>
</div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="tracker-status">
<span class="label-text font-medium">Status</span> Status
</label> </label>
<select name="status" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()"> <select id="tracker-status" name="status" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="" selected={filterStatus === ''}>All Entries</option> <option value="" selected={filterStatus === ''}>All Entries</option>
<option value="completed" selected={filterStatus === 'completed'}>Completed</option> <option value="completed" selected={filterStatus === 'completed'}>Completed</option>
<option value="running" selected={filterStatus === 'running'}>Running</option> <option value="running" selected={filterStatus === 'running'}>Running</option>
@@ -277,10 +245,10 @@ const paginationPages = getPaginationPages(page, totalPages);
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="tracker-type">
<span class="label-text font-medium">Entry Type</span> Entry Type
</label> </label>
<select name="type" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()"> <select id="tracker-type" name="type" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="" selected={filterType === ''}>All Types</option> <option value="" selected={filterType === ''}>All Types</option>
<option value="timed" selected={filterType === 'timed'}>Timed</option> <option value="timed" selected={filterType === 'timed'}>Timed</option>
<option value="manual" selected={filterType === 'manual'}>Manual</option> <option value="manual" selected={filterType === 'manual'}>Manual</option>
@@ -288,10 +256,10 @@ const paginationPages = getPaginationPages(page, totalPages);
</div> </div>
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label font-medium" for="tracker-sort">
<span class="label-text font-medium">Sort By</span> Sort By
</label> </label>
<select name="sort" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()"> <select id="tracker-sort" name="sort" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="start-desc" selected={sortBy === 'start-desc'}>Newest First</option> <option value="start-desc" selected={sortBy === 'start-desc'}>Newest First</option>
<option value="start-asc" selected={sortBy === 'start-asc'}>Oldest First</option> <option value="start-asc" selected={sortBy === 'start-asc'}>Oldest First</option>
<option value="duration-desc" selected={sortBy === 'duration-desc'}>Longest Duration</option> <option value="duration-desc" selected={sortBy === 'duration-desc'}>Longest Duration</option>
@@ -317,7 +285,7 @@ const paginationPages = getPaginationPages(page, totalPages);
<Icon name="heroicons:list-bullet" class="w-6 h-6" /> <Icon name="heroicons:list-bullet" class="w-6 h-6" />
Time Entries ({totalCount?.count || 0} total) Time Entries ({totalCount?.count || 0} total)
</h2> </h2>
{(filterClient || filterCategory || filterStatus || filterType || searchTerm) && ( {(filterClient || filterStatus || filterType || searchTerm) && (
<a href="/dashboard/tracker" class="btn btn-sm btn-ghost hover:bg-base-300/50 transition-colors"> <a href="/dashboard/tracker" class="btn btn-sm btn-ghost hover:bg-base-300/50 transition-colors">
<Icon name="heroicons:x-mark" class="w-4 h-4" /> <Icon name="heroicons:x-mark" class="w-4 h-4" />
Clear Filters Clear Filters
@@ -330,7 +298,6 @@ const paginationPages = getPaginationPages(page, totalPages);
<tr class="bg-base-300/30"> <tr class="bg-base-300/30">
<th>Type</th> <th>Type</th>
<th>Client</th> <th>Client</th>
<th>Category</th>
<th>Description</th> <th>Description</th>
<th>Member</th> <th>Member</th>
<th>Start Time</th> <th>Start Time</th>
@@ -340,7 +307,7 @@ const paginationPages = getPaginationPages(page, totalPages);
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{entries.map(({ entry, client, category, user: entryUser }) => ( {entries.map(({ entry, client, user: entryUser }) => (
<tr class="hover:bg-base-300/20 transition-colors"> <tr class="hover:bg-base-300/20 transition-colors">
<td> <td>
{entry.isManual ? ( {entry.isManual ? (
@@ -356,14 +323,6 @@ const paginationPages = getPaginationPages(page, totalPages);
)} )}
</td> </td>
<td class="font-medium">{client?.name || 'Unknown'}</td> <td class="font-medium">{client?.name || 'Unknown'}</td>
<td>
{category ? (
<div class="flex items-center gap-2">
<span class="w-3 h-3 rounded-full shadow-sm" style={`background-color: ${category.color}`}></span>
<span>{category.name}</span>
</div>
) : '-'}
</td>
<td class="text-base-content/80">{entry.description || '-'}</td> <td class="text-base-content/80">{entry.description || '-'}</td>
<td>{entryUser?.name || 'Unknown'}</td> <td>{entryUser?.name || 'Unknown'}</td>
<td class="whitespace-nowrap"> <td class="whitespace-nowrap">
@@ -406,7 +365,7 @@ const paginationPages = getPaginationPages(page, totalPages);
{totalPages > 1 && ( {totalPages > 1 && (
<div class="flex justify-center items-center gap-2 mt-6"> <div class="flex justify-center items-center gap-2 mt-6">
<a <a
href={`?page=${Math.max(1, page - 1)}${filterClient ? `&client=${filterClient}` : ''}${filterCategory ? `&category=${filterCategory}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`} href={`?page=${Math.max(1, page - 1)}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === 1 ? 'btn-disabled' : 'hover:bg-base-300/50'}`} class={`btn btn-sm transition-all ${page === 1 ? 'btn-disabled' : 'hover:bg-base-300/50'}`}
> >
<Icon name="heroicons:chevron-left" class="w-4 h-4" /> <Icon name="heroicons:chevron-left" class="w-4 h-4" />
@@ -416,7 +375,7 @@ const paginationPages = getPaginationPages(page, totalPages);
<div class="flex gap-1"> <div class="flex gap-1">
{paginationPages.map(pageNum => ( {paginationPages.map(pageNum => (
<a <a
href={`?page=${pageNum}${filterClient ? `&client=${filterClient}` : ''}${filterCategory ? `&category=${filterCategory}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`} href={`?page=${pageNum}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === pageNum ? 'btn-active' : 'hover:bg-base-300/50'}`} class={`btn btn-sm transition-all ${page === pageNum ? 'btn-active' : 'hover:bg-base-300/50'}`}
> >
{pageNum} {pageNum}
@@ -425,7 +384,7 @@ const paginationPages = getPaginationPages(page, totalPages);
</div> </div>
<a <a
href={`?page=${Math.min(totalPages, page + 1)}${filterClient ? `&client=${filterClient}` : ''}${filterCategory ? `&category=${filterCategory}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`} href={`?page=${Math.min(totalPages, page + 1)}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === totalPages ? 'btn-disabled' : 'hover:bg-base-300/50'}`} class={`btn btn-sm transition-all ${page === totalPages ? 'btn-disabled' : 'hover:bg-base-300/50'}`}
> >
Next Next

View File

@@ -1,6 +1,7 @@
--- ---
import Layout from '../layouts/Layout.astro'; import Layout from '../layouts/Layout.astro';
import { Icon } from 'astro-icon/components'; import { Icon } from 'astro-icon/components';
import PasskeyLogin from '../components/auth/PasskeyLogin.vue';
if (Astro.locals.user) { if (Astro.locals.user) {
return Astro.redirect('/dashboard'); return Astro.redirect('/dashboard');
@@ -31,35 +32,41 @@ const errorMessage =
)} )}
<form action="/api/auth/login" method="POST" class="space-y-4"> <form action="/api/auth/login" method="POST" class="space-y-4">
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="email">
<span class="label-text font-medium">Email</span> Email
</div> </label>
<input <input
type="email" type="email"
id="email"
name="email" name="email"
placeholder="your@email.com" placeholder="your@email.com"
class="input input-bordered w-full" class="input input-bordered w-full"
autocomplete="email"
required required
/> />
</label> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="password">
<span class="label-text font-medium">Password</span> Password
</div> </label>
<input <input
type="password" type="password"
id="password"
name="password" name="password"
placeholder="Enter your password" placeholder="Enter your password"
class="input input-bordered w-full" class="input input-bordered w-full"
autocomplete="current-password"
required required
/> />
</label> </div>
<button class="btn btn-primary w-full mt-6">Sign In</button> <button class="btn btn-primary w-full mt-6">Sign In</button>
</form> </form>
<PasskeyLogin client:idle />
<div class="divider">OR</div> <div class="divider">OR</div>
<div class="text-center"> <div class="text-center">

View File

@@ -64,44 +64,50 @@ const errorMessage =
) : ( ) : (
<> <>
<form action="/api/auth/signup" method="POST" class="space-y-4"> <form action="/api/auth/signup" method="POST" class="space-y-4">
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="name">
<span class="label-text font-medium">Full Name</span> Full Name
</div> </label>
<input <input
type="text" type="text"
id="name"
name="name" name="name"
placeholder="John Doe" placeholder="John Doe"
class="input input-bordered w-full" class="input input-bordered w-full"
autocomplete="name"
required required
/> />
</label> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="email">
<span class="label-text font-medium">Email</span> Email
</div> </label>
<input <input
type="email" type="email"
id="email"
name="email" name="email"
placeholder="your@email.com" placeholder="your@email.com"
class="input input-bordered w-full" class="input input-bordered w-full"
autocomplete="email"
required required
/> />
</label> </div>
<label class="form-control"> <div class="form-control">
<div class="label"> <label class="label font-medium" for="password">
<span class="label-text font-medium">Password</span> Password
</div> </label>
<input <input
type="password" type="password"
id="password"
name="password" name="password"
placeholder="Create a strong password" placeholder="Create a strong password"
class="input input-bordered w-full" class="input input-bordered w-full"
autocomplete="new-password"
required required
/> />
</label> </div>
<button class="btn btn-primary w-full mt-6">Create Account</button> <button class="btn btn-primary w-full mt-6">Create Account</button>
</form> </form>

View File

@@ -40,6 +40,9 @@ interface Invoice {
dueDate: Date; dueDate: Date;
currency: string; currency: string;
subtotal: number; subtotal: number;
discountValue: number | null;
discountType: string | null;
discountAmount: number | null;
taxRate: number | null; taxRate: number | null;
taxAmount: number; taxAmount: number;
total: number; total: number;
@@ -503,6 +506,24 @@ export function createInvoiceDocument(props: InvoiceDocumentProps) {
formatCurrency(invoice.subtotal), formatCurrency(invoice.subtotal),
), ),
]), ]),
(invoice.discountAmount ?? 0) > 0
? h(View, { style: styles.totalRow }, [
h(
Text,
{ style: styles.totalLabel },
`Discount${
invoice.discountType === "percentage"
? ` (${invoice.discountValue}%)`
: ""
}`,
),
h(
Text,
{ style: styles.totalValue },
`-${formatCurrency(invoice.discountAmount ?? 0)}`,
),
])
: null,
(invoice.taxRate ?? 0) > 0 (invoice.taxRate ?? 0) > 0
? h(View, { style: styles.totalRow }, [ ? h(View, { style: styles.totalRow }, [
h( h(

View File

@@ -2,4 +2,5 @@
@plugin "daisyui" { @plugin "daisyui" {
themes: false; themes: false;
} }
@plugin "./theme.ts"; @plugin "./theme-dark.ts";
@plugin "./theme-light.ts";

View File

@@ -0,0 +1,9 @@
import { createCatppuccinPlugin } from "@catppuccin/daisyui";
export default createCatppuccinPlugin(
"latte",
{},
{
default: false,
},
);

View File

@@ -24,19 +24,36 @@ export async function recalculateInvoiceTotals(invoiceId: string) {
.all(); .all();
// Calculate totals // Calculate totals
// Note: amounts are in cents
const subtotal = items.reduce((acc, item) => acc + item.amount, 0); const subtotal = items.reduce((acc, item) => acc + item.amount, 0);
const taxRate = invoice.taxRate || 0; // Calculate discount
const taxAmount = Math.round(subtotal * (taxRate / 100)); const discountType = invoice.discountType || "percentage";
const discountValue = invoice.discountValue || 0;
let discountAmount = 0;
const total = subtotal + taxAmount; if (discountType === "percentage") {
discountAmount = Math.round(subtotal * (discountValue / 100));
} else {
// Fixed amount is assumed to be in cents
discountAmount = Math.round(discountValue);
}
// Ensure discount doesn't exceed subtotal
discountAmount = Math.max(0, Math.min(discountAmount, subtotal));
const taxableAmount = subtotal - discountAmount;
const taxRate = invoice.taxRate || 0;
const taxAmount = Math.round(taxableAmount * (taxRate / 100));
const total = taxableAmount + taxAmount;
// Update invoice // Update invoice
await db await db
.update(invoices) .update(invoices)
.set({ .set({
subtotal, subtotal,
discountAmount,
taxAmount, taxAmount,
total, total,
}) })