renewals = $renewals; $this->runner = $runner; $this->cron = $cron; $this->settings = $settings; } /** * Registers the routes. * * @since 0.1.0 * * @return void */ public function register_routes() { $permission = Permissions::require_capability( Capabilities::MANAGE_INVOICES ); $base = '/' . $this->rest_base; register_rest_route( $this->namespace, $base . '/status', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'status' ), 'permission_callback' => $permission, ) ); register_rest_route( $this->namespace, $base . '/upcoming', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'upcoming' ), 'permission_callback' => $permission, 'args' => array( 'days' => array( 'type' => 'integer', 'default' => 30, 'minimum' => 0, 'maximum' => 365, 'sanitize_callback' => 'absint', ), ), ) ); register_rest_route( $this->namespace, $base . '/run', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'run' ), 'permission_callback' => $permission, ) ); } /** * Health of the background jobs and the automation settings. * * @since 0.1.0 * * @return WP_REST_Response */ public function status(): WP_REST_Response { return rest_ensure_response( array_merge( $this->cron->health(), array( 'settings' => array( 'invoice_ahead_days' => (int) $this->settings->get( 'invoice_ahead_days' ), 'renewal_combine' => (bool) $this->settings->get( 'renewal_combine' ), 'auto_suspend_enabled' => (bool) $this->settings->get( 'auto_suspend_enabled' ), 'late_fee_enabled' => (bool) $this->settings->get( 'late_fee_enabled' ), 'grace_days' => (int) $this->settings->get( 'grace_days' ), ), ) ) ); } /** * Renewals that fall due in the next days and are not invoiced yet. * * @since 0.1.0 * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function upcoming( $request ) { $plan = $this->renewals->upcoming( Date::today_gmt(), (int) $request['days'] ); $present = function ( array $item ): array { return array( 'kind' => $item['kind'], 'id' => $item['id'], 'customer_id' => $item['customer_id'], 'label' => $item['label'], 'period_start' => $item['period'], 'amount' => $item['amount'] ?? 0, 'amount_formatted' => $this->settings->format_money( (int) ( $item['amount'] ?? 0 ) ), 'reason' => $item['skip'] ?? '', ); }; return rest_ensure_response( array( 'due' => array_map( $present, $plan['due'] ), 'skipped' => array_map( $present, $plan['skipped'] ), ) ); } /** * Runs the daily billing job now. * * @since 0.1.0 * * @return WP_REST_Response */ public function run(): WP_REST_Response { return rest_ensure_response( $this->runner->run() ); } }