class-wc-payments-captured-event-note.php 12.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
<?php
/**
 * Class WC_Payments_Captured_Event_Note
 *
 * @package WooCommerce\Payments
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Utility class generating detailed captured note for successful payments.
 */
class WC_Payments_Captured_Event_Note {
	const HTML_BLACK_BULLET = '<span style="font-size: 7px;vertical-align: middle;">&#9679;</span>';
	const HTML_WHITE_BULLET = '<span style="font-size: 7px;vertical-align: middle;">&#9675;</span>';
	const HTML_SPACE        = '&nbsp;';
	const HTML_BR           = '<br>';

	/**
	 * Captured event data.
	 *
	 * @var array
	 */
	private $captured_event;

	/**
	 * Constructor.
	 *
	 * @param  array $captured_event Captured event data.
	 *
	 * @throws Exception
	 */
	public function __construct( array $captured_event ) {
		$is_captured_event = isset( $captured_event['type'] ) && 'captured' === $captured_event['type'];
		if ( ! $is_captured_event ) {
			throw new Exception( 'Not a captured event' );
		}

		$this->captured_event = $captured_event;
	}

	/**
	 * Generate the HTML note.
	 *
	 * @return string
	 */
	public function generate_html_note(): string {

		$lines = [];

		$fx_string = $this->compose_fx_string();
		if ( null !== $fx_string ) {
			$lines[] = $fx_string;
		}

		$lines[] = $this->compose_fee_string();

		$fee_breakdown_lines = $this->compose_fee_break_down();
		if ( null !== $fee_breakdown_lines ) {
			$lines = array_merge( $lines, $fee_breakdown_lines );
		}

		$lines[] = $this->compose_net_string();

		$html = '';
		foreach ( $lines as $line ) {
			$html .= self::HTML_BR . $line . PHP_EOL;
		}

		return '<div class="captured-event-details" style="line-height: 0.8;padding-top: 15px;">' . PHP_EOL
				. $html
				. '</div>';
	}

	/**
	 * Generate FX string.
	 *
	 * @return string|null
	 */
	public function compose_fx_string() {
		if ( ! $this->is_fx_event() ) {
			return null;
		}

		$customer_currency = $this->captured_event['transaction_details']['customer_currency'];
		$customer_amount   = $this->captured_event['transaction_details']['customer_amount'];
		$store_currency    = $this->captured_event['transaction_details']['store_currency'];
		$store_amount      = $this->captured_event['transaction_details']['store_amount'];

		return $this->format_fx( $customer_currency, $customer_amount, $store_currency, $store_amount );
	}

	/**
	 * Generate fee string.
	 *
	 * @return string
	 */
	public function compose_fee_string(): string {
		$data = $this->captured_event;

		$fee_rates      = $data['fee_rates'];
		$percentage     = $fee_rates['percentage'];
		$fixed          = WC_Payments_Utils::interpret_stripe_amount( (int) $fee_rates['fixed'] );
		$fixed_currency = $fee_rates['fixed_currency'];
		$history        = $fee_rates['history'];

		$fee_amount   = WC_Payments_Utils::interpret_stripe_amount( (int) $data['transaction_details']['store_fee'] );
		$fee_currency = $data['transaction_details']['store_currency'];

		$base_fee_label = $this->is_base_fee_only()
			? __( 'Base fee', 'woocommerce-payments' )
			: __( 'Fee', 'woocommerce-payments' );

		$is_capped = isset( $history[0]['capped'] ) && true === $history[0]['capped'];

		if ( $this->is_base_fee_only() && $is_capped ) {
			return sprintf(
				'%1$s (capped at %2$s): %3$s',
				$base_fee_label,
				WC_Payments_Utils::format_currency( $fixed, $fixed_currency ),
				WC_Payments_Utils::format_currency( - $fee_amount, $fee_currency )
			);
		}

		return sprintf(
			'%1$s (%2$s%% + %3$s): %4$s',
			$base_fee_label,
			self::format_fee( $percentage ),
			WC_Payments_Utils::format_currency( $fixed, $fixed_currency ),
			WC_Payments_Utils::format_currency( - $fee_amount, $fee_currency )
		);
	}

	/**
	 * Generate an array including HTML formatted breakdown lines.
	 *
	 * @return array<string>|null
	 */
	public function compose_fee_break_down() {
		$fee_history_strings = $this->get_fee_breakdown();

		if ( null === $fee_history_strings ) {
			return null;
		}

		if ( 0 === count( $fee_history_strings ) ) {
			return null;
		}

		$res = [];
		foreach ( $fee_history_strings as $type => $fee ) {
			$res[] = self::HTML_BLACK_BULLET . ' ' . ( 'discount' === $type
					? $fee['label']
					: $fee
				);

			if ( 'discount' === $type ) {
				$res[] = str_repeat( self::HTML_SPACE . ' ', 2 ) . self::HTML_WHITE_BULLET . ' ' . $fee['variable'];
				$res[] = str_repeat( self::HTML_SPACE . ' ', 2 ) . self::HTML_WHITE_BULLET . ' ' . $fee['fixed'];
			}
		}

		return $res;
	}

	/**
	 * Generate net string.
	 *
	 * @return string
	 */
	public function compose_net_string(): string {
		$data = $this->captured_event['transaction_details'];

		$net = WC_Payments_Utils::interpret_stripe_amount( (int) $data['store_amount'] - $data['store_fee'] );

		return sprintf(
			/* translators: %s is a monetary amount */
			__( 'Net deposit: %s', 'woocommerce-payments' ),
			WC_Payments_Utils::format_explicit_currency( $net, $data['store_currency'] )
		);
	}

	/**
	 * Returns an associative array containing fee breakdown.
	 * Keys are fee types such as base, additional-fx, etc, except for "discount" that is an associative array including more discount details.
	 *
	 * @return array|null
	 */
	public function get_fee_breakdown() {
		$data = $this->captured_event;

		if ( ! isset( $data['fee_rates']['history'] ) ) {
			return null;
		}

		$history = $data['fee_rates']['history'];

		// Hide breakdown when there's only a base fee.
		if ( $this->is_base_fee_only() ) {
			return null;
		}

		$fee_history_strings = [];

		foreach ( $history as $fee ) {
			$label_type = $fee['type'];
			if ( isset( $fee['additional_type'] ) ) {
				$label_type .= '-' . $fee['additional_type'];
			}

			$percentage_rate = (float) $fee['percentage_rate'];
			$fixed_rate      = (int) $fee['fixed_rate'];
			$currency        = strtoupper( $fee['currency'] );
			$is_capped       = isset( $fee['capped'] ) && true === $fee['capped'];

			$percentage_rate_formatted = self::format_fee( $percentage_rate );
			$fix_rate_formatted        = WC_Payments_Utils::format_currency(
				WC_Payments_Utils::interpret_stripe_amount( $fixed_rate ),
				$currency
			);

			$label = sprintf(
				$this->fee_label_mapping( $fixed_rate, $is_capped )[ $label_type ],
				$percentage_rate_formatted,
				$fix_rate_formatted
			);

			if ( 'discount' === $label_type ) {
				$fee_history_strings[ $label_type ] = [
					'label'    => $label,
					'variable' => sprintf(
						/* translators: %s is a percentage number */
						__( 'Variable fee: %s', 'woocommerce-payments' ),
						$percentage_rate_formatted
					) . '%',
					'fixed'    => sprintf(
						/* translators: %s is a monetary amount */
						__( 'Fixed fee: %s', 'woocommerce-payments' ),
						$fix_rate_formatted
					),
				];
			} else {
				$fee_history_strings[ $label_type ] = $label;
			}
		}

		return $fee_history_strings;
	}

	/**
	 * Check if this is a FX event.
	 *
	 * @return bool
	 */
	private function is_fx_event(): bool {
		$customer_currency = $this->captured_event['transaction_details']['customer_currency'] ?? null;
		$store_currency    = $this->captured_event['transaction_details']['store_currency'] ?? null;

		return ! (
			is_null( $customer_currency )
			|| is_null( $store_currency )
			|| $customer_currency === $store_currency
		);
	}

	/**
	 * Return a boolean indicating whether only fee applied is the base fee.
	 *
	 * @return bool True if the only applied fee is the base fee
	 */
	private function is_base_fee_only(): bool {
		if ( ! isset( $this->captured_event['fee_rates']['history'] ) ) {
			return false;
		}

		$history = $this->captured_event['fee_rates']['history'];

		return 1 === count( $history ) && 'base' === $history[0]['type'];
	}

	/**
	 * Get the mapping format for all types of fees.
	 *
	 * @param  int  $fixed_rate Fixed rate amount in Stripe format.
	 * @param  bool $is_capped True if the fee is capped.
	 *
	 * @return array An associative array with keys are fee types, values are string formats.
	 */
	private function fee_label_mapping( int $fixed_rate, bool $is_capped ) {
		$res = [];

		$res['base'] = $is_capped
			/* translators: %2$s is the capped fee */
			? __( 'Base fee: capped at %2$s', 'woocommerce-payments' )
			:
			( 0 !== $fixed_rate
				/* translators: %1$s% is the fee percentage and %2$s is the fixed rate */
				? __( 'Base fee: %1$s%% + %2$s', 'woocommerce-payments' )
				/* translators: %1$s% is the fee percentage */
				: __( 'Base fee: %1$s%%', 'woocommerce-payments' )
			);

		$res['additional-international'] = 0 !== $fixed_rate
			/* translators: %1$s% is the fee percentage and %2$s is the fixed rate */
			? __( 'International card fee: %1$s%% + %2$s', 'woocommerce-payments' )
			/* translators: %1$s% is the fee percentage */
			: __( 'International card fee: %1$s%%', 'woocommerce-payments' );

		$res['additional-fx'] = 0 !== $fixed_rate
			/* translators: %1$s% is the fee percentage and %2$s is the fixed rate */
			? __( 'Foreign exchange fee: %1$s%% + %2$s', 'woocommerce-payments' )
			/* translators: %1$s% is the fee percentage */
			: __( 'Foreign exchange fee: %1$s%%', 'woocommerce-payments' );

		$res['additional-wcpay-subscription'] = 0 !== $fixed_rate
			/* translators: %1$s% is the fee percentage and %2$s is the fixed rate */
			? __( 'Subscription transaction fee: %1$s%% + %2$s', 'woocommerce-payments' )
			/* translators: %1$s% is the fee percentage */
			: __( 'Subscription transaction fee: %1$s%%', 'woocommerce-payments' );

		$res['discount'] = __( 'Discount', 'woocommerce-payments' );

		return $res;
	}

	/**
	 * Return a given decimal fee as a percentage with a maximum of 3 decimal places.
	 *
	 * @param  float $percentage Percentage as float.
	 *
	 * @return string
	 */
	private function format_fee( float $percentage ): string {
		return (string) round( $percentage * 100, 3 );
	}

	/**
	 * Format FX string based on the two provided currencies.
	 *
	 * @param  string $from_currency 3-letter code for original currency.
	 * @param  int    $from_amount Amount (Stripe-type) for original currency.
	 * @param  string $to_currency 3-letter code for converted currency.
	 * @param  int    $to_amount Amount (Stripe-type) for converted currency.
	 *
	 * @return string Formatted FX string.
	 */
	private function format_fx(
		string $from_currency,
		int $from_amount,
		string $to_currency,
		int $to_amount
	): string {

		$exchange_rate = (float) ( 0 !== $from_amount
			? $to_amount / $from_amount
			: 0 );

		if ( WC_Payments_Utils::is_zero_decimal_currency( strtolower( $to_currency ) ) ) {
			$exchange_rate *= 100;
		}

		if ( WC_Payments_Utils::is_zero_decimal_currency( strtolower( $from_currency ) ) ) {
			$exchange_rate /= 100;
		}

		$to_display_amount = WC_Payments_Utils::interpret_stripe_amount( $to_amount, $to_currency );

		return sprintf(
			'%1$s → %2$s: %3$s',
			self::format_explicit_currency_with_base( 1, $from_currency, $to_currency, true ),
			self::format_exchange_rate( $exchange_rate, $to_currency ),
			WC_Payments_Utils::format_explicit_currency( $to_display_amount, $to_currency, false )
		);

	}

	/**
	 * Format exchange rate.
	 *
	 * @param  float  $rate Exchange rate.
	 * @param  string $currency 3-letter currency code.
	 *
	 * @return string
	 */
	private function format_exchange_rate( float $rate, string $currency ): string {
		$num_decimals = $rate > 1 ? 5 : 6;
		$formatted    = WC_Payments_Utils::format_explicit_currency(
			$rate,
			$currency,
			true,
			[ 'decimals' => $num_decimals ]
		);

		$func_remove_ending_zeros = function( $str ) {
			return rtrim( $str, '0' );
		};

		// Remove ending zeroes after the decimal separator if they exist.
		return implode(
			' ',
			array_map(
				$func_remove_ending_zeros,
				explode( ' ', $formatted )
			)
		);
	}

	/**
	 * Format amount for a given currency but according to the base currency's format.
	 *
	 * @param  float  $amount Amount.
	 * @param  string $currency 3-letter currency code.
	 * @param  string $base_currency 3-letter base currency code.
	 * @param  bool   $skip_symbol Optional. If true, trims off the short currency symbol. Default false.
	 *
	 * @return string
	 */
	private function format_explicit_currency_with_base( float $amount, string $currency, string $base_currency, bool $skip_symbol = false ) {
		$custom_format = WC_Payments_Utils::get_currency_format_for_wc_price( $base_currency );
		unset( $custom_format['currency'] );

		if ( 0 === WC_Payments_Utils::get_currency_format_for_wc_price( $currency )['decimals'] ) {
			unset( $custom_format['decimals'] );
		}

		return WC_Payments_Utils::format_explicit_currency( $amount, $currency, $skip_symbol, $custom_format );
	}
}