calculate.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Code generated by fkit v3.11.0. DO NOT EDIT.
  2. //
  3. // Source: schema/payroll/aggregates.fkit
  4. // Regenerate with: go run ./tools/fkitgen ./schema/payroll
  5. package payroll
  6. import (
  7. "context"
  8. "database/sql"
  9. )
  10. // PayrollCycleTotals is the generated aggregate row for a payroll cycle.
  11. type PayrollCycleTotals struct {
  12. CycleID string
  13. Payslips int64
  14. GrossCents int64
  15. DeductionCents int64
  16. NetCents int64
  17. }
  18. // CalculatePayrollCycleTotals runs the generated SUM aggregate over the
  19. // payslip rows of one cycle. It totals what is already stored; it does not
  20. // calculate any payslip.
  21. func CalculatePayrollCycleTotals(ctx context.Context, db *sql.DB, cycleID string) (PayrollCycleTotals, error) {
  22. const q = `SELECT count(*), COALESCE(sum(gross_cents), 0), COALESCE(sum(deduction_cents), 0),
  23. COALESCE(sum(net_cents), 0)
  24. FROM payslip WHERE cycle_id = $1`
  25. var t PayrollCycleTotals
  26. t.CycleID = cycleID
  27. err := db.QueryRowContext(ctx, q, cycleID).Scan(&t.Payslips, &t.GrossCents, &t.DeductionCents, &t.NetCents)
  28. return t, err
  29. }
  30. // CalculatePayslipNet recomputes net from the stored gross and deduction
  31. // columns of one row. Pure column arithmetic — no pay rules.
  32. func CalculatePayslipNet(row PayslipRow) int64 {
  33. return row.GrossCents - row.DeductionCents
  34. }
  35. // CalculatePayrollCycleAverage averages the stored net over a cycle.
  36. func CalculatePayrollCycleAverage(ctx context.Context, db *sql.DB, cycleID string) (int64, error) {
  37. totals, err := CalculatePayrollCycleTotals(ctx, db, cycleID)
  38. if err != nil {
  39. return 0, err
  40. }
  41. if totals.Payslips == 0 {
  42. return 0, nil
  43. }
  44. return totals.NetCents / totals.Payslips, nil
  45. }
  46. // CalculateEmployeeYearToDate sums an employee's stored payslips for a year.
  47. func CalculateEmployeeYearToDate(ctx context.Context, db *sql.DB, employeeID string, year int) (int64, error) {
  48. const q = `SELECT COALESCE(sum(net_cents), 0) FROM payslip
  49. WHERE employee_id = $1 AND extract(year from period_from) = $2`
  50. var n int64
  51. err := db.QueryRowContext(ctx, q, employeeID, year).Scan(&n)
  52. return n, err
  53. }