service = $service; $this->credits = $credits; $this->customers = $customers; $this->settings = $settings; } /** * Registers the routes. * * @since 0.1.0 * * @return void */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_ledger' ), 'permission_callback' => Permissions::require_capability( Capabilities::MANAGE_PAYMENTS ), 'args' => array( 'customer_id' => array( 'type' => 'integer', 'required' => true, 'sanitize_callback' => 'absint', ), ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'adjust' ), 'permission_callback' => Permissions::require_capability( Capabilities::MANAGE_PAYMENTS ), ), ) ); } /** * Returns a customer's balance and ledger. * * @since 0.1.0 * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_ledger( $request ) { $customer_id = (int) $request['customer_id']; if ( null === $this->customers->find( $customer_id ) ) { return $this->error( 'hostkhata_not_found', __( 'Customer not found.', 'hostkhata' ), 404 ); } return rest_ensure_response( $this->present( $customer_id ) ); } /** * Adds or removes credit. * * @since 0.1.0 * * @param WP_REST_Request $request Request: `customer_id`, `amount` (signed minor units), `reason`. * @return WP_REST_Response|WP_Error */ public function adjust( $request ) { $body = $this->request_body( $request ); $customer_id = Sanitizer::absint( $body['customer_id'] ?? 0 ); $result = $this->service->adjust( $customer_id, $body ); return is_wp_error( $result ) ? $result : rest_ensure_response( $this->present( $customer_id ) ); } /** * Shapes a balance and ledger. * * @param int $customer_id Customer id. * @return array */ private function present( int $customer_id ): array { $balance = $this->credits->balance( $customer_id ); $entries = array_map( function ( array $entry ) { $entry['amount_formatted'] = $this->settings->format_money( $entry['amount'] ); $entry['balance_formatted'] = $this->settings->format_money( $entry['balance_after'] ); $entry['created_at'] = str_replace( ' ', 'T', (string) $entry['created_at_gmt'] ) . 'Z'; return $entry; }, $this->credits->for_customer( $customer_id ) ); return array( 'customer_id' => $customer_id, 'balance' => $balance, 'balance_formatted' => $this->settings->format_money( $balance ), 'entries' => $entries, ); } }