| 1 | 'use server' |
| 2 | |
| 3 | import { render } from '@react-email/render' |
| 4 | import { and, asc |
| 5 | import { authService } |
| 6 | import { projectsService } |
| 7 | import { timesheetService } |
| 8 | import BudgetThresholdReachedEmail from '@/emails/templates/budget-threshold-reached |
| 9 | import TimesheetApprovedEmail from '@/emails/templates/timesheet-approved |
| 10 | import TimesheetClientRespondedEmail from '@/emails/templates/timesheet-client-responded |
| 11 | import TimesheetRejectedEmail from '@/emails/templates/timesheet-rejected |
| 12 | import TimesheetSentToClientEmail from '@/emails/templates/timesheet-sent-to-client |
| 13 | import TimesheetSubmittedEmail from '@/emails/templates/timesheet-submitted |
| 14 | import { computeEntryAmount } |
| 15 | import { |
| 16 | buildCustomValuesSchema, |
| 17 | type CustomFieldDefinition, |
| 18 | } from '@/lib/custom-fields' |
| 19 | import { getAdminsAndOwners, sendEmailsToRecipients |
| 20 | import { authedActionClient } |
| 21 | import { db } |
| 22 | import { |
| 23 | customFields, |
| 24 | invoices, |
| 25 | memberRates, |
| 26 | members, |
| 27 | projectBudgets, |
| 28 | projects, |
| 29 | timeEntries, |
| 30 | timesheetReportEntries, |
| 31 | timesheetReportRecipients, |
| 32 | timesheetReports, |
| 33 | users, |
| 34 | } from '@/server/db/schema' |
| 35 | import { currencyConversionService } |
| 36 | import { |
| 37 | approveTimeEntriesSchema, |
| 38 | createTimeEntrySchema, |
| 39 | deleteTimeEntrySchema, |
| 40 | linkTimeEntriesToInvoiceSchema, |
| 41 | rejectTimeEntriesSchema, |
| 42 | resendTimesheetReportSchema, |
| 43 | respondTimesheetReportSchema, |
| 44 | sendTimesheetToClientSchema, |
| 45 | setMemberRateSchema, |
| 46 | setProjectBudgetSchema, |
| 47 | submitTimesheetSchema, |
| 48 | updateTimeEntrySchema, |
| 49 | } from './common' |
| 50 | |
| 51 | /** Columns selected for bulk time entry operations. */ |
| 52 | const timeEntryColumns = { |
| 53 | id: timeEntries.id |
| 54 | projectId: timeEntries.projectId |
| 55 | memberId: timeEntries.memberId |
| 56 | durationMinutes: timeEntries.durationMinutes |
| 57 | date: timeEntries.date |
| 58 | status: timeEntries.status |
| 59 | createdAt: timeEntries.createdAt |
| 60 | billable: timeEntries.billable |
| 61 | description: timeEntries.description |
| 62 | } as const |
| 63 | |
| 64 | /** |
| 65 | * Validates that every entry in `entries` belongs to the same project. |
| 66 | * Throws if entries span multiple projects. |
| 67 | * Returns the single shared projectId. |
| 68 | */ |
| 69 | async function loadProjectCustomFieldDefs |
| 70 | projectId: string |
| 71 | ): Promise<CustomFieldDefinition |
| 72 | const rows = |
| 73 | .select() |
| 74 | .from(customFields) |
| 75 | .where(eq(customFields |
| 76 | .orderBy(asc(customFields |
| 77 | return rows |
| 78 | } |
| 79 | |
| 80 | function validateCustomValues( |
| 81 | defs: CustomFieldDefinition |
| 82 | input: Record |
| 83 | ): Record<string |
| 84 | if (defs.length |
| 85 | return {} |
| 86 | } |
| 87 | const filtered: |
| 88 | const allowed = |
| 89 | for (const [k |
| 90 | if (allowed.has |
| 91 | filtered[k] = |
| 92 | } |
| 93 | } |
| 94 | const schema = |
| 95 | const result = |
| 96 | if (!result.success |
| 97 | const first = |
| 98 | const path = |
| 99 | const def = |
| 100 | const label = |
| 101 | throw new Error( |
| 102 | `Custom field "${label}": ${ |
| 103 | ) |
| 104 | } |
| 105 | return result.data |
| 106 | } |
| 107 | |
| 108 | function assertSingleProject(entries: |
| 109 | const projectIds = |
| 110 | if (projectIds.size |
| 111 | throw new Error( |
| 112 | } |
| 113 | return [...projectIds |
| 114 | } |
| 115 | |
| 116 | export const createTimeEntryAction = |
| 117 | .inputSchema(createTimeEntrySchema) |
| 118 | .action( |
| 119 | async ({ |
| 120 | parsedInput: { |
| 121 | projectId, |
| 122 | requirementId, |
| 123 | description, |
| 124 | date, |
| 125 | durationMinutes, |
| 126 | billable, |
| 127 | customValues, |
| 128 | }, |
| 129 | ctx: { role, |
| 130 | }) => { |
| 131 | if (!role.authorize |
| 132 | throw new Error( |
| 133 | } |
| 134 | const hasProjectAccess = |
| 135 | orgMember.organizationId, |
| 136 | projectId, |
| 137 | user.id |
| 138 | ) |
| 139 | if (!hasProjectAccess.success |
| 140 | throw new Error( |
| 141 | } |
| 142 | |
| 143 | const isAdmin = |
| 144 | const settings = |
| 145 | orgMember.organizationId, |
| 146 | projectId |
| 147 | ) |
| 148 | const clientOff = |
| 149 | |
| 150 | // Admin/owner entries are auto-approved, so they must clear the same rate |
| 151 | // requirement as the approval flow before the entry is created. |
| 152 | if (isAdmin) { |
| 153 | await timesheetService.ensureMemberRate |
| 154 | orgMember.id, |
| 155 | projectId, |
| 156 | date, |
| 157 | settings |
| 158 | ) |
| 159 | } |
| 160 | |
| 161 | const defs = |
| 162 | const validatedCustomValues = |
| 163 | |
| 164 | const [entry] |
| 165 | .insert(timeEntries) |
| 166 | .values({ |
| 167 | projectId, |
| 168 | requirementId: requirementId || |
| 169 | memberId: orgMember.id |
| 170 | description, |
| 171 | date, |
| 172 | durationMinutes, |
| 173 | billable, |
| 174 | customValues: validatedCustomValues, |
| 175 | status: isAdmin |
| 176 | ? clientOff |
| 177 | ? 'client_accepted' |
| 178 | : 'admin_accepted' |
| 179 | : 'draft', |
| 180 | }) |
| 181 | .returning() |
| 182 | |
| 183 | if (isAdmin) { |
| 184 | await checkBudgetThreshold(projectId |
| 185 | } |
| 186 | |
| 187 | return entry |
| 188 | } |
| 189 | ) |
| 190 | |
| 191 | export const updateTimeEntryAction = |
| 192 | .inputSchema(updateTimeEntrySchema) |
| 193 | .action( |
| 194 | async ({ |
| 195 | parsedInput: { |
| 196 | timeEntryId, |
| 197 | requirementId, |
| 198 | description, |
| 199 | date, |
| 200 | durationMinutes, |
| 201 | billable, |
| 202 | customValues, |
| 203 | }, |
| 204 | ctx: { role, |
| 205 | }) => { |
| 206 | if (!role.authorize |
| 207 | throw new Error( |
| 208 | } |
| 209 | |
| 210 | const existing = |
| 211 | .select({ |
| 212 | id: timeEntries.id |
| 213 | projectId: timeEntries.projectId |
| 214 | memberId: timeEntries.memberId |
| 215 | status: timeEntries.status |
| 216 | }) |
| 217 | .from(timeEntries) |
| 218 | .where(eq(timeEntries |
| 219 | .then((r) |
| 220 | |
| 221 | if (!existing) |
| 222 | throw new Error( |
| 223 | } |
| 224 | const hasProjectAccess = |
| 225 | orgMember.organizationId, |
| 226 | existing.projectId, |
| 227 | user.id |
| 228 | ) |
| 229 | if (!hasProjectAccess.success |
| 230 | throw new Error( |
| 231 | } |
| 232 | |
| 233 | const isAdmin = |
| 234 | |
| 235 | if (!isAdmin && |
| 236 | throw new Error( |
| 237 | } |
| 238 | |
| 239 | if ( |
| 240 | !isAdmin && |
| 241 | existing.status !== |
| 242 | existing.status !== |
| 243 | ) { |
| 244 | throw new Error( |
| 245 | } |
| 246 | |
| 247 | const updates: |
| 248 | if (requirementId !== |
| 249 | updates.requirementId = |
| 250 | } |
| 251 | if (description !== |
| 252 | updates.description = |
| 253 | } |
| 254 | if (date !== |
| 255 | updates.date = |
| 256 | } |
| 257 | if (durationMinutes !== |
| 258 | updates.durationMinutes = |
| 259 | } |
| 260 | if (billable !== |
| 261 | updates.billable = |
| 262 | } |
| 263 | if (customValues !== |
| 264 | const defs = |
| 265 | updates.customValues = |
| 266 | } |
| 267 | // Reset rejected entries to draft when edited so they can be resubmitted |
| 268 | if (existing.status |
| 269 | updates.status = |
| 270 | updates.rejectReason = |
| 271 | } |
| 272 | |
| 273 | const [updated] |
| 274 | .update(timeEntries) |
| 275 | .set(updates) |
| 276 | .where(eq(timeEntries |
| 277 | .returning() |
| 278 | |
| 279 | return updated |
| 280 | } |
| 281 | ) |
| 282 | |
| 283 | export const deleteTimeEntryAction = |
| 284 | .inputSchema(deleteTimeEntrySchema) |
| 285 | .action( |
| 286 | async ({ |
| 287 | parsedInput: { timeEntryId |
| 288 | ctx: { role, |
| 289 | }) => { |
| 290 | if (!role.authorize |
| 291 | throw new Error( |
| 292 | } |
| 293 | |
| 294 | const existing = |
| 295 | .select({ |
| 296 | id: timeEntries.id |
| 297 | projectId: timeEntries.projectId |
| 298 | memberId: timeEntries.memberId |
| 299 | status: timeEntries.status |
| 300 | }) |
| 301 | .from(timeEntries) |
| 302 | .where(eq(timeEntries |
| 303 | .then((r) |
| 304 | |
| 305 | if (!existing) |
| 306 | throw new Error( |
| 307 | } |
| 308 | const hasProjectAccess = |
| 309 | orgMember.organizationId, |
| 310 | existing.projectId, |
| 311 | user.id |
| 312 | ) |
| 313 | if (!hasProjectAccess.success |
| 314 | throw new Error( |
| 315 | } |
| 316 | |
| 317 | const isAdmin = |
| 318 | |
| 319 | if (!isAdmin && |
| 320 | throw new Error( |
| 321 | } |
| 322 | |
| 323 | if (!isAdmin && |
| 324 | throw new Error( |
| 325 | } |
| 326 | |
| 327 | await db.delete |
| 328 | |
| 329 | return { success: |
| 330 | } |
| 331 | ) |
| 332 | |
| 333 | export const submitTimesheetAction = |
| 334 | .inputSchema(submitTimesheetSchema) |
| 335 | .action( |
| 336 | async ({ |
| 337 | parsedInput: { timeEntryIds |
| 338 | ctx: { role, |
| 339 | }) => { |
| 340 | if (!role.authorize |
| 341 | throw new Error( |
| 342 | } |
| 343 | |
| 344 | const entries = |
| 345 | .select(timeEntryColumns) |
| 346 | .from(timeEntries) |
| 347 | .where(inArray(timeEntries |
| 348 | |
| 349 | if (entries.length |
| 350 | throw new Error( |
| 351 | } |
| 352 | |
| 353 | const projectId = |
| 354 | |
| 355 | const hasProjectAccess = |
| 356 | orgMember.organizationId, |
| 357 | projectId, |
| 358 | user.id |
| 359 | ) |
| 360 | if (!hasProjectAccess.success |
| 361 | throw new Error( |
| 362 | } |
| 363 | |
| 364 | for (const entry |
| 365 | if (entry.memberId |
| 366 | throw new Error( |
| 367 | } |
| 368 | if (entry.status |
| 369 | throw new Error( |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | await db |
| 374 | .update(timeEntries) |
| 375 | .set({ status: |
| 376 | .where(inArray(timeEntries |
| 377 | |
| 378 | const totalMinutes = |
| 379 | (sum, e) |
| 380 | 0 |
| 381 | ) |
| 382 | const totalHours = |
| 383 | |
| 384 | const details = |
| 385 | const recipients = |
| 386 | |
| 387 | await sendEmailsToRecipients(recipients |
| 388 | const html = |
| 389 | TimesheetSubmittedEmail({ |
| 390 | recipientName: recipient.name |
| 391 | memberName: user.name |
| 392 | projectName: details.projectName |
| 393 | totalHours, |
| 394 | weekLabel: formatWeekLabel(entries |
| 395 | entryCount: entries.length, |
| 396 | orgSlug: details.orgSlug |
| 397 | projectSlug: details.projectSlug |
| 398 | }) |
| 399 | ) |
| 400 | return { |
| 401 | to: recipient.email |
| 402 | subject: `Timesheet submitted — ${user |
| 403 | html, |
| 404 | } |
| 405 | }) |
| 406 | |
| 407 | return { success: |
| 408 | } |
| 409 | ) |
| 410 | |
| 411 | export const approveTimeEntriesAction = |
| 412 | .inputSchema(approveTimeEntriesSchema) |
| 413 | .action( |
| 414 | async ({ |
| 415 | parsedInput: { timeEntryIds |
| 416 | ctx: { role, |
| 417 | }) => { |
| 418 | if (!role.authorize |
| 419 | throw new Error( |
| 420 | } |
| 421 | |
| 422 | const entries = |
| 423 | .select(timeEntryColumns) |
| 424 | .from(timeEntries) |
| 425 | .where(inArray(timeEntries |
| 426 | |
| 427 | if (entries.length |
| 428 | throw new Error( |
| 429 | } |
| 430 | |
| 431 | const projectId = |
| 432 | |
| 433 | const hasProjectAccess = |
| 434 | orgMember.organizationId, |
| 435 | projectId, |
| 436 | user.id |
| 437 | ) |
| 438 | if (!hasProjectAccess.success |
| 439 | throw new Error( |
| 440 | } |
| 441 | |
| 442 | for (const entry |
| 443 | if (entry.status |
| 444 | throw new Error( |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | const approveSettings = |
| 449 | orgMember.organizationId, |
| 450 | projectId |
| 451 | ) |
| 452 | |
| 453 | // Each member needs a rate before approval — seed from the org/project |
| 454 | // defaults when missing, effective from their earliest entry so it |
| 455 | // covers every entry being approved. Throws if no default is configured. |
| 456 | const memberIds = |
| 457 | for (const id |
| 458 | const earliest = |
| 459 | .filter((e) |
| 460 | .reduce( |
| 461 | (min, e) |
| 462 | entries.find((e |
| 463 | ) |
| 464 | await timesheetService.ensureMemberRate |
| 465 | id, |
| 466 | projectId, |
| 467 | earliest, |
| 468 | approveSettings |
| 469 | ) |
| 470 | } |
| 471 | const approvedStatus = |
| 472 | approveSettings.clientInvolvement.timesheets |
| 473 | ? 'client_accepted' |
| 474 | : 'admin_accepted' |
| 475 | |
| 476 | await db |
| 477 | .update(timeEntries) |
| 478 | .set({ status: |
| 479 | .where(inArray(timeEntries |
| 480 | |
| 481 | const details = |
| 482 | |
| 483 | // Notify each member about their approved entries |
| 484 | for (const memberId |
| 485 | const memberEntries = |
| 486 | const memberMinutes = |
| 487 | (sum, e) |
| 488 | 0 |
| 489 | ) |
| 490 | const [member] |
| 491 | .select({ email: |
| 492 | .from(members) |
| 493 | .innerJoin(users, |
| 494 | .where(eq(members |
| 495 | |
| 496 | if (member) { |
| 497 | await sendEmailsToRecipients([member |
| 498 | const html = |
| 499 | TimesheetApprovedEmail({ |
| 500 | recipientName: recipient.name |
| 501 | approverName: user.name |
| 502 | projectName: details.projectName |
| 503 | totalHours: (memberMinutes / |
| 504 | weekLabel: formatWeekLabel(memberEntries |
| 505 | entryCount: memberEntries.length, |
| 506 | orgSlug: details.orgSlug |
| 507 | projectSlug: details.projectSlug |
| 508 | }) |
| 509 | ) |
| 510 | return { |
| 511 | to: recipient.email |
| 512 | subject: `Timesheet approved — ${(memberMinutes |
| 513 | html, |
| 514 | } |
| 515 | }) |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | await checkBudgetThreshold(projectId |
| 520 | |
| 521 | return { success: |
| 522 | } |
| 523 | ) |
| 524 | |
| 525 | export const rejectTimeEntriesAction = |
| 526 | .inputSchema(rejectTimeEntriesSchema) |
| 527 | .action( |
| 528 | async ({ |
| 529 | parsedInput: { timeEntryIds, |
| 530 | ctx: { role, |
| 531 | }) => { |
| 532 | if (!role.authorize |
| 533 | throw new Error( |
| 534 | } |
| 535 | |
| 536 | const entries = |
| 537 | .select(timeEntryColumns) |
| 538 | .from(timeEntries) |
| 539 | .where(inArray(timeEntries |
| 540 | |
| 541 | if (entries.length |
| 542 | throw new Error( |
| 543 | } |
| 544 | |
| 545 | const projectId = |
| 546 | |
| 547 | const hasProjectAccess = |
| 548 | orgMember.organizationId, |
| 549 | projectId, |
| 550 | user.id |
| 551 | ) |
| 552 | if (!hasProjectAccess.success |
| 553 | throw new Error( |
| 554 | } |
| 555 | |
| 556 | for (const entry |
| 557 | if (entry.status |
| 558 | throw new Error( |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | await db |
| 563 | .update(timeEntries) |
| 564 | .set({ status: |
| 565 | .where(inArray(timeEntries |
| 566 | |
| 567 | const details = |
| 568 | |
| 569 | const memberIds = |
| 570 | for (const memberId |
| 571 | const memberEntries = |
| 572 | const memberMinutes = |
| 573 | (sum, e) |
| 574 | 0 |
| 575 | ) |
| 576 | const [member] |
| 577 | .select({ email: |
| 578 | .from(members) |
| 579 | .innerJoin(users, |
| 580 | .where(eq(members |
| 581 | |
| 582 | if (member) { |
| 583 | await sendEmailsToRecipients([member |
| 584 | const html = |
| 585 | TimesheetRejectedEmail({ |
| 586 | recipientName: recipient.name |
| 587 | rejectorName: user.name |
| 588 | projectName: details.projectName |
| 589 | totalHours: (memberMinutes / |
| 590 | weekLabel: formatWeekLabel(memberEntries |
| 591 | reason, |
| 592 | orgSlug: details.orgSlug |
| 593 | projectSlug: details.projectSlug |
| 594 | }) |
| 595 | ) |
| 596 | return { |
| 597 | to: recipient.email |
| 598 | subject: 'Timesheet rejected — changes requested', |
| 599 | html, |
| 600 | } |
| 601 | }) |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | return { success: |
| 606 | } |
| 607 | ) |
| 608 | |
| 609 | export const setMemberRateAction = |
| 610 | .inputSchema(setMemberRateSchema) |
| 611 | .action( |
| 612 | async ({ |
| 613 | parsedInput: { |
| 614 | memberId, |
| 615 | projectId, |
| 616 | effectiveFrom, |
| 617 | billingCurrency, |
| 618 | billingFrequency, |
| 619 | billingRate, |
| 620 | payCurrency, |
| 621 | payFrequency, |
| 622 | payRate, |
| 623 | }, |
| 624 | ctx: { role, |
| 625 | }) => { |
| 626 | if (!role.authorize |
| 627 | throw new Error( |
| 628 | } |
| 629 | |
| 630 | // Verify the target member belongs to this org before writing — with |
| 631 | // projectId null this would otherwise be a cross-tenant write path. |
| 632 | const [targetMember] |
| 633 | .select({ id: |
| 634 | .from(members) |
| 635 | .where( |
| 636 | and( |
| 637 | eq(members.id |
| 638 | eq(members.organizationId |
| 639 | ) |
| 640 | ) |
| 641 | if (!targetMember) |
| 642 | throw new Error( |
| 643 | } |
| 644 | |
| 645 | if (projectId) { |
| 646 | const hasProjectAccess = |
| 647 | orgMember.organizationId, |
| 648 | projectId, |
| 649 | user.id |
| 650 | ) |
| 651 | if (!hasProjectAccess.success |
| 652 | throw new Error( |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | const effectiveDate = |
| 657 | const resolvedProjectId = |
| 658 | |
| 659 | const [existing] |
| 660 | .select({ id: |
| 661 | .from(memberRates) |
| 662 | .where( |
| 663 | and( |
| 664 | eq(memberRates.memberId |
| 665 | resolvedProjectId |
| 666 | ? eq(memberRates. |
| 667 | : isNull(memberRates. |
| 668 | eq(memberRates.effectiveFrom |
| 669 | ) |
| 670 | ) |
| 671 | |
| 672 | let rate: |
| 673 | if (existing) { |
| 674 | const [newRate] |
| 675 | .update(memberRates) |
| 676 | .set({ |
| 677 | billingCurrency, |
| 678 | billingFrequency, |
| 679 | billingRate, |
| 680 | payCurrency, |
| 681 | payFrequency, |
| 682 | payRate, |
| 683 | }) |
| 684 | .where(eq(memberRates |
| 685 | .returning() |
| 686 | rate = newRate |
| 687 | } else { |
| 688 | const [newRate] |
| 689 | .insert(memberRates) |
| 690 | .values({ |
| 691 | memberId, |
| 692 | projectId: resolvedProjectId, |
| 693 | billingCurrency, |
| 694 | billingFrequency, |
| 695 | billingRate, |
| 696 | payCurrency, |
| 697 | payFrequency, |
| 698 | payRate, |
| 699 | effectiveFrom: effectiveDate, |
| 700 | }) |
| 701 | .returning() |
| 702 | rate = newRate |
| 703 | } |
| 704 | |
| 705 | return rate |
| 706 | } |
| 707 | ) |
| 708 | |
| 709 | export const setProjectBudgetAction = |
| 710 | .inputSchema(setProjectBudgetSchema) |
| 711 | .action( |
| 712 | async ({ |
| 713 | parsedInput: { projectId, |
| 714 | ctx: { role, |
| 715 | }) => { |
| 716 | if (!role.authorize |
| 717 | throw new Error( |
| 718 | } |
| 719 | const hasProjectAccess = |
| 720 | orgMember.organizationId, |
| 721 | projectId, |
| 722 | user.id |
| 723 | ) |
| 724 | if (!hasProjectAccess.success |
| 725 | throw new Error( |
| 726 | } |
| 727 | |
| 728 | const existing = |
| 729 | .select({ id: |
| 730 | .from(projectBudgets) |
| 731 | .where(eq(projectBudgets |
| 732 | .then((r) |
| 733 | |
| 734 | let budget: |
| 735 | if (existing) { |
| 736 | ;[budget] = |
| 737 | .update(projectBudgets) |
| 738 | .set({ budgetMinutes |
| 739 | .where(eq(projectBudgets |
| 740 | .returning() |
| 741 | } else { |
| 742 | ;[budget] = |
| 743 | .insert(projectBudgets) |
| 744 | .values({ projectId |
| 745 | .returning() |
| 746 | } |
| 747 | |
| 748 | return budget |
| 749 | } |
| 750 | ) |
| 751 | |
| 752 | export const linkTimeEntriesToInvoiceAction = |
| 753 | .inputSchema(linkTimeEntriesToInvoiceSchema) |
| 754 | .action( |
| 755 | async ({ |
| 756 | parsedInput: { timeEntryIds, |
| 757 | ctx: { role, |
| 758 | }) => { |
| 759 | if (!role.authorize |
| 760 | throw new Error( |
| 761 | } |
| 762 | |
| 763 | const entries = |
| 764 | .select({ id: |
| 765 | .from(timeEntries) |
| 766 | .where(inArray(timeEntries |
| 767 | if (entries.length |
| 768 | throw new Error( |
| 769 | } |
| 770 | |
| 771 | const projectId = |
| 772 | |
| 773 | const hasProjectAccess = |
| 774 | orgMember.organizationId, |
| 775 | projectId, |
| 776 | user.id |
| 777 | ) |
| 778 | if (!hasProjectAccess.success |
| 779 | throw new Error( |
| 780 | } |
| 781 | |
| 782 | // Confirm the invoice belongs to the same project as the entries — |
| 783 | // otherwise a user could attach entries to an invoice in a project |
| 784 | // they don't own. |
| 785 | const [invoice] |
| 786 | .select({ projectId: |
| 787 | .from(invoices) |
| 788 | .where(eq(invoices |
| 789 | if (!invoice || |
| 790 | throw new Error( |
| 791 | } |
| 792 | |
| 793 | await db |
| 794 | .update(timeEntries) |
| 795 | .set({ invoiceId |
| 796 | .where(inArray(timeEntries |
| 797 | |
| 798 | // Conversion rates for these entries are snapshotted by the editor's |
| 799 | // create/update flow via item metadata, so nothing more is needed here. |
| 800 | return { success: |
| 801 | } |
| 802 | ) |
| 803 | |
| 804 | export const sendTimesheetToClientAction = |
| 805 | .inputSchema(sendTimesheetToClientSchema) |
| 806 | .action( |
| 807 | async ({ |
| 808 | parsedInput: { projectId, |
| 809 | ctx: { role, |
| 810 | }) => { |
| 811 | if (!role.authorize |
| 812 | throw new Error( |
| 813 | } |
| 814 | if (clientMemberIds.length |
| 815 | throw new Error( |
| 816 | } |
| 817 | const hasProjectAccess = |
| 818 | orgMember.organizationId, |
| 819 | projectId, |
| 820 | user.id |
| 821 | ) |
| 822 | if (!hasProjectAccess.success |
| 823 | throw new Error( |
| 824 | } |
| 825 | const settings = |
| 826 | orgMember.organizationId, |
| 827 | projectId |
| 828 | ) |
| 829 | if (settings.clientInvolvement |
| 830 | throw new Error( |
| 831 | 'Client involvement is disabled for timesheets in this project' |
| 832 | ) |
| 833 | } |
| 834 | |
| 835 | const entries = |
| 836 | .select(timeEntryColumns) |
| 837 | .from(timeEntries) |
| 838 | .where( |
| 839 | and( |
| 840 | inArray(timeEntries.id |
| 841 | eq(timeEntries.projectId |
| 842 | ) |
| 843 | ) |
| 844 | if (entries.length |
| 845 | throw new Error( |
| 846 | 'Some of the time entries do not belong to the selected project.' |
| 847 | ) |
| 848 | } |
| 849 | for (const entry |
| 850 | if (entry.status |
| 851 | throw new Error( |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | const totalMinutes = |
| 856 | (sum, e) |
| 857 | 0 |
| 858 | ) |
| 859 | |
| 860 | // Resolve each member's rate as of the entry's own date, memoised per |
| 861 | // (member, date), so totals stay correct when the selected entries |
| 862 | // straddle a rate change. |
| 863 | const rateCache = |
| 864 | string, |
| 865 | Awaited<ReturnType<typeof |
| 866 | >() |
| 867 | const resolveRate = |
| 868 | const key = |
| 869 | if (!rateCache.has |
| 870 | rateCache.set( |
| 871 | key, |
| 872 | await timesheetService.getMemberRate |
| 873 | ) |
| 874 | } |
| 875 | return rateCache.get |
| 876 | } |
| 877 | |
| 878 | const reportCurrency = |
| 879 | |
| 880 | let totalAmountCents = |
| 881 | for (const entry |
| 882 | const rate = |
| 883 | if (!rate) |
| 884 | continue |
| 885 | } |
| 886 | const entryAmount = |
| 887 | entry.durationMinutes, |
| 888 | rate.billingRate ?? |
| 889 | rate.billingFrequency ?? |
| 890 | ) |
| 891 | const entryCurrency = |
| 892 | rate.billingRate == |
| 893 | if (!entryCurrency) |
| 894 | continue |
| 895 | } |
| 896 | const { amount: |
| 897 | await currencyConversionService.convertCents |
| 898 | entryAmount, |
| 899 | entryCurrency, |
| 900 | reportCurrency |
| 901 | ) |
| 902 | totalAmountCents += converted |
| 903 | } |
| 904 | |
| 905 | const report = |
| 906 | const [r] |
| 907 | .insert(timesheetReports) |
| 908 | .values({ |
| 909 | projectId, |
| 910 | title, |
| 911 | totalMinutes, |
| 912 | totalAmount: totalAmountCents, |
| 913 | currency: reportCurrency, |
| 914 | sentByMemberId: orgMember.id |
| 915 | status: 'sent', |
| 916 | sentAt: new Date |
| 917 | }) |
| 918 | .returning() |
| 919 | |
| 920 | if (!r) |
| 921 | throw new Error( |
| 922 | } |
| 923 | |
| 924 | await tx |
| 925 | .insert(timesheetReportRecipients) |
| 926 | .values( |
| 927 | clientMemberIds.map((clientMemberId |
| 928 | reportId: r.id |
| 929 | clientMemberId, |
| 930 | status: 'pending' as |
| 931 | })) |
| 932 | ) |
| 933 | .onConflictDoNothing() |
| 934 | |
| 935 | await tx.insert |
| 936 | timeEntryIds.map((teId |
| 937 | reportId: r.id |
| 938 | timeEntryId: teId, |
| 939 | })) |
| 940 | ) |
| 941 | await tx |
| 942 | .update(timeEntries) |
| 943 | .set({ status: |
| 944 | .where(inArray(timeEntries |
| 945 | |
| 946 | return r |
| 947 | }) |
| 948 | |
| 949 | const details = |
| 950 | |
| 951 | const clients = |
| 952 | .select({ email: |
| 953 | .from(members) |
| 954 | .innerJoin(users, |
| 955 | .where(inArray(members |
| 956 | |
| 957 | if (clients.length |
| 958 | const totalHours = |
| 959 | const totalAmountFormatted = |
| 960 | 'en-US', |
| 961 | { |
| 962 | style: 'currency', |
| 963 | currency: reportCurrency, |
| 964 | } |
| 965 | ) |
| 966 | await sendEmailsToRecipients(clients |
| 967 | const html = |
| 968 | TimesheetSentToClientEmail({ |
| 969 | recipientName: recipient.name |
| 970 | senderName: user.name |
| 971 | projectName: details.projectName |
| 972 | reportTitle: title, |
| 973 | totalHours, |
| 974 | totalAmount: totalAmountFormatted, |
| 975 | currency: reportCurrency, |
| 976 | orgSlug: details.orgSlug |
| 977 | projectSlug: details.projectSlug |
| 978 | reportId: report.id |
| 979 | }) |
| 980 | ) |
| 981 | return { |
| 982 | to: recipient.email |
| 983 | subject: `Timesheet for review — ${title |
| 984 | html, |
| 985 | } |
| 986 | }) |
| 987 | } |
| 988 | |
| 989 | return report |
| 990 | } |
| 991 | ) |
| 992 | |
| 993 | export const respondTimesheetReportAction = |
| 994 | .inputSchema(respondTimesheetReportSchema) |
| 995 | .action( |
| 996 | async ({ |
| 997 | parsedInput: { reportId, |
| 998 | ctx: { role, |
| 999 | }) => { |
| 1000 | const permission = |
| 1001 | action === 'approve' |
| 1002 | if (!role.authorize |
| 1003 | throw new Error( |
| 1004 | } |
| 1005 | |
| 1006 | const [report] |
| 1007 | .select({ |
| 1008 | id: timesheetReports.id |
| 1009 | projectId: timesheetReports.projectId |
| 1010 | title: timesheetReports.title |
| 1011 | status: timesheetReports.status |
| 1012 | totalMinutes: timesheetReports.totalMinutes |
| 1013 | sentByMemberId: timesheetReports.sentByMemberId |
| 1014 | }) |
| 1015 | .from(timesheetReports) |
| 1016 | .where(eq(timesheetReports |
| 1017 | |
| 1018 | if (!report) |
| 1019 | throw new Error( |
| 1020 | } |
| 1021 | const hasProjectAccess = |
| 1022 | orgMember.organizationId, |
| 1023 | report.projectId, |
| 1024 | user.id |
| 1025 | ) |
| 1026 | if (!hasProjectAccess.success |
| 1027 | throw new Error( |
| 1028 | } |
| 1029 | const settings = |
| 1030 | orgMember.organizationId, |
| 1031 | report.projectId |
| 1032 | ) |
| 1033 | if (settings.clientInvolvement |
| 1034 | throw new Error( |
| 1035 | 'Client involvement is disabled for timesheets in this project' |
| 1036 | ) |
| 1037 | } |
| 1038 | if (report.status |
| 1039 | throw new Error( |
| 1040 | } |
| 1041 | |
| 1042 | const recipients = |
| 1043 | .select({ |
| 1044 | id: timesheetReportRecipients.id |
| 1045 | clientMemberId: timesheetReportRecipients.clientMemberId |
| 1046 | status: timesheetReportRecipients.status |
| 1047 | }) |
| 1048 | .from(timesheetReportRecipients) |
| 1049 | .where(eq(timesheetReportRecipients |
| 1050 | |
| 1051 | const currentRecipient = |
| 1052 | (r) => |
| 1053 | ) |
| 1054 | if (!currentRecipient) |
| 1055 | throw new Error( |
| 1056 | } |
| 1057 | if (currentRecipient.status |
| 1058 | throw new Error( |
| 1059 | } |
| 1060 | |
| 1061 | const recipientStatus = |
| 1062 | |
| 1063 | await db |
| 1064 | .update(timesheetReportRecipients) |
| 1065 | .set({ |
| 1066 | status: recipientStatus, |
| 1067 | disputeReason: action === |
| 1068 | respondedAt: new Date |
| 1069 | }) |
| 1070 | .where(eq(timesheetReportRecipients |
| 1071 | |
| 1072 | if (action === |
| 1073 | await db.transaction |
| 1074 | await tx |
| 1075 | .update(timesheetReports) |
| 1076 | .set({ |
| 1077 | status: 'disputed', |
| 1078 | respondedAt: new Date |
| 1079 | }) |
| 1080 | .where(eq(timesheetReports |
| 1081 | const entries = |
| 1082 | .select() |
| 1083 | .from(timesheetReportEntries) |
| 1084 | .where(eq(timesheetReportEntries |
| 1085 | await tx |
| 1086 | .update(timeEntries) |
| 1087 | .set({ status: |
| 1088 | .where( |
| 1089 | inArray( |
| 1090 | timeEntries.id, |
| 1091 | entries.map((e |
| 1092 | ) |
| 1093 | ) |
| 1094 | }) |
| 1095 | } else { |
| 1096 | const totalRecipients = |
| 1097 | const alreadyApproved = |
| 1098 | (r) => |
| 1099 | ).length |
| 1100 | const totalApproved = |
| 1101 | |
| 1102 | if (totalApproved >= |
| 1103 | await db.transaction |
| 1104 | await tx |
| 1105 | .update(timesheetReports) |
| 1106 | .set({ |
| 1107 | status: 'approved', |
| 1108 | respondedAt: new Date |
| 1109 | }) |
| 1110 | .where(eq(timesheetReports |
| 1111 | const entries = |
| 1112 | .select() |
| 1113 | .from(timesheetReportEntries) |
| 1114 | .where(eq(timesheetReportEntries |
| 1115 | await tx |
| 1116 | .update(timeEntries) |
| 1117 | .set({ status: |
| 1118 | .where( |
| 1119 | inArray( |
| 1120 | timeEntries.id, |
| 1121 | entries.map((e |
| 1122 | ) |
| 1123 | ) |
| 1124 | }) |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | if (report.sentByMemberId |
| 1129 | const [sender] |
| 1130 | .select({ email: |
| 1131 | .from(members) |
| 1132 | .innerJoin(users, |
| 1133 | .where(eq(members |
| 1134 | |
| 1135 | if (sender) { |
| 1136 | const details = |
| 1137 | report.projectId |
| 1138 | ) |
| 1139 | const totalHours = |
| 1140 | await sendEmailsToRecipients([sender |
| 1141 | const html = |
| 1142 | TimesheetClientRespondedEmail({ |
| 1143 | recipientName: recipient.name |
| 1144 | clientName: user.name |
| 1145 | projectName: details.projectName |
| 1146 | reportTitle: report.title |
| 1147 | totalHours, |
| 1148 | action: action === |
| 1149 | disputeReason: reason, |
| 1150 | orgSlug: details.orgSlug |
| 1151 | projectSlug: details.projectSlug |
| 1152 | reportId: report.id |
| 1153 | }) |
| 1154 | ) |
| 1155 | return { |
| 1156 | to: recipient.email |
| 1157 | subject: `Timesheet ${action |
| 1158 | html, |
| 1159 | } |
| 1160 | }) |
| 1161 | } |
| 1162 | } |
| 1163 | |
| 1164 | return { success: |
| 1165 | } |
| 1166 | ) |
| 1167 | |
| 1168 | export const resendTimesheetReportAction = |
| 1169 | .inputSchema(resendTimesheetReportSchema) |
| 1170 | .action( |
| 1171 | async ({ parsedInput |
| 1172 | if (!role.authorize |
| 1173 | throw new Error( |
| 1174 | } |
| 1175 | |
| 1176 | const [report] |
| 1177 | .select({ |
| 1178 | id: timesheetReports.id |
| 1179 | projectId: timesheetReports.projectId |
| 1180 | title: timesheetReports.title |
| 1181 | status: timesheetReports.status |
| 1182 | currency: timesheetReports.currency |
| 1183 | }) |
| 1184 | .from(timesheetReports) |
| 1185 | .where(eq(timesheetReports |
| 1186 | |
| 1187 | if (!report) |
| 1188 | throw new Error( |
| 1189 | } |
| 1190 | |
| 1191 | const [project] |
| 1192 | .select({ organizationId: |
| 1193 | .from(projects) |
| 1194 | .where(eq(projects |
| 1195 | if (!project || |
| 1196 | throw new Error( |
| 1197 | } |
| 1198 | |
| 1199 | const settings = |
| 1200 | orgMember.organizationId, |
| 1201 | report.projectId |
| 1202 | ) |
| 1203 | if (settings.clientInvolvement |
| 1204 | throw new Error( |
| 1205 | 'Client involvement is disabled for timesheets in this project' |
| 1206 | ) |
| 1207 | } |
| 1208 | |
| 1209 | if (report.status |
| 1210 | throw new Error( |
| 1211 | } |
| 1212 | |
| 1213 | const entryLinks = |
| 1214 | .select({ timeEntryId: |
| 1215 | .from(timesheetReportEntries) |
| 1216 | .where(eq(timesheetReportEntries |
| 1217 | |
| 1218 | const entryIds = |
| 1219 | const linkedEntries = |
| 1220 | entryIds.length > 0 |
| 1221 | ? await db |
| 1222 | .select(timeEntryColumns) |
| 1223 | .from(timeEntries) |
| 1224 | .where(inArray(timeEntries |
| 1225 | : [] |
| 1226 | |
| 1227 | const totalMinutes = |
| 1228 | (sum, e) |
| 1229 | 0 |
| 1230 | ) |
| 1231 | |
| 1232 | // Resolve each member's rate as of the entry's own date, memoised per |
| 1233 | // (member, date), so totals stay correct when the linked entries |
| 1234 | // straddle a rate change. |
| 1235 | const rateCache = |
| 1236 | string, |
| 1237 | Awaited<ReturnType<typeof |
| 1238 | >() |
| 1239 | const resolveRate = |
| 1240 | const key = |
| 1241 | if (!rateCache.has |
| 1242 | rateCache.set( |
| 1243 | key, |
| 1244 | await timesheetService.getMemberRate |
| 1245 | memberId, |
| 1246 | report.projectId, |
| 1247 | date |
| 1248 | ) |
| 1249 | ) |
| 1250 | } |
| 1251 | return rateCache.get |
| 1252 | } |
| 1253 | |
| 1254 | const reportCurrency = |
| 1255 | |
| 1256 | let totalAmountCents = |
| 1257 | for (const entry |
| 1258 | const rate = |
| 1259 | if (!rate) |
| 1260 | continue |
| 1261 | } |
| 1262 | const entryAmount = |
| 1263 | entry.durationMinutes, |
| 1264 | rate.billingRate ?? |
| 1265 | rate.billingFrequency ?? |
| 1266 | ) |
| 1267 | const entryCurrency = |
| 1268 | rate.billingRate == |
| 1269 | if (!entryCurrency) |
| 1270 | continue |
| 1271 | } |
| 1272 | const { amount: |
| 1273 | await currencyConversionService.convertCents |
| 1274 | entryAmount, |
| 1275 | entryCurrency, |
| 1276 | reportCurrency |
| 1277 | ) |
| 1278 | totalAmountCents += converted |
| 1279 | } |
| 1280 | |
| 1281 | await db |
| 1282 | .update(timesheetReports) |
| 1283 | .set({ |
| 1284 | status: 'sent', |
| 1285 | disputeReason: null, |
| 1286 | respondedAt: null, |
| 1287 | sentAt: new Date |
| 1288 | totalMinutes, |
| 1289 | totalAmount: totalAmountCents, |
| 1290 | }) |
| 1291 | .where(eq(timesheetReports |
| 1292 | |
| 1293 | await db |
| 1294 | .update(timesheetReportRecipients) |
| 1295 | .set({ |
| 1296 | status: 'pending', |
| 1297 | disputeReason: null, |
| 1298 | respondedAt: null, |
| 1299 | }) |
| 1300 | .where(eq(timesheetReportRecipients |
| 1301 | |
| 1302 | const details = |
| 1303 | |
| 1304 | const recipients = |
| 1305 | .select({ clientMemberId: |
| 1306 | .from(timesheetReportRecipients) |
| 1307 | .where(eq(timesheetReportRecipients |
| 1308 | |
| 1309 | const clientMemberIds = |
| 1310 | |
| 1311 | if (clientMemberIds.length |
| 1312 | const clients = |
| 1313 | .select({ email: |
| 1314 | .from(members) |
| 1315 | .innerJoin(users, |
| 1316 | .where(inArray(members |
| 1317 | |
| 1318 | if (clients.length |
| 1319 | const totalHours = |
| 1320 | const totalAmountFormatted = |
| 1321 | 'en-US', |
| 1322 | { style: 'currency', |
| 1323 | ) |
| 1324 | await sendEmailsToRecipients(clients |
| 1325 | const html = |
| 1326 | TimesheetSentToClientEmail({ |
| 1327 | recipientName: recipient.name |
| 1328 | senderName: user.name |
| 1329 | projectName: details.projectName |
| 1330 | reportTitle: report.title |
| 1331 | totalHours, |
| 1332 | totalAmount: totalAmountFormatted, |
| 1333 | currency: report.currency |
| 1334 | orgSlug: details.orgSlug |
| 1335 | projectSlug: details.projectSlug |
| 1336 | reportId: report.id |
| 1337 | }) |
| 1338 | ) |
| 1339 | return { |
| 1340 | to: recipient.email |
| 1341 | subject: `Revised timesheet for review — ${report |
| 1342 | html, |
| 1343 | } |
| 1344 | }) |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | return { success: |
| 1349 | } |
| 1350 | ) |
| 1351 | |
| 1352 | function formatWeekLabel(dates: |
| 1353 | if (dates.length |
| 1354 | return '' |
| 1355 | } |
| 1356 | const sorted = |
| 1357 | const first = |
| 1358 | const last = |
| 1359 | const fmt = |
| 1360 | const [y, |
| 1361 | return new Date |
| 1362 | month: 'short', |
| 1363 | day: 'numeric', |
| 1364 | }) |
| 1365 | } |
| 1366 | const year = |
| 1367 | return `${fmt( |
| 1368 | } |
| 1369 | |
| 1370 | async function checkBudgetThreshold |
| 1371 | const budgetStatus = |
| 1372 | if (!budgetStatus) |
| 1373 | return |
| 1374 | } |
| 1375 | |
| 1376 | const { budget, |
| 1377 | |
| 1378 | if (percentageUsed >= |
| 1379 | const details = |
| 1380 | const recipients = |
| 1381 | |
| 1382 | await sendEmailsToRecipients(recipients |
| 1383 | const html = |
| 1384 | BudgetThresholdReachedEmail({ |
| 1385 | recipientName: recipient.name |
| 1386 | projectName: details.projectName |
| 1387 | organizationName: details.orgName |
| 1388 | percentageUsed, |
| 1389 | hoursUsed: (totalApprovedMinutes / |
| 1390 | hoursTotal: (budget.budgetMinutes |
| 1391 | orgSlug: details.orgSlug |
| 1392 | projectSlug: details.projectSlug |
| 1393 | }) |
| 1394 | ) |
| 1395 | return { |
| 1396 | to: recipient.email |
| 1397 | subject: `Budget alert — ${percentageUsed |
| 1398 | html, |
| 1399 | } |
| 1400 | }) |
| 1401 | } |
| 1402 | } |