Add HST/tax support and payment reporting with HST aggregation
CI / Tests (PHP 8.1) (pull_request) Successful in 51s
CI / Coding Standards (pull_request) Successful in 1m1s
CI / Tests (PHP 8.2) (pull_request) Successful in 58s
CI / No Debug Code (pull_request) Successful in 4s
CI / PHPStan (pull_request) Successful in 1m16s
CI / Tests (PHP 8.3) (pull_request) Successful in 45s
CI / Build Plugin Zip (pull_request) Has been skipped
CI / Tests (PHP 8.1) (pull_request) Successful in 51s
CI / Coding Standards (pull_request) Successful in 1m1s
CI / Tests (PHP 8.2) (pull_request) Successful in 58s
CI / No Debug Code (pull_request) Successful in 4s
CI / PHPStan (pull_request) Successful in 1m16s
CI / Tests (PHP 8.3) (pull_request) Successful in 45s
CI / Build Plugin Zip (pull_request) Has been skipped
Studio Settings gains a default HST rate; the rate is frozen onto each payment at booking and computed against the pre-tax subtotal, with the total billed as subtotal + tax. The rate is overridable per booking on My Lessons while unpaid (recomputing the tax amount), comped registrations are never taxed, and receipts break out subtotal/HST/total. Builds the payments report (roadmap #8) from us_payments: a monthly per-instructor view with subtotal, HST collected, and grand-total aggregation, plus a nonce-protected CSV export via admin-post. Studio admins see all instructors and can filter; instructors are scoped to their own rows. The Payment Report menu is gated on export_payments so instructors (who lack manage_billing) can reach it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -40,6 +40,8 @@ class Payment {
|
||||
public readonly string $currency = 'CAD',
|
||||
public readonly string $method = self::METHOD_ETRANSFER,
|
||||
public readonly string $status = self::STATUS_PENDING,
|
||||
public readonly float $taxRate = 0.0,
|
||||
public readonly float $taxAmount = 0.0,
|
||||
public readonly ?string $etransferEmail = null,
|
||||
public readonly ?string $stripePaymentIntentId = null,
|
||||
public readonly ?string $receiptNumber = null,
|
||||
@@ -58,6 +60,8 @@ class Payment {
|
||||
currency: $row->currency,
|
||||
method: $row->method,
|
||||
status: $row->status,
|
||||
taxRate: (float) $row->tax_rate,
|
||||
taxAmount: (float) $row->tax_amount,
|
||||
etransferEmail: $row->etransfer_email,
|
||||
stripePaymentIntentId: $row->stripe_payment_intent_id,
|
||||
receiptNumber: $row->receipt_number,
|
||||
@@ -71,6 +75,13 @@ class Payment {
|
||||
return self::STATUS_PAID === $this->status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Amount billed including tax.
|
||||
*/
|
||||
public function total(): float {
|
||||
return round( $this->amount + $this->taxAmount, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a plain array representation of the payment.
|
||||
*
|
||||
@@ -85,6 +96,9 @@ class Payment {
|
||||
'etransfer_email' => $this->etransferEmail,
|
||||
'registration_id' => $this->registrationId,
|
||||
'amount' => $this->amount,
|
||||
'tax_rate' => $this->taxRate,
|
||||
'tax_amount' => $this->taxAmount,
|
||||
'total' => $this->total(),
|
||||
'currency' => $this->currency,
|
||||
'method' => $this->method,
|
||||
'status' => $this->status,
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Payment;
|
||||
|
||||
/**
|
||||
* Pure aggregator over a set of paid-payment display rows: produces the column
|
||||
* totals (subtotal, HST collected, grand total) and a CSV rendering. Building
|
||||
* the rows (name lookups, filtering) is the controller's job — this class does
|
||||
* no I/O so it stays trivially testable.
|
||||
*/
|
||||
class PaymentReport {
|
||||
|
||||
/**
|
||||
* Build a report over already-resolved display rows.
|
||||
*
|
||||
* @param list<array{date: string, student: string, instructor: string, method: string, status: string, amount: float, tax_rate: float, tax_amount: float, total: float}> $rows
|
||||
*/
|
||||
public function __construct( private array $rows ) {}
|
||||
|
||||
/**
|
||||
* The report's display rows.
|
||||
*
|
||||
* @return list<array{date: string, student: string, instructor: string, method: string, status: string, amount: float, tax_rate: float, tax_amount: float, total: float}>
|
||||
*/
|
||||
public function rows(): array {
|
||||
return $this->rows;
|
||||
}
|
||||
|
||||
public function count(): int {
|
||||
return count( $this->rows );
|
||||
}
|
||||
|
||||
public function totalAmount(): float {
|
||||
return round( array_sum( array_column( $this->rows, 'amount' ) ), 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Total HST collected across all rows — the figure the studio remits.
|
||||
*/
|
||||
public function totalTax(): float {
|
||||
return round( array_sum( array_column( $this->rows, 'tax_amount' ) ), 2 );
|
||||
}
|
||||
|
||||
public function grandTotal(): float {
|
||||
return round( array_sum( array_column( $this->rows, 'total' ) ), 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the report as CSV, including a trailing totals row.
|
||||
*/
|
||||
public function toCsv(): string {
|
||||
$lines = [];
|
||||
|
||||
$lines[] = $this->csvLine(
|
||||
[ 'Date', 'Student', 'Instructor', 'Method', 'Status', 'Subtotal', 'HST Rate', 'HST', 'Total' ]
|
||||
);
|
||||
|
||||
foreach ( $this->rows as $row ) {
|
||||
$lines[] = $this->csvLine(
|
||||
[
|
||||
$row['date'],
|
||||
$row['student'],
|
||||
$row['instructor'],
|
||||
$row['method'],
|
||||
$row['status'],
|
||||
number_format( $row['amount'], 2, '.', '' ),
|
||||
number_format( $row['tax_rate'], 2, '.', '' ),
|
||||
number_format( $row['tax_amount'], 2, '.', '' ),
|
||||
number_format( $row['total'], 2, '.', '' ),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$lines[] = $this->csvLine(
|
||||
[
|
||||
'Totals',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
number_format( $this->totalAmount(), 2, '.', '' ),
|
||||
'',
|
||||
number_format( $this->totalTax(), 2, '.', '' ),
|
||||
number_format( $this->grandTotal(), 2, '.', '' ),
|
||||
]
|
||||
);
|
||||
|
||||
return implode( "\n", $lines ) . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Format one CSV record, quoting fields and escaping embedded quotes.
|
||||
*
|
||||
* @param list<string> $fields
|
||||
*/
|
||||
private function csvLine( array $fields ): string {
|
||||
$escaped = array_map(
|
||||
static fn( string $field ): string => '"' . str_replace( '"', '""', $field ) . '"',
|
||||
$fields
|
||||
);
|
||||
|
||||
return implode( ',', $escaped );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Payment;
|
||||
|
||||
use Unsupervised\Schedular\Auth\RoleManager;
|
||||
|
||||
class PaymentReportController {
|
||||
|
||||
public const EXPORT_ACTION = 'usc_export_payments';
|
||||
|
||||
public function __construct( private PaymentRepository $payments ) {}
|
||||
|
||||
/**
|
||||
* Render the monthly payments report with HST aggregation. Studio admins see
|
||||
* all instructors; instructors are scoped to their own payments.
|
||||
*/
|
||||
public function renderPage(): void {
|
||||
if ( ! current_user_can( RoleManager::CAP_VIEW_ALL_PAYMENTS ) && ! current_user_can( RoleManager::CAP_VIEW_OWN_PAYMENTS ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to view payment reports.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only report filters, no state change.
|
||||
$month = $this->sanitizeMonth( isset( $_GET['month'] ) ? sanitize_text_field( wp_unslash( $_GET['month'] ) ) : '' );
|
||||
$instructorId = isset( $_GET['instructor_id'] ) ? absint( $_GET['instructor_id'] ) : 0;
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
$instructorId = $this->scopeInstructor( $instructorId );
|
||||
|
||||
$report = $this->buildReport( $month, $instructorId );
|
||||
$canExport = current_user_can( RoleManager::CAP_EXPORT_PAYMENTS );
|
||||
$canFilter = current_user_can( RoleManager::CAP_VIEW_ALL_PAYMENTS );
|
||||
$exportUrl = wp_nonce_url(
|
||||
admin_url( 'admin-post.php?action=' . self::EXPORT_ACTION . '&month=' . rawurlencode( $month ) . '&instructor_id=' . $instructorId ),
|
||||
self::EXPORT_ACTION
|
||||
);
|
||||
|
||||
$instructors = $canFilter
|
||||
? get_users(
|
||||
[
|
||||
'role' => RoleManager::INSTRUCTOR,
|
||||
'fields' => [ 'ID', 'display_name' ],
|
||||
]
|
||||
)
|
||||
: [];
|
||||
|
||||
include USC_PLUGIN_DIR . 'templates/admin/payment-report.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream the report as a CSV download (admin_post handler).
|
||||
*/
|
||||
public function export(): void {
|
||||
if ( ! current_user_can( RoleManager::CAP_EXPORT_PAYMENTS ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to export payments.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
check_admin_referer( self::EXPORT_ACTION );
|
||||
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- nonce checked above.
|
||||
$month = $this->sanitizeMonth( isset( $_GET['month'] ) ? sanitize_text_field( wp_unslash( $_GET['month'] ) ) : '' );
|
||||
$instructorId = isset( $_GET['instructor_id'] ) ? absint( $_GET['instructor_id'] ) : 0;
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Recommended
|
||||
|
||||
$instructorId = $this->scopeInstructor( $instructorId );
|
||||
$report = $this->buildReport( $month, $instructorId );
|
||||
|
||||
$filename = 'payments-' . $month . '.csv';
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
|
||||
|
||||
echo $report->toCsv(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV body, not HTML.
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict the requested instructor to the current user when they may only
|
||||
* see their own payments.
|
||||
*/
|
||||
private function scopeInstructor( int $instructorId ): int {
|
||||
if ( ! current_user_can( RoleManager::CAP_VIEW_ALL_PAYMENTS ) ) {
|
||||
return get_current_user_id();
|
||||
}
|
||||
|
||||
return $instructorId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a report of paid payments for the given `Y-m` month, optionally for
|
||||
* one instructor.
|
||||
*/
|
||||
private function buildReport( string $month, int $instructorId ): PaymentReport {
|
||||
$start = $month . '-01 00:00:00';
|
||||
$end = gmdate( 'Y-m-d H:i:s', strtotime( $month . '-01 00:00:00 +1 month' ) );
|
||||
|
||||
$rows = array_map(
|
||||
static function ( Payment $payment ): array {
|
||||
$student = get_userdata( $payment->studentId );
|
||||
$instructor = get_userdata( $payment->instructorId );
|
||||
|
||||
return [
|
||||
'date' => substr( (string) $payment->paidAt, 0, 10 ),
|
||||
'student' => $student ? $student->display_name : (string) $payment->studentId,
|
||||
'instructor' => $instructor ? $instructor->display_name : (string) $payment->instructorId,
|
||||
'method' => $payment->method,
|
||||
'status' => $payment->status,
|
||||
'amount' => (float) $payment->amount,
|
||||
'tax_rate' => (float) $payment->taxRate,
|
||||
'tax_amount' => (float) $payment->taxAmount,
|
||||
'total' => $payment->total(),
|
||||
];
|
||||
},
|
||||
$this->payments->findPaidBetween( $start, $end, $instructorId )
|
||||
);
|
||||
|
||||
return new PaymentReport( $rows );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a `Y-m` month string, defaulting to the current month.
|
||||
*/
|
||||
private function sanitizeMonth( string $month ): string {
|
||||
if ( 1 === preg_match( '/^\d{4}-\d{2}$/', $month ) ) {
|
||||
return $month;
|
||||
}
|
||||
|
||||
return gmdate( 'Y-m' );
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ class PaymentRepository {
|
||||
'currency' => $payment->currency,
|
||||
'method' => $payment->method,
|
||||
'status' => $payment->status,
|
||||
'tax_rate' => $payment->taxRate,
|
||||
'tax_amount' => $payment->taxAmount,
|
||||
'etransfer_email' => $payment->etransferEmail,
|
||||
'stripe_payment_intent_id' => $payment->stripePaymentIntentId,
|
||||
'receipt_number' => $payment->receiptNumber,
|
||||
@@ -30,7 +32,7 @@ class PaymentRepository {
|
||||
'paid_at' => $payment->paidAt,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
],
|
||||
[ '%d', '%d', '%s', '%d', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ]
|
||||
[ '%d', '%d', '%s', '%d', '%f', '%s', '%s', '%s', '%f', '%f', '%s', '%s', '%s', '%s', '%s', '%s' ]
|
||||
);
|
||||
|
||||
return $this->db->insert_id;
|
||||
@@ -46,6 +48,42 @@ class PaymentRepository {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a payment's tax rate and recompute the tax amount from its subtotal.
|
||||
*/
|
||||
public function updateTax( int $id, float $rate ): bool {
|
||||
return false !== $this->db->query(
|
||||
$this->db->prepare(
|
||||
"UPDATE {$this->table} SET tax_rate = %f, tax_amount = ROUND( amount * %f / 100, 2 ) WHERE id = %d",
|
||||
$rate,
|
||||
$rate,
|
||||
$id
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paid payments in a month (`Y-m` bounds), optionally for one instructor —
|
||||
* the reporting source.
|
||||
*
|
||||
* @return list<Payment>
|
||||
*/
|
||||
public function findPaidBetween( string $from, string $to, int $instructorId = 0 ): array {
|
||||
$sql = "SELECT * FROM {$this->table} WHERE status = %s AND paid_at >= %s AND paid_at < %s";
|
||||
$params = [ Payment::STATUS_PAID, $from, $to ];
|
||||
|
||||
if ( $instructorId > 0 ) {
|
||||
$sql .= ' AND instructor_id = %d';
|
||||
$params[] = $instructorId;
|
||||
}
|
||||
|
||||
$sql .= ' ORDER BY paid_at ASC';
|
||||
|
||||
$rows = $this->db->get_results( $this->db->prepare( $sql, $params ) );
|
||||
|
||||
return array_map( Payment::fromRow( ... ), $rows ?? [] );
|
||||
}
|
||||
|
||||
public function findById( int $id ): ?Payment {
|
||||
$row = $this->db->get_row(
|
||||
$this->db->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id )
|
||||
|
||||
@@ -41,6 +41,10 @@ class PaymentService {
|
||||
? $offeringEtransferEmail
|
||||
: ( '' !== $this->settings->etransferEmail() ? $this->settings->etransferEmail() : null );
|
||||
|
||||
// HST is frozen from the studio default at booking; comped students are not taxed.
|
||||
$taxRate = Payment::METHOD_COMP === $method ? 0.0 : $this->settings->hstRate();
|
||||
$taxAmount = round( $amount * $taxRate / 100, 2 );
|
||||
|
||||
$id = $this->payments->insert(
|
||||
new Payment(
|
||||
studentId: $studentId,
|
||||
@@ -51,6 +55,8 @@ class PaymentService {
|
||||
currency: $currency,
|
||||
method: $method,
|
||||
status: $status,
|
||||
taxRate: $taxRate,
|
||||
taxAmount: $taxAmount,
|
||||
etransferEmail: $etransferEmail,
|
||||
)
|
||||
);
|
||||
|
||||
@@ -20,13 +20,26 @@ class ReceiptMailer {
|
||||
(string) $payment->receiptNumber
|
||||
);
|
||||
|
||||
$body = sprintf(
|
||||
/* translators: 1: amount, 2: currency, 3: receipt number */
|
||||
__( "Thank you. We have recorded your payment of %1\$s %2\$s.\n\nReceipt: %3\$s", 'unsupervised-schedular' ),
|
||||
number_format( $payment->amount, 2 ),
|
||||
$payment->currency,
|
||||
(string) $payment->receiptNumber
|
||||
);
|
||||
if ( $payment->taxAmount > 0 ) {
|
||||
$body = sprintf(
|
||||
/* translators: 1: currency, 2: subtotal, 3: HST rate, 4: HST amount, 5: total, 6: receipt number */
|
||||
__( "Thank you. We have recorded your payment.\n\nSubtotal: %1\$s %2\$s\nHST (%3\$s%%): %1\$s %4\$s\nTotal: %1\$s %5\$s\n\nReceipt: %6\$s", 'unsupervised-schedular' ),
|
||||
$payment->currency,
|
||||
number_format( $payment->amount, 2 ),
|
||||
number_format( $payment->taxRate, 2 ),
|
||||
number_format( $payment->taxAmount, 2 ),
|
||||
number_format( $payment->total(), 2 ),
|
||||
(string) $payment->receiptNumber
|
||||
);
|
||||
} else {
|
||||
$body = sprintf(
|
||||
/* translators: 1: amount, 2: currency, 3: receipt number */
|
||||
__( "Thank you. We have recorded your payment of %1\$s %2\$s.\n\nReceipt: %3\$s", 'unsupervised-schedular' ),
|
||||
number_format( $payment->total(), 2 ),
|
||||
$payment->currency,
|
||||
(string) $payment->receiptNumber
|
||||
);
|
||||
}
|
||||
|
||||
return (bool) wp_mail( $student->user_email, $subject, $body );
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ class StudioSettings {
|
||||
public const OPT_MODE = 'us_stripe_mode';
|
||||
public const OPT_CURRENCY = 'us_currency';
|
||||
public const OPT_ETRANSFER_EMAIL = 'us_etransfer_email';
|
||||
public const OPT_HST_RATE = 'us_hst_rate';
|
||||
|
||||
public function publishableKey(): string {
|
||||
return (string) get_option( self::OPT_PUBLISHABLE, '' );
|
||||
@@ -39,6 +40,13 @@ class StudioSettings {
|
||||
return (string) get_option( self::OPT_ETRANSFER_EMAIL, '' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Default HST/tax rate as a percentage (e.g. 13.0). 0 means no tax.
|
||||
*/
|
||||
public function hstRate(): float {
|
||||
return max( 0.0, (float) get_option( self::OPT_HST_RATE, 0 ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Stripe is configured. When false the platform falls back to
|
||||
* e-transfer billing and card processing is unavailable.
|
||||
@@ -61,6 +69,7 @@ class StudioSettings {
|
||||
$mode = $this->mode();
|
||||
$currency = $this->currency();
|
||||
$etransferEmail = $this->etransferEmail();
|
||||
$hstRate = $this->hstRate();
|
||||
$stripeConfigured = $this->isStripeConfigured();
|
||||
|
||||
include USC_PLUGIN_DIR . 'templates/admin/settings.php';
|
||||
@@ -75,6 +84,8 @@ class StudioSettings {
|
||||
update_option( self::OPT_MODE, 'live' === $mode ? 'live' : 'test' );
|
||||
update_option( self::OPT_CURRENCY, strtoupper( sanitize_text_field( wp_unslash( $_POST['currency'] ?? 'CAD' ) ) ) );
|
||||
update_option( self::OPT_ETRANSFER_EMAIL, sanitize_email( wp_unslash( $_POST['etransfer_email'] ?? '' ) ) );
|
||||
$hstRate = isset( $_POST['hst_rate'] ) ? (float) $_POST['hst_rate'] : 0.0;
|
||||
update_option( self::OPT_HST_RATE, max( 0.0, $hstRate ) );
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user