'Write what the shop answers for its products\' prices to a JSON file: before and after an update, then compare the two files. It reads only (no setting, rule or product changes); --all-states is for a copy of a shop and needs --copy.', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'file', 'description' => 'The file to write.', 'optional' => false ), array( 'type' => 'assoc', 'name' => 'products', 'description' => 'Only the first published products, by id.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'roles', 'description' => 'Also as one customer of each role that has role prices.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'classes', 'description' => 'Also as one customer of each customer class that counts today.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'all-states', 'description' => 'Under each pricing mode and each value of the two price switches (eight states), not the shop\'s own alone. For a copy of a shop: no option is written, but the precomputed mode stores its fingerprints and a customer\'s audience may be stored. Needs --copy.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'copy', 'description' => 'Says this site is a copy of a shop, not the shop: what --all-states asks for.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers audit', array( __CLASS__, 'audit' ), array( 'shortdesc' => 'List the rules, rows and settings on this shop whose meaning an offers fix changes (reads only).', 'synopsis' => array( array( 'type' => 'assoc', 'name' => 'format', 'description' => 'text (the default) or json.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers line-record', array( __CLASS__, 'line_record' ), array( 'shortdesc' => 'The record of the offers on each order line (Phase 0b): switch it on or off, or say what is on. On: the part\'s two tables are made, then every new order\'s lines are stamped with the discount rules that matched them. On and off each empty the stored recommendation cards and purge the page cache once, so the next visits build them again: on a busy shop, switch it at a quiet hour. Off also takes away the part\'s waiting background run.', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'what', 'description' => 'on, off or status.', 'optional' => false, 'options' => array( 'on', 'off', 'status' ) ), ), ) ); WP_CLI::add_command( 'aieo offers parts', array( 'AIEO_DMM_Offer_Parts', 'cli' ), array( 'shortdesc' => 'The offers\' parts (11.3.14: every part comes on by itself once the shop reads the one offers table): status (each part, whether it is on, and what keeps it off; --format=json for a machine), on , off (a person\'s off: the part stays off, the switch-on never switches it on again), run (the switch-on run to its end in this command, one step a run as the queue runs them; --queue: queued instead). Parts: record, access, life, signals:, measure, watch, channels:, wizard.', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'action', 'description' => 'status, on, off or run.', 'optional' => true, 'options' => array( 'status', 'on', 'off', 'run' ) ), array( 'type' => 'positional', 'name' => 'part', 'description' => 'on and off: the part.', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'format', 'description' => 'status: table (the default) or json.', 'optional' => true, 'options' => array( 'table', 'json' ) ), array( 'type' => 'flag', 'name' => 'queue', 'description' => 'run: queue the switch-on rather than run it here.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers stamps', array( __CLASS__, 'stamps' ), array( 'shortdesc' => 'List the stamped order lines and whether each stamp agrees with what the line was charged (reads only).', 'synopsis' => array( array( 'type' => 'assoc', 'name' => 'since', 'description' => 'Only orders made on or after this day of the shop (Y-m-d).', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'order', 'description' => 'Only this order.', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'format', 'description' => 'table (the default), csv or json.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers overlaps', array( __CLASS__, 'overlaps' ), array( 'shortdesc' => 'List the intervals in which two running discount rules shared products: which one was kept, by which step, from when to when (reads only, but for --run).', 'synopsis' => array( array( 'type' => 'flag', 'name' => 'open', 'description' => 'Only the intervals that are open now.', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'offer', 'description' => 'Only the intervals that name this rule, as bd:12.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'run', 'description' => 'Work the overlaps out now, in the foreground, before listing them.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'notice', 'description' => 'Print the daily notice instead: the rules that change no price, the steps beside an overlap.', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'format', 'description' => 'table (the default), csv or json.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers store', array( __CLASS__, 'store' ), array( 'shortdesc' => 'The move to the one offers table: status (reads only), shadow (run schema step 7 if it has not run, copy every rule now and write both stores), verify (compare the two stores now), switch (read the one table; refused unless the last comparison was clean), hold (no automatic switch until one by hand; the mode stays), rollback (read the old tables again at once; both stores stay written, and a new comparison is needed before the next switch), legacy --yes (back to the old tables altogether; nothing starts again by itself).', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'action', 'description' => 'status, shadow, verify, switch, hold, rollback or legacy.', 'optional' => false ), array( 'type' => 'assoc', 'name' => 'products', 'description' => 'verify: only the first published products, by id.', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'format', 'description' => 'status: text (the default) or json.', 'optional' => true ), array( 'type' => 'flag', 'name' => 'yes', 'description' => 'legacy: says you mean it.', 'optional' => true ), ), ) ); WP_CLI::add_command( 'aieo offers explain', array( __CLASS__, 'explain' ), array( 'shortdesc' => 'What a customer is charged for a product, or was at an instant, and why: each offer that ran then (read at its revision in force then) with its role, what it gives alone and what it adds; the winner, the struck price and until when the answer holds (reads only).', 'synopsis' => array( array( 'type' => 'positional', 'name' => 'product', 'description' => 'The product or variation id.', 'optional' => false ), array( 'type' => 'assoc', 'name' => 'user', 'description' => 'The customer, by user id (the public when left out).', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'at', 'description' => 'The instant, GMT, as Y-m-d H:i:s (now when left out).', 'optional' => true ), array( 'type' => 'assoc', 'name' => 'format', 'description' => 'table (the default) or json.', 'optional' => true ), ), ) ); } const EXPLAIN_FIELDS = array( 'id', 'rev', 'kind', 'group', 'role', 'alone', 'marg', 'w' ); public static function explain( $args, $assoc ) { $answer = self::explain_action( (array) $args, (array) $assoc ); if ( ! $answer['ok'] ) { WP_CLI::error( $answer['message'] ); } if ( 'json' === $answer['format'] ) { WP_CLI::line( self::encode( $answer['answer'] ) ); return; } foreach ( $answer['lines'] as $line ) { WP_CLI::line( $line ); } if ( $answer['rows'] ) { WP_CLI\Utils\format_items( 'table', $answer['rows'], self::EXPLAIN_FIELDS ); } foreach ( $answer['tail'] as $line ) { WP_CLI::line( $line ); } } public static function explain_action( array $args, array $assoc = array() ) { $out = array( 'ok' => false, 'message' => '', 'format' => isset( $assoc['format'] ) ? (string) $assoc['format'] : 'table', 'answer' => array(), 'lines' => array(), 'rows' => array(), 'tail' => array(), ); if ( ! in_array( $out['format'], array( 'table', 'json' ), true ) ) { $out['message'] = '--format is table or json.'; return $out; } if ( ! class_exists( 'AIEO_DMM_Price_Resolver' ) || ! function_exists( 'wc_get_product' ) ) { $out['message'] = 'The price resolver or WooCommerce is not loaded on this site.'; return $out; } $product_id = isset( $args[0] ) && is_numeric( $args[0] ) ? (int) $args[0] : 0; $product = $product_id > 0 ? wc_get_product( $product_id ) : null; if ( ! $product ) { $out['message'] = sprintf( 'There is no product #%s.', isset( $args[0] ) ? (string) $args[0] : '' ); return $out; } $user_id = isset( $assoc['user'] ) ? (int) $assoc['user'] : 0; $customer = $user_id > 0 ? AIEO_DMM_Price_Resolver::customer( $user_id ) : null; if ( $user_id > 0 && null === $customer ) { $out['message'] = sprintf( 'There is no user #%d.', $user_id ); return $out; } $at = isset( $assoc['at'] ) ? (string) $assoc['at'] : gmdate( 'Y-m-d H:i:s' ); try { $answer = AIEO_DMM_Price_Resolver::explain( $product_id, $customer, $at ); } catch ( InvalidArgumentException $e ) { $out['message'] = '--at takes an instant in GMT, as Y-m-d H:i:s.'; return $out; } $out['ok'] = true; $out['answer'] = $answer; $none = static function ( $value ) { return null === $value ? 'none' : self::number( $value ); }; $who = null === $customer ? 'the public' : sprintf( 'user #%d (roles: %s; priced roles: %s; classes: %s)', $user_id, $customer['roles'] ? implode( ', ', $customer['roles'] ) : 'none', $customer['price_roles'] ? implode( ', ', $customer['price_roles'] ) : 'none', $customer['class_ids'] ? implode( ', ', $customer['class_ids'] ) : 'none' ); $sku = (string) $product->get_sku(); $out['lines'] = array( sprintf( 'Product #%d%s, for %s, at %s GMT.', $product_id, '' !== $sku ? ' (' . $sku . ')' : '', $who, $answer['at'] ), sprintf( 'List price %s (%s); option %s; sale price %s.', self::number( $answer['list'] ), $answer['list_src'], self::number( $answer['option'] ), $none( $answer['sale'] ) ), ); if ( is_array( $answer['cost'] ) ) { $out['lines'][] = sprintf( 'Cost %s (%s): %s', self::number( $answer['cost']['value'] ), $answer['cost']['basis'], $answer['cost']['note'] ); } if ( ! $answer['offers'] ) { $out['lines'][] = 'No offer ran on it then.'; } foreach ( $answer['offers'] as $offer ) { $out['rows'][] = array( 'id' => (int) $offer['id'], 'rev' => (int) $offer['rev'], 'kind' => (string) $offer['kind'], 'group' => (string) $offer['group'], 'role' => (string) $offer['role'], 'alone' => self::number( $offer['alone'] ), 'marg' => self::number( $offer['marg'] ), 'w' => (int) $offer['w'], ); } $out['tail'] = array( sprintf( 'Price %s, won by %s; struck price %s; floor %s.', self::number( $answer['price'] ), $answer['winner'], $none( $answer['strike'] ), $none( $answer['floor'] ) ), '' !== (string) $answer['valid_until'] ? sprintf( 'The answer holds until %s GMT.', $answer['valid_until'] ) : 'No start or end of an offer lies ahead of it.', ); if ( $answer['approximate'] ) { $out['tail'][] = 'Approximate: ' . implode( ' ', $answer['why'] ); } return $out; } const STORE_ACTIONS = array( 'status', 'shadow', 'verify', 'switch', 'hold', 'rollback', 'legacy' ); const SCHEMA_NOT_RUN = 'Schema step 7 has not run: it runs at the update\'s first request or when an administrator opens the dashboard; wp aieo offers store shadow runs it now.'; const LEGACY_LEAVES = 'The readers read the old tables, and the discount, gift and class forms save there first, as before the move (each save is still copied to the one table, as before the move). The one table keeps its copies, and the free-shipping rules, which live there in every mode. Nothing starts again by itself: the move begins again only with wp aieo offers store shadow.'; public static function store( $args, $assoc ) { $action = isset( $args[0] ) ? (string) $args[0] : ''; $answer = self::store_action( $action, (array) $assoc ); if ( ! $answer['ok'] ) { WP_CLI::error( $answer['message'] ); } if ( 'status' === $action ) { if ( isset( $assoc['format'] ) && 'json' === $assoc['format'] ) { WP_CLI::line( self::encode( $answer['status'] ) ); return; } foreach ( self::store_lines( $answer['status'] ) as $line ) { WP_CLI::line( $line ); } return; } WP_CLI::success( $answer['message'] ); } public static function store_action( $action, array $assoc = array() ) { $action = (string) $action; if ( ! in_array( $action, self::STORE_ACTIONS, true ) ) { return array( 'ok' => false, 'message' => 'Say what to do: ' . implode( ', ', self::STORE_ACTIONS ) . '.', 'status' => array() ); } if ( ! class_exists( 'AIEO_DMM_Offer_Store' ) || ! class_exists( 'AIEO_DMM_Offer_Store_Compare' ) ) { return array( 'ok' => false, 'message' => 'The offers\' store is not loaded on this site.', 'status' => array() ); } $steps = ''; if ( 'status' !== $action && (int) get_option( 'aieo_db_version', 0 ) < AIEO_DMM_Offer_Store_Compare::SCHEMA_STEP ) { if ( 'shadow' !== $action ) { return array( 'ok' => false, 'message' => 'The one offers table is not ready on this site. ' . self::SCHEMA_NOT_RUN, 'status' => self::store_status() ); } $ran = self::run_schema_steps(); if ( true !== $ran ) { return array( 'ok' => false, 'message' => $ran, 'status' => self::store_status() ); } $steps = sprintf( 'Schema step %d ran (the site is at step %d). ', AIEO_DMM_Offer_Store_Compare::SCHEMA_STEP, (int) get_option( 'aieo_db_version', 0 ) ); } $message = ''; switch ( $action ) { case 'shadow': AIEO_DMM_Offer_Store_Compare::seed_now(); $message = $steps . 'Every rule is copied and both stores are written from now on. The readers still read the old tables.'; break; case 'verify': if ( 'legacy' === AIEO_DMM_Offer_Store::mode() ) { return array( 'ok' => false, 'message' => 'The shop is on its old tables: seed it first (wp aieo offers store shadow).', 'status' => self::store_status() ); } $report = AIEO_DMM_Offer_Store_Compare::verify( isset( $assoc['products'] ) ? max( 0, (int) $assoc['products'] ) : 0 ); $blocking = AIEO_DMM_Offer_Store_Compare::blocking( $report ); $message = sprintf( '%d products and variations compared for %d audiences: %d blocking differences%s.', (int) $report['products'], count( (array) $report['audiences'] ), $blocking, $blocking ? ' (' . self::encode_inline( $report['differences'] ) . ')' : '' ); break; case 'switch': $switched = AIEO_DMM_Offer_Store_Compare::switch_now(); if ( is_wp_error( $switched ) ) { return array( 'ok' => false, 'message' => $switched->get_error_message(), 'status' => self::store_status() ); } $message = 'The readers read the one offers table. Both stores stay written: rollback returns to the old tables at once.'; break; case 'hold': AIEO_DMM_Offer_Store_Compare::hold(); $message = sprintf( 'The shop stays in mode %s and will not switch by itself; the daily comparison still runs. To switch by hand: wp aieo offers store verify, then wp aieo offers store switch (wp aieo offers store shadow seeds again and lets it switch by itself).', AIEO_DMM_Offer_Store::mode() ); break; case 'rollback': AIEO_DMM_Offer_Store_Compare::rollback(); $message = 'The readers read the old tables again (mode shadow). Both stores stay written, so a later switch loses nothing. The shop will not switch by itself: a new comparison is needed before the next switch (wp aieo offers store verify, then wp aieo offers store switch). To leave the one table altogether: wp aieo offers store legacy --yes.'; break; case 'legacy': if ( empty( $assoc['yes'] ) ) { return array( 'ok' => false, 'message' => 'This returns the shop to its old tables altogether. ' . self::LEGACY_LEAVES . ' Add --yes to do it.', 'status' => self::store_status() ); } AIEO_DMM_Offer_Store_Compare::to_legacy(); $message = 'The shop is back on its old tables altogether (mode legacy). ' . self::LEGACY_LEAVES; break; } return array( 'ok' => true, 'message' => $message, 'status' => self::store_status() ); } private static function run_schema_steps() { global $wpdb; if ( ! function_exists( 'aieo_run_db_migrations' ) ) { return 'The plugin\'s numbered schema steps are not loaded on this request: open the dashboard as an administrator, then run this again.'; } aieo_run_db_migrations(); $now = (int) get_option( 'aieo_db_version', 0 ); if ( $now >= AIEO_DMM_Offer_Store_Compare::SCHEMA_STEP ) { return true; } return sprintf( 'Schema step %d did not complete (the site is at step %d)%s. Nothing was copied, and the shop reads its old tables as before.', AIEO_DMM_Offer_Store_Compare::SCHEMA_STEP, $now, '' !== (string) $wpdb->last_error ? ': ' . $wpdb->last_error : ': another request may be running the steps, so try again in a minute' ); } public static function store_status() { global $wpdb; $schedules = array(); $table = $wpdb->prefix . 'aieo_dmm_discount_schedules'; if ( ! function_exists( 'aieo_dmm_table_exists' ) || aieo_dmm_table_exists( $table ) ) { $today = current_time( 'Y-m-d' ); $suppress = $wpdb->suppress_errors( true ); $schedules = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, product_id, percent, date_from, date_to FROM {$table} WHERE active = 1 AND percent > 0 AND (date_from IS NULL OR date_from <= %s) AND (date_to IS NULL OR date_to >= %s) ORDER BY id ASC LIMIT 200", $today, $today ), ARRAY_A ); $wpdb->suppress_errors( $suppress ); } $report = AIEO_DMM_Offer_Store_Compare::report(); return array( 'mode' => AIEO_DMM_Offer_Store::mode(), 'schema' => (int) get_option( 'aieo_db_version', 0 ), 'blocking' => AIEO_DMM_Offer_Store_Compare::blocking( $report ), 'report' => $report, 'held' => class_exists( 'AIEO_DMM_Offers_Held' ) ? AIEO_DMM_Offers_Held::all() : array(), 'pinned' => AIEO_DMM_Offer_Store::pinned(), 'schedules' => $schedules, 'not_in_old_tables' => AIEO_DMM_Offer_Store_Compare::not_in_the_old_tables(), ); } public static function store_lines( array $status ) { $report = $status['report']; $lines = array( 'Mode: ' . $status['mode'] . ( 'legacy' === $status['mode'] ? ' (the old tables are read and written)' : ( 'shadow' === $status['mode'] ? ' (both stores are written; the old tables are read)' : ' (both stores are written; the one table is read)' ) ), 'Schema step: ' . $status['schema'] . ( $status['schema'] < AIEO_DMM_Offer_Store_Compare::SCHEMA_STEP ? '. ' . self::SCHEMA_NOT_RUN : '' ), 'Landed: ' . ( '' !== (string) $report['landed_gmt'] ? $report['landed_gmt'] . ' GMT' : 'not yet seen' ) . ( '' !== (string) $report['held_gmt'] ? '; held by hand ' . $report['held_gmt'] . ' GMT: it will not switch by itself' : ( false === $report['auto'] ? '; rolled back by hand: it will not switch by itself' : '' ) ), 'Last comparison: ' . ( '' !== (string) $report['finished_gmt'] ? 'finished ' . $report['finished_gmt'] . ' GMT' : ( '' !== (string) $report['started_gmt'] ? 'started ' . $report['started_gmt'] . ' GMT, not finished' : 'none' ) ) . sprintf( '; %d products, %d audiences', (int) $report['products'], count( (array) $report['audiences'] ) ), 'Blocking differences: ' . $status['blocking'] . ( $report['differences'] ? ' ' . self::encode_inline( $report['differences'] ) : '' ), ); if ( ! empty( $report['finding']['blocking'] ) ) { $lines[] = sprintf( 'Finding: %d products priced otherwise by the old store, found %s GMT (%s); the mode stays %s, only a command changes it; %s', (int) $report['finding']['products'], (string) $report['finding']['gmt'], self::encode_inline( (array) $report['finding']['kinds'] ), $status['mode'], '' !== (string) $report['finding']['told_gmt'] ? 'told on the staff digest ' . $report['finding']['told_gmt'] . ' GMT' : 'not told on the staff digest (no recipient)' ); } foreach ( (array) $report['samples'] as $sample ) { $lines[] = sprintf( ' %s: product %d, %s: %s against %s', $sample['kind'], (int) $sample['product'], $sample['audience'], self::encode_inline( $sample['old'] ), self::encode_inline( $sample['new'] ) ); } $lines = array_merge( $lines, self::not_in_old_tables_lines( (array) ( $status['not_in_old_tables'] ?? array() ) ) ); $lines[] = 'Held rules: ' . ( $status['held'] ? implode( ', ', $status['held'] ) : 'none' ); $lines[] = 'Pinned gift offers: ' . ( $status['pinned'] ? count( $status['pinned'] ) . ' (each keeps its old cart reading until it is saved in the admin; saving it applies what is said below)' : 'none' ); foreach ( $status['pinned'] as $name => $reasons ) { $words = AIEO_DMM_Offer_Store_Compare::gift_reading_sentences( (array) $reasons ); $lines[] = sprintf( ' %s%s: %s', $name, self::offer_label( (string) $name ), $words ? implode( ' ', $words ) : 'no reason is recorded' ); } $lines[] = 'Schedule rows that run today (the one table does not read them): ' . count( $status['schedules'] ); foreach ( $status['schedules'] as $row ) { $lines[] = sprintf( ' #%d: product %d, %s %%, %s to %s', (int) $row['id'], (int) $row['product_id'], $row['percent'], $row['date_from'] ? $row['date_from'] : 'always', $row['date_to'] ? $row['date_to'] : 'always' ); } foreach ( array_slice( (array) $report['history'], -5 ) as $move ) { $lines[] = sprintf( 'Moved %s GMT: %s to %s (%s)', $move['gmt'], $move['from'], $move['to'], $move['reason'] ); } return $lines; } private static function not_in_old_tables_lines( array $offers ) { $lines = array( 'Not in the old tables (no reader applies them after a rollback): ' . ( $offers ? count( $offers ) : 'none' ) ); foreach ( $offers as $offer ) { $kept = (string) ( $offer['old_row'] ?? '' ); $lines[] = sprintf( ' of:%d, %s "%s": %s%s', (int) $offer['id'], (string) $offer['type'], (string) $offer['label'], implode( ', ', (array) $offer['why'] ), '' !== $kept ? '; ' . AIEO_DMM_Offer_Store_Compare::kept_disabled_sentence( $kept ) : '' ); } return $lines; } private static function offer_label( $name ) { global $wpdb; $parts = explode( ':', (string) $name, 2 ); if ( 2 !== count( $parts ) || ! class_exists( 'AIEO_DMM_Offer_Ids' ) ) { return ''; } $id = (int) AIEO_DMM_Offer_Ids::resolve( $parts[0], (int) $parts[1] ); $label = $id > 0 ? (string) $wpdb->get_var( $wpdb->prepare( "SELECT label FROM {$wpdb->prefix}aieo_dmm_offers WHERE id = %d", $id ) ) : ''; return '' !== $label ? ' "' . $label . '"' : ''; } private static function encode_inline( $value ) { return is_scalar( $value ) ? (string) $value : (string) wp_json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); } public static function record( $args, $assoc ) { $file = isset( $args[0] ) ? (string) $args[0] : ''; if ( '' === $file ) { WP_CLI::error( 'Name the file to write.' ); } if ( ! function_exists( 'wc_get_product' ) ) { WP_CLI::error( 'WooCommerce is not active.' ); } $limit = isset( $assoc['products'] ) ? max( 0, (int) $assoc['products'] ) : 0; $products = self::shop_products( $limit ); $picked = self::shop_viewers( ! empty( $assoc['roles'] ), ! empty( $assoc['classes'] ) ); $refusal = self::all_states_refusal( (array) $assoc ); if ( '' !== $refusal ) { WP_CLI::error( $refusal ); } $states = ! empty( $assoc['all-states'] ) ? self::STATES : array( self::own_state() ); $record = array( 'v' => self::RECORD_VERSION, 'own_state' => self::own_state(), 'viewers' => $picked['viewers'], 'no_viewer' => $picked['none'], 'prices' => self::prices( $products, $picked['viewers'], $states, true ), ); $json = self::encode( $record ); if ( false === file_put_contents( $file, $json ) ) { WP_CLI::error( 'The file could not be written: ' . $file ); } WP_CLI::success( sprintf( '%d products and variations, %d viewers, %d states: %s', count( $products ), count( $picked['viewers'] ), count( $states ), $file ) ); } public static function all_states_refusal( array $assoc ) { if ( empty( $assoc['all-states'] ) || ! empty( $assoc['copy'] ) ) { return ''; } $type = function_exists( 'wp_get_environment_type' ) ? (string) wp_get_environment_type() : 'production'; return '--all-states is for a copy of a shop (this site says it is "' . $type . '"): it writes no option, but the precomputed mode stores its fingerprints and a customer\'s audience may be stored while every state is asked. Add --copy to say this site is a copy. Without --all-states, record reads only.'; } public static function prices( array $products, array $viewers, array $states = array(), $ranges = false ) { if ( ! $states ) { $states = array( self::own_state() ); } $out = array(); $was = get_current_user_id(); $ask = static function () use ( $states, $products, $viewers, $ranges, &$out ) { foreach ( $states as $state ) { $out[ $state ] = self::in_state( $state, static function () use ( $products, $viewers, $ranges ) { $block = array(); foreach ( $viewers as $viewer => $user_id ) { wp_set_current_user( (int) $user_id ); foreach ( $products as $name => $product_id ) { $block[ $viewer ][ $name ] = self::price_record( (int) $product_id, $ranges ); } } return $block; } ); } }; try { if ( class_exists( 'AIEO_DMM_Offers_Held' ) ) { AIEO_DMM_Offers_Held::looking_only( $ask ); } else { $ask(); } } finally { wp_set_current_user( $was ); } return $out; } public static function price_record( $product_id, $ranges = false ) { $product = wc_get_product( $product_id ); if ( ! $product ) { return null; } $lowest = ''; if ( class_exists( 'AIEO_Lowest_Price' ) && class_exists( 'AIEO_DMM_Price_Filter' ) && AIEO_DMM_Price_Filter::resolves() ) { $amount = AIEO_Lowest_Price::amount( $product ); $lowest = null !== $amount ? $amount : ''; } elseif ( class_exists( 'AIEO_Lowest_Price' ) ) { $worked = AIEO_Lowest_Price::work_out( $product ); $lowest = ! empty( $worked[0] ) && (float) $worked[1] > 0 ? $worked[1] : ''; } $record = array( 'regular' => self::number( $product->get_regular_price() ), 'sale' => self::number( $product->get_sale_price() ), 'price' => self::number( $product->get_price() ), 'effective' => self::number( AIEO_DMM_Pricing_Engine::instance()->get_effective_price( $product_id ) ), 'html' => self::text( (string) $product->get_price_html() ), 'lowest' => self::number( $lowest ), ); if ( $ranges && $product->is_type( 'variable' ) && method_exists( $product, 'get_variation_prices' ) ) { $shown = $product->get_variation_prices( true ); $price = array_map( 'floatval', array_values( (array) ( $shown['price'] ?? array() ) ) ); $reg = array_map( 'floatval', array_values( (array) ( $shown['regular_price'] ?? array() ) ) ); $record['range'] = array( 'price_min' => $price ? self::number( min( $price ) ) : '', 'price_max' => $price ? self::number( max( $price ) ) : '', 'regular_min' => $reg ? self::number( min( $reg ) ) : '', 'regular_max' => $reg ? self::number( max( $reg ) ) : '', ); } return $record; } public static function own_state() { $mode = 'precomputed' === (string) AIEO_DMM_Settings::get( 'pricing_mode', 'reactive' ) ? 'precomputed' : 'reactive'; $main = AIEO_DMM_Settings::get( 'apply_recipe_to_main_price', false ) ? 'on' : 'off'; $stored = class_exists( 'AIEO_Effective_Prices' ) && AIEO_Effective_Prices::is_enabled() ? 'on' : 'off'; return $mode . '.main-' . $main . '.stored-' . $stored; } public static function in_state( $state, callable $do ) { $parts = explode( '.', (string) $state ); if ( ! in_array( $state, self::STATES, true ) ) { throw new InvalidArgumentException( 'Not a state of the offers recorder: ' . $state ); } $mode = $parts[0]; $main = 'main-on' === $parts[1]; $stored = 'stored-on' === $parts[2]; $settings = get_option( AIEO_DMM_Settings::OPTION_KEY, array() ); $settings = is_array( $settings ) ? $settings : array(); $settings['pricing_mode'] = $mode; $settings['apply_recipe_to_main_price'] = $main; unset( $settings['discounts_combine'], $settings['role_prices_combine'], $settings['sale_price_combines'] ); $answer_settings = static function () use ( $settings ) { return $settings; }; $answer_flag = static function () use ( $stored ) { return $stored ? '1' : '0'; }; $keep = static function ( $value, $old_value ) { return $old_value; }; $row = $stored && ( ! class_exists( 'AIEO_DMM_Price_Filter' ) || ! AIEO_DMM_Price_Filter::resolves() ); $hooks = array( array( 'woocommerce_get_price_html', array( 'AIEO_Effective_Prices', 'maybe_filter_price_html' ), 50, 2, $row ), array( 'woocommerce_product_get_price', array( 'AIEO_Effective_Prices', 'maybe_filter_get_price' ), 90, 2, $row ), ); $had = array(); foreach ( $hooks as $i => $hook ) { $had[ $i ] = false !== has_filter( $hook[0], $hook[1] ); } $forced_was = isset( $GLOBALS['aieo_dmm_force_reactive'] ) ? $GLOBALS['aieo_dmm_force_reactive'] : null; add_filter( 'pre_option_' . AIEO_DMM_Settings::OPTION_KEY, $answer_settings ); add_filter( 'pre_option_aieo_use_effective_prices', $answer_flag ); add_filter( 'pre_update_option_' . AIEO_DMM_Settings::OPTION_KEY, $keep, 9999, 2 ); add_filter( 'pre_update_option_aieo_use_effective_prices', $keep, 9999, 2 ); foreach ( $hooks as $i => $hook ) { self::hook( $hook, $hook[4], $had[ $i ] ); } $GLOBALS['aieo_dmm_force_reactive'] = 'reactive' === $mode; AIEO_DMM_Settings::flush_memo(); AIEO_DMM_Cache::forget_request(); try { return $do(); } finally { remove_filter( 'pre_option_' . AIEO_DMM_Settings::OPTION_KEY, $answer_settings ); remove_filter( 'pre_option_aieo_use_effective_prices', $answer_flag ); remove_filter( 'pre_update_option_' . AIEO_DMM_Settings::OPTION_KEY, $keep, 9999 ); remove_filter( 'pre_update_option_aieo_use_effective_prices', $keep, 9999 ); foreach ( $hooks as $i => $hook ) { self::hook( $hook, $had[ $i ], $hook[4] ); } if ( null === $forced_was ) { unset( $GLOBALS['aieo_dmm_force_reactive'] ); } else { $GLOBALS['aieo_dmm_force_reactive'] = $forced_was; } AIEO_DMM_Settings::flush_memo(); AIEO_DMM_Cache::forget_request(); } } private static function hook( array $hook, $wanted, $is ) { if ( $wanted && ! $is ) { add_filter( $hook[0], $hook[1], $hook[2], $hook[3] ); } elseif ( ! $wanted && $is ) { remove_filter( $hook[0], $hook[1], $hook[2] ); } } private static function shop_products( $limit ) { global $wpdb; $sql = "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' ORDER BY ID ASC"; if ( $limit > 0 ) { $sql .= $wpdb->prepare( ' LIMIT %d', $limit ); } $ids = array_map( 'intval', (array) $wpdb->get_col( $sql ) ); $out = array(); foreach ( $ids as $id ) { $out[ (string) $id ] = $id; } if ( $ids ) { $in = implode( ',', $ids ); $children = (array) $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product_variation' AND post_status = 'publish' AND post_parent IN ({$in}) ORDER BY ID ASC" ); foreach ( $children as $id ) { $out[ (string) (int) $id ] = (int) $id; } } return $out; } private static function shop_viewers( $roles, $classes ) { $viewers = array( 'guest' => 0 ); $none = array(); if ( ( $roles || $classes ) && class_exists( 'AIEO_Identity_Bridge' ) && class_exists( 'AIEO_Effective_Prices' ) ) { foreach ( AIEO_Identity_Bridge::known_audience_keys() as $key ) { if ( ( $roles && 0 === strpos( $key, 'role:' ) ) || ( $classes && 0 === strpos( $key, 'tier:' ) ) ) { $user_id = (int) AIEO_Effective_Prices::representative_user_for_audience( $key ); if ( $user_id > 0 ) { $viewers[ $key ] = $user_id; } else { $none[] = $key; } } } } return array( 'viewers' => $viewers, 'none' => $none ); } const STAMP_ROWS_LIMIT = 5000; public static function line_record( $args, $assoc ) { $what = isset( $args[0] ) ? (string) $args[0] : 'status'; if ( ! class_exists( 'AIEO_DMM_Offer_Record' ) ) { WP_CLI::error( 'The record of the offers is not in this version.' ); } if ( 'on' === $what ) { if ( true !== AIEO_DMM_Offer_Parts::switch_on( 'record', true ) ) { WP_CLI::error( 'Not switched on: the part\'s two tables could not be made.' ); } WP_CLI::success( 'The record of the offers on order lines is on.' ); } elseif ( 'off' === $what ) { AIEO_DMM_Offer_Parts::switch_off( 'record', true ); WP_CLI::success( 'The record of the offers on order lines is off, and stays off. Its tables and the stamps already written stay.' ); } elseif ( 'status' !== $what ) { WP_CLI::error( 'Say on, off or status.' ); } $status = self::line_record_status(); WP_CLI::line( 'option ' . AIEO_DMM_Offer_Record::OPTION . ': ' . ( '' !== $status['option'] ? $status['option'] : 'absent' ) . ( $status['on'] ? ' (on)' : ' (off)' ) ); WP_CLI::line( 'schema ' . AIEO_DMM_Offer_Record::SCHEMA_OPTION . ': ' . ( $status['schema'] > 0 ? $status['schema'] : 'not installed' ) ); WP_CLI::line( 'the overlaps were last worked out: ' . ( '' !== $status['overlaps_last'] ? $status['overlaps_last'] . ' GMT' : 'never' ) ); } public static function line_record_status() { $option = get_option( AIEO_DMM_Offer_Record::OPTION, '' ); $last = get_option( 'aieo_dmm_offer_overlaps_last', array() ); return array( 'option' => is_scalar( $option ) ? (string) $option : '', 'on' => AIEO_DMM_Offer_Record::is_on(), 'schema' => (int) get_option( AIEO_DMM_Offer_Record::SCHEMA_OPTION, 0 ), 'overlaps_last' => is_array( $last ) && ! empty( $last['ran_gmt'] ) ? (string) $last['ran_gmt'] : '', ); } public static function stamps( $args, $assoc ) { if ( ! function_exists( 'wc_get_order' ) ) { WP_CLI::error( 'WooCommerce is not active.' ); } $filter = array(); if ( isset( $assoc['since'] ) ) { if ( 1 !== preg_match( '/^\d{4}-\d{2}-\d{2}$/', (string) $assoc['since'] ) ) { WP_CLI::error( '--since takes a day as Y-m-d.' ); } $filter['since'] = (string) $assoc['since']; } if ( isset( $assoc['order'] ) ) { $filter['order'] = (int) $assoc['order']; } $rows = self::stamp_rows( $filter ); $format = isset( $assoc['format'] ) && in_array( $assoc['format'], array( 'table', 'csv', 'json' ), true ) ? (string) $assoc['format'] : 'table'; $fields = array( 'order_id', 'line_id', 'product_id', 'quantity', 'unit_price', 'chg', 'won', 'set', 'tb', 'applied', 'p', 'alone', 'agrees' ); if ( $rows || 'table' !== $format ) { WP_CLI\Utils\format_items( $format, $rows, $fields ); } if ( 'table' === $format ) { $no = count( array_filter( $rows, static function ( $row ) { return 'yes' !== $row['agrees']; } ) ); WP_CLI::line( sprintf( '%d stamped lines, %d that do not agree with what the line was charged.', count( $rows ), $no ) ); } } public static function stamp_rows( array $filter = array() ) { global $wpdb; $where = "m.meta_key = '_aieo_offers'"; if ( ! empty( $filter['order'] ) ) { $where .= $wpdb->prepare( ' AND i.order_id = %d', (int) $filter['order'] ); } if ( ! empty( $filter['since'] ) ) { $from = date_create_immutable( (string) $filter['since'] . ' 00:00:00', wp_timezone() ); $ids = $from ? wc_get_orders( array( 'date_created' => '>=' . $from->getTimestamp(), 'return' => 'ids', 'limit' => -1, 'type' => 'shop_order' ) ) : array(); $ids = array_filter( array_map( 'intval', (array) $ids ) ); if ( ! $ids ) { return array(); } $where .= ' AND i.order_id IN (' . implode( ',', $ids ) . ')'; } $found = (array) $wpdb->get_results( "SELECT i.order_id, i.order_item_id, m.meta_value FROM {$wpdb->prefix}woocommerce_order_itemmeta m JOIN {$wpdb->prefix}woocommerce_order_items i ON i.order_item_id = m.order_item_id WHERE {$where} ORDER BY i.order_id, i.order_item_id LIMIT " . (int) self::STAMP_ROWS_LIMIT, ARRAY_A ); $rows = array(); $include_tax = function_exists( 'wc_prices_include_tax' ) && wc_prices_include_tax(); foreach ( $found as $row ) { $stamp = json_decode( (string) $row['meta_value'], true ); $line = WC_Order_Factory::get_order_item( (int) $row['order_item_id'] ); if ( ! is_array( $stamp ) || ! $line || ! is_a( $line, 'WC_Order_Item_Product' ) ) { continue; } $quantity = max( 1, (int) $line->get_quantity() ); $by_price = isset( $stamp['by'] ) && 'price' === $stamp['by']; $unit = $by_price ? (float) $line->get_subtotal() / $quantity : ( (float) $line->get_subtotal() + ( $include_tax ? (float) $line->get_subtotal_tax() : 0.0 ) ) / $quantity; $applied = null; foreach ( (array) ( $stamp['offers'] ?? array() ) as $offer ) { if ( isset( $offer['role'] ) && 'applied' === $offer['role'] ) { $applied = $offer; break; } } $chg = ! empty( $stamp['chg'] ) ? 1 : 0; if ( $by_price ) { list( $chg, $agrees ) = self::price_stamp_agrees( $stamp, $unit ); } elseif ( 1 === $chg ) { $percent = $applied ? (float) $applied['p'] : 0.0; $alone = $applied ? (float) $applied['alone'] : 0.0; $agrees = $applied && $percent > 0 && round( $unit, 4 ) <= round( ( $alone / ( $percent / 100 ) ) - $alone + 0.01, 4 ); } else { $agrees = null === $applied; } $rows[] = array( 'order_id' => (int) $row['order_id'], 'line_id' => (int) $row['order_item_id'], 'product_id' => (int) $line->get_variation_id() > 0 ? (int) $line->get_variation_id() : (int) $line->get_product_id(), 'quantity' => (int) $line->get_quantity(), 'unit_price' => self::number( round( $unit, 2 ) ), 'chg' => $chg, 'won' => isset( $stamp['won'] ) ? (string) $stamp['won'] : '', 'set' => isset( $stamp['set'] ) ? (string) $stamp['set'] : '', 'tb' => isset( $stamp['tb'] ) ? (string) $stamp['tb'] : '', 'applied' => $applied ? (string) $applied['s'] . ':' . (int) $applied['id'] : '', 'p' => $applied && isset( $applied['p'] ) ? self::number( $applied['p'] ) : '', 'alone' => $applied ? self::number( $applied['alone'] ) : '', 'agrees' => $agrees ? 'yes' : 'no', ); } return $rows; } private static function price_stamp_agrees( array $stamp, float $unit ): array { $list = isset( $stamp['list'] ) ? (float) $stamp['list'] : 0.0; $won = isset( $stamp['won'] ) ? (string) $stamp['won'] : ''; $alone = array(); $gift = false; foreach ( (array) ( $stamp['offers'] ?? array() ) as $offer ) { if ( ! is_array( $offer ) || 'applied' !== ( $offer['role'] ?? '' ) || 'qualify' === ( $offer['part'] ?? '' ) ) { continue; } $kind = (string) ( $offer['k'] ?? '' ); if ( 'gift' === $kind ) { $gift = true; } elseif ( 'free_shipping' !== $kind ) { $alone[] = (float) ( $offer['alone'] ?? 0 ); } } $unit = round( $unit, 4 ); $chg = $alone ? 1 : 0; if ( $gift ) { return array( $chg, $unit <= 0.01 ); } if ( 'sale' === $won || 'role' === $won ) { return array( $chg, ! $alone ); } if ( 'combined' === $won ) { return array( $chg, $alone && $unit <= round( $list - max( $alone ) + 0.01, 4 ) ); } return array( $chg, round( abs( $unit - ( $list - array_sum( $alone ) ) ), 4 ) <= 0.01 ); } public static function overlaps( $args, $assoc ) { if ( ! class_exists( 'AIEO_DMM_Offer_Overlaps' ) || ! class_exists( 'AIEO_DMM_Offer_Record' ) ) { WP_CLI::error( 'The record of the offers is not in this version.' ); } if ( ! AIEO_DMM_Offer_Record::is_on() ) { WP_CLI::error( 'The record of the offers is off: wp aieo offers line-record on' ); } if ( ! empty( $assoc['notice'] ) ) { foreach ( AIEO_DMM_Offer_Notice::lines() as $line ) { WP_CLI::line( $line ); } return; } if ( ! empty( $assoc['run'] ) ) { $last = AIEO_DMM_Offer_Overlaps::run_now( 'cli' ); if ( ! empty( $last['busy'] ) ) { WP_CLI::warning( 'Another run of the overlaps is at work and did not end in time: what follows is as the last finished run left it.' ); } WP_CLI::line( sprintf( '%d products read in %s seconds: %d intervals opened, %d closed.', (int) ( $last['products'] ?? 0 ), self::number( $last['seconds'] ?? 0 ), (int) ( $last['opened'] ?? 0 ), (int) ( $last['closed'] ?? 0 ) ) ); } $filter = array( 'open' => ! empty( $assoc['open'] ) ); if ( isset( $assoc['offer'] ) ) { if ( 1 !== preg_match( '/^[a-z]{2}:\d+$/', (string) $assoc['offer'] ) ) { WP_CLI::error( '--offer takes a store and an id, as bd:12.' ); } $filter['offer'] = (string) $assoc['offer']; } $rows = self::overlap_rows( $filter ); $format = isset( $assoc['format'] ) && in_array( $assoc['format'], array( 'table', 'csv', 'json' ), true ) ? (string) $assoc['format'] : 'table'; if ( $rows || 'table' !== $format ) { WP_CLI\Utils\format_items( $format, $rows, array( 'a', 'a_label', 'a_value', 'b', 'b_label', 'b_value', 'relation', 'keeps', 'tb', 'products', 'from_gmt', 'to_gmt', 'opened_by', 'closed_by' ) ); } if ( 'table' === $format ) { WP_CLI::line( sprintf( '%d intervals.', count( $rows ) ) ); } } public static function overlap_rows( array $filter = array() ) { $out = array(); foreach ( AIEO_DMM_Offer_Overlaps::rows( $filter ) as $row ) { $out[] = array( 'a' => $row['a_store'] . ':' . (int) $row['a_id'], 'a_label' => (string) $row['a_label'], 'a_value' => self::number( $row['a_value'] ), 'b' => $row['b_store'] . ':' . (int) $row['b_id'], 'b_label' => (string) $row['b_label'], 'b_value' => self::number( $row['b_value'] ), 'relation' => (string) $row['relation'], 'keeps' => (string) $row['keeps'], 'tb' => (string) $row['tb'], 'products' => (int) $row['products'], 'from_gmt' => (string) $row['from_gmt'], 'to_gmt' => null === $row['to_gmt'] ? '' : (string) $row['to_gmt'], 'opened_by' => (string) $row['opened_by'], 'closed_by' => (string) $row['closed_by'], ); } return $out; } public static function audit( $args, $assoc ) { $report = self::audit_report(); if ( isset( $assoc['format'] ) && 'json' === $assoc['format'] ) { WP_CLI::line( self::encode( $report ) ); return; } foreach ( self::audit_lines( $report ) as $line ) { WP_CLI::line( $line ); } } public static function audit_report() { global $wpdb; $report = array( 'pattern_only' => array( 'and' => array(), 'or' => array() ), 'excluded_patterns' => array(), 'not_applied' => array( 'minimum' => array(), 'product_list' => array(), 'whole_cart' => array() ), 'gift_rows' => array(), 'switches' => array( 'apply_recipe_to_main_price' => (bool) AIEO_DMM_Settings::get( 'apply_recipe_to_main_price', false ), 'aieo_use_effective_prices' => class_exists( 'AIEO_Effective_Prices' ) && AIEO_Effective_Prices::is_enabled(), 'pricing_mode' => (string) AIEO_DMM_Settings::get( 'pricing_mode', 'reactive' ), ), 'role_filters' => class_exists( 'AIEO_DMM_Offers_Held' ) ? AIEO_DMM_Offers_Held::looking_only( array( __CLASS__, 'audit_role_filters' ) ) : self::audit_role_filters(), ); $table = $wpdb->prefix . 'aieo_dmm_brand_discounts'; if ( function_exists( 'aieo_dmm_table_exists' ) && aieo_dmm_table_exists( $table ) ) { $rows = (array) $wpdb->get_results( "SELECT * FROM {$table} ORDER BY id ASC", ARRAY_A ); $all = null; $count = static function ( array $patterns ) use ( &$all ) { if ( null === $all ) { $all = self::coded_products(); } $matched = 0; foreach ( $all as $codes ) { if ( AIEO_DMM_Pattern_Match::any_matches_any( $codes, $patterns ) ) { ++$matched; } } return array( count( $all ), $matched ); }; $seeded = class_exists( 'AIEO_DMM_Offers_Held' ) && AIEO_DMM_Offers_Held::seeded( 'bd_pattern_or' ); foreach ( $rows as $row ) { $rule = array( 'id' => (int) $row['id'], 'label' => (string) ( $row['label'] ?? '' ), 'percent' => (float) $row['percent'], 'enabled' => ! empty( $row['enabled'] ), 'window' => AIEO_DMM_Schedule::state( $row['date_from'] ?? '', $row['date_to'] ?? '' ), ); $patterns = self::json_list( $row['code_patterns'] ?? '' ); $targets = (int) $row['brand_term_id'] > 0 || self::json_list( $row['category_term_ids'] ?? '' ) || self::json_list( $row['need_term_ids'] ?? '' ); if ( $patterns && ! $targets ) { $or = 'OR' === strtoupper( (string) $row['rule_operator'] ); $found = $rule; $found['patterns'] = $patterns; list( $found['products'], $found['matched'] ) = $count( $patterns ); if ( $or ) { $is_held = class_exists( 'AIEO_DMM_Offers_Held' ) && AIEO_DMM_Offers_Held::is_held( 'bd', (int) $row['id'] ); $found['held'] = $is_held ? 'held' : ( $seeded ? 'applies' : 'to_hold' ); } $report['pattern_only'][ $or ? 'or' : 'and' ][] = $found; } $excluded = self::json_list( $row['excluded_code_patterns'] ?? '' ); if ( $excluded ) { $found = $rule; $found['patterns'] = $excluded; list( $found['products'], $found['matched'] ) = $count( $excluded ); $report['excluded_patterns'][] = $found; } if ( (float) ( $row['min_subtotal'] ?? 0 ) > 0 ) { $report['not_applied']['minimum'][] = $rule + array( 'min_subtotal' => (float) $row['min_subtotal'] ); } if ( self::json_list( $row['product_ids'] ?? '' ) ) { $report['not_applied']['product_list'][] = $rule + array( 'products' => count( self::json_list( $row['product_ids'] ) ) ); } if ( 'whole_cart' === (string) ( $row['application_scope'] ?? '' ) ) { $report['not_applied']['whole_cart'][] = $rule; } } } $rows_table = $wpdb->prefix . 'aieo_effective_eligibility'; $gift_table = $wpdb->prefix . 'aieo_dmm_brand_gift_offers'; if ( function_exists( 'aieo_dmm_table_exists' ) && aieo_dmm_table_exists( $rows_table ) && aieo_dmm_table_exists( $gift_table ) ) { $found = (array) $wpdb->get_results( "SELECT e.offer_id, COUNT(*) AS n, g.id AS gift_id, g.enabled, g.date_from, g.date_to FROM {$rows_table} e LEFT JOIN {$gift_table} g ON g.id = e.offer_id WHERE e.surface = 'brand_gift' AND e.eligible = 1 GROUP BY e.offer_id, g.id, g.enabled, g.date_from, g.date_to", ARRAY_A ); foreach ( $found as $row ) { if ( null === $row['gift_id'] ) { $became = 'deleted'; } elseif ( empty( $row['enabled'] ) ) { $became = 'disabled'; } else { $became = AIEO_DMM_Schedule::state( $row['date_from'], $row['date_to'] ); } if ( ! isset( $report['gift_rows'][ $became ] ) ) { $report['gift_rows'][ $became ] = array( 'offers' => 0, 'rows' => 0 ); } ++$report['gift_rows'][ $became ]['offers']; $report['gift_rows'][ $became ]['rows'] += (int) $row['n']; } ksort( $report['gift_rows'] ); } return $report; } public static function audit_role_filters() { global $wpdb, $wp_filter; $out = array( 'runtime' => defined( 'AIEO_RUNTIME_OWNS_AJAX' ), 'callbacks' => array(), 'above_regular' => 0, 'above_price' => 0, 'above_price_rows' => array(), 'no_price' => 0, 'no_price_rows' => array(), 'probe' => null, ); foreach ( self::GETTERS as $getter ) { $out['callbacks'][ $getter ] = array(); if ( empty( $wp_filter[ $getter ] ) ) { continue; } foreach ( $wp_filter[ $getter ]->callbacks as $priority => $callbacks ) { foreach ( $callbacks as $callback ) { $f = $callback['function']; if ( is_array( $f ) && 2 === count( $f ) ) { $name = ( is_object( $f[0] ) ? get_class( $f[0] ) : (string) $f[0] ) . '::' . $f[1]; } elseif ( is_string( $f ) ) { $name = $f; } else { $name = 'closure'; } if ( 0 === strpos( $name, 'AIEO_' ) ) { $out['callbacks'][ $getter ][] = (int) $priority . ' ' . $name; } } } } $table = $wpdb->prefix . 'aieo_dmm_role_prices'; $roles = (array) AIEO_DMM_Settings::get( 'enabled_roles', array() ); if ( ! $roles || ! function_exists( 'aieo_dmm_table_exists' ) || ! aieo_dmm_table_exists( $table ) ) { return $out; } $columns = (array) $wpdb->get_col( "SHOW COLUMNS FROM {$table}" ); foreach ( $roles as $role ) { $column = aieo_dmm_sanitize_role_column( (string) $role ); if ( ! in_array( $column, $columns, true ) ) { continue; } $found = (array) $wpdb->get_results( "SELECT r.product_id, r.`{$column}` AS role_price, m.meta_value AS regular FROM {$table} r JOIN {$wpdb->postmeta} m ON m.post_id = r.product_id AND m.meta_key = '_regular_price' WHERE r.`{$column}` IS NOT NULL AND m.meta_value <> '' ORDER BY r.product_id ASC", ARRAY_A ); foreach ( $found as $row ) { $regular = AIEO_DMM_Stored_Price::read( $row['regular'] ); if ( null !== $regular && (float) $row['role_price'] > $regular ) { ++$out['above_regular']; } } $above = array(); $found = (array) $wpdb->get_results( "SELECT r.product_id, r.parent_id, r.product_type, r.sku, r.`{$column}` AS role_price, p.meta_value AS price, m.meta_value AS regular FROM {$table} r JOIN {$wpdb->postmeta} p ON p.post_id = r.product_id AND p.meta_key = '_price' LEFT JOIN {$wpdb->postmeta} m ON m.post_id = r.product_id AND m.meta_key = '_regular_price' WHERE r.`{$column}` IS NOT NULL AND p.meta_value <> '' ORDER BY r.product_id ASC", ARRAY_A ); $lowest = array(); foreach ( $found as $row ) { $price = AIEO_DMM_Stored_Price::read( $row['price'] ); $id = (int) $row['product_id']; if ( null !== $price && ( ! isset( $lowest[ $id ] ) || $price < $lowest[ $id ][0] ) ) { $lowest[ $id ] = array( $price, $row ); } } foreach ( $lowest as $id => $pair ) { if ( (float) $pair[1]['role_price'] > $pair[0] ) { $above[ $id ] = self::role_price_row( $pair[1], (string) $role ); } } $above = array_values( $above ); $out['above_price_rows'] = array_merge( $out['above_price_rows'], $above ); $found = (array) $wpdb->get_results( "SELECT r.product_id, r.parent_id, r.product_type, r.sku, r.`{$column}` AS role_price, '' AS price, m.meta_value AS regular FROM {$table} r JOIN {$wpdb->posts} o ON o.ID = r.product_id AND o.post_status = 'publish' LEFT JOIN {$wpdb->postmeta} p ON p.post_id = r.product_id AND p.meta_key = '_price' AND p.meta_value <> '' LEFT JOIN {$wpdb->postmeta} m ON m.post_id = r.product_id AND m.meta_key = '_regular_price' WHERE r.`{$column}` > 0 AND p.meta_id IS NULL ORDER BY r.product_id ASC", ARRAY_A ); foreach ( $found as $row ) { $out['no_price_rows'][] = self::role_price_row( $row, (string) $role ); } if ( $above && null === $out['probe'] && class_exists( 'AIEO_Effective_Prices' ) ) { $user_id = (int) AIEO_Effective_Prices::representative_user_for_audience( 'role:' . $role ); if ( $user_id > 0 ) { $was = get_current_user_id(); wp_set_current_user( $user_id ); AIEO_DMM_Cache::forget_request(); $role_price = (float) $above[0]['role_price']; $public = (float) $above[0]['price']; try { $product = wc_get_product( (int) $above[0]['product_id'] ); $answered = $product ? (float) $product->get_price() : 0.0; } finally { wp_set_current_user( $was ); AIEO_DMM_Cache::forget_request(); } if ( $answered > $public + 0.005 ) { $rule = 'replace'; } elseif ( $answered > 0 ) { $rule = 'lower_of'; } else { $rule = 'other'; } $out['probe'] = array( 'product_id' => (int) $above[0]['product_id'], 'role' => (string) $role, 'regular' => $above[0]['regular'], 'price' => $above[0]['price'], 'role_price' => $above[0]['role_price'], 'answered' => self::number( $answered ), 'rule' => $rule, 'recipe' => $answered > 0 && ( $answered < min( $role_price, $public ) - 0.005 || ( 'replace' === $rule && abs( $answered - $role_price ) >= 0.005 ) ), ); } } } $out['above_price'] = count( $out['above_price_rows'] ); $out['no_price'] = count( $out['no_price_rows'] ); return $out; } private static function role_price_row( array $row, $role ) { return array( 'product_id' => (int) $row['product_id'], 'parent_id' => 'variation' === (string) $row['product_type'] ? (int) $row['parent_id'] : 0, 'sku' => (string) $row['sku'], 'role' => (string) $role, 'role_price' => self::number( $row['role_price'] ), 'regular' => self::number( AIEO_DMM_Stored_Price::read( $row['regular'] ) ), 'price' => self::number( AIEO_DMM_Stored_Price::read( $row['price'] ) ), ); } public static function audit_lines( array $report ) { $lines = array(); $rule_is = static function ( array $rule ) { return sprintf( '#%d "%s" %s%% (%s, %s)', $rule['id'], $rule['label'], self::number( $rule['percent'] ), $rule['enabled'] ? 'enabled' : 'disabled', $rule['window'] ); }; $lines[] = 'F1. Discounts and product-code patterns (the price reads a discount\'s patterns since this fix)'; foreach ( $report['pattern_only']['and'] as $rule ) { $lines[] = ' AND ' . $rule_is( $rule ) . ': a pattern is its only target. It priced every product; it prices only the ' . $rule['matched'] . ' of ' . $rule['products'] . ' products and variations its patterns match (' . implode( ', ', $rule['patterns'] ) . '). The others lose this discount.'; } $held_says = array( 'held' => 'It is held until it is opened and saved.', 'to_hold' => 'It will be held at the first price read on this shop, until it is opened and saved.', 'applies' => 'It was saved since the fix and prices those products.', ); foreach ( $report['pattern_only']['or'] as $rule ) { $lines[] = ' OR ' . $rule_is( $rule ) . ': a pattern is its only target. It priced no product; its patterns match ' . $rule['matched'] . ' of ' . $rule['products'] . ' (' . implode( ', ', $rule['patterns'] ) . '). ' . $held_says[ $rule['held'] ]; } foreach ( $report['excluded_patterns'] as $rule ) { $lines[] = ' EXCLUDES ' . $rule_is( $rule ) . ': its excluded patterns (' . implode( ', ', $rule['patterns'] ) . ') match ' . $rule['matched'] . ' of ' . $rule['products'] . ' products and variations. They were discounted all the same; they lose this discount.'; } if ( ! $report['pattern_only']['and'] && ! $report['pattern_only']['or'] && ! $report['excluded_patterns'] ) { $lines[] = ' none'; } $lines[] = 'F5. Discounts with a minimum subtotal, a product list or a whole-cart scope (the form refuses the three since this fix)'; $any = false; foreach ( array( 'minimum' => 'a minimum subtotal: applied to no price, shown as "Not applied" and held until it is saved without it', 'product_list' => 'a product list: applied to no price, shown as "Not applied" and held until it is saved without it', 'whole_cart' => 'a whole-cart scope: priced as an ordinary rule, as before; its next save asks for "matching items only"' ) as $kind => $says ) { foreach ( $report['not_applied'][ $kind ] as $rule ) { $lines[] = ' ' . $rule_is( $rule ) . ': ' . $says . '.'; $any = true; } } if ( ! $any ) { $lines[] = ' none'; } $lines[] = 'F4. Stored gift-badge rows, by what became of their offer'; if ( $report['gift_rows'] ) { foreach ( $report['gift_rows'] as $became => $count ) { $lines[] = sprintf( ' %s: %d rows of %d offers%s', $became, $count['rows'], $count['offers'], 'active' === $became ? '' : ' (the fix deletes them)' ); } } else { $lines[] = ' none'; } $lines[] = 'F2. The two price switches'; $lines[] = ' apply_recipe_to_main_price: ' . ( $report['switches']['apply_recipe_to_main_price'] ? 'on' : 'off' ) . ' (as stored; no longer read since this fix: the recipe is always applied to the price charged)'; $lines[] = ' aieo_use_effective_prices: ' . ( $report['switches']['aieo_use_effective_prices'] ? 'on' : 'off' ); $lines[] = ' pricing_mode: ' . $report['switches']['pricing_mode']; $lines[] = 'F6. The role-price filters (a role customer is charged the lower of the role price and the public\'s price since this fix)'; $lines[] = ' the Runtime owns the hooks: ' . ( $report['role_filters']['runtime'] ? 'yes' : 'no' ); foreach ( $report['role_filters']['callbacks'] as $getter => $callbacks ) { $lines[] = ' ' . $getter . ': ' . ( $callbacks ? implode( ' > ', $callbacks ) : 'none of ours' ); } $row_is = static function ( array $row ) { return sprintf( '#%d%s%s, role %s: role price %s, regular %s', $row['product_id'], '' !== $row['sku'] ? ' ' . $row['sku'] : '', $row['parent_id'] > 0 ? ' (a variation of #' . $row['parent_id'] . ')' : '', $row['role'], $row['role_price'], '' !== $row['regular'] ? $row['regular'] : 'none' ); }; $lines[] = ' role prices above the regular price: ' . (int) $report['role_filters']['above_regular']; $lines[] = ' role prices above the price the public is charged (the sale price while a sale runs): ' . (int) $report['role_filters']['above_price'] . ( $report['role_filters']['above_price_rows'] ? '. Their customers were charged the role price; they are charged the public\'s price:' : '' ); foreach ( $report['role_filters']['above_price_rows'] as $row ) { $lines[] = ' ' . $row_is( $row ) . ', public price ' . $row['price'] . ( '' !== $row['regular'] && $row['price'] !== $row['regular'] ? ' (on sale)' : '' ); } $lines[] = ' role prices of a published product that has no public price: ' . (int) $report['role_filters']['no_price'] . ( $report['role_filters']['no_price_rows'] ? '. Each is sold to its role only, at the role price, as before (the public cannot buy it):' : '' ); foreach ( $report['role_filters']['no_price_rows'] as $row ) { $lines[] = ' ' . $row_is( $row ); } if ( $report['role_filters']['probe'] ) { $probe = $report['role_filters']['probe']; $lines[] = sprintf( ' product #%d as a customer of the role %s: regular %s, public price %s, role price %s, the getters answer %s (%s%s)', $probe['product_id'], $probe['role'], '' !== $probe['regular'] ? $probe['regular'] : 'none', $probe['price'], $probe['role_price'], $probe['answered'], 'replace' === $probe['rule'] ? 'the role price replaces the price' : ( 'lower_of' === $probe['rule'] ? 'the lower of the two' : 'neither of the two' ), ! empty( $probe['recipe'] ) ? ', with the customer\'s discounts on top' : '' ); } return $lines; } private static function coded_products() { global $wpdb; $rows = (array) $wpdb->get_results( "SELECT ID, post_parent FROM {$wpdb->posts} WHERE post_type IN ('product', 'product_variation') AND post_status = 'publish' ORDER BY ID ASC", ARRAY_A ); $out = array(); foreach ( $rows as $row ) { $ids = array( (int) $row['ID'] ); if ( (int) $row['post_parent'] > 0 ) { $ids[] = (int) $row['post_parent']; } $out[ (int) $row['ID'] ] = AIEO_DMM_Offer_Matcher::product_codes( $ids ); } return $out; } private static function json_list( $raw ) { $list = json_decode( (string) $raw, true ); return is_array( $list ) ? array_values( array_filter( $list ) ) : array(); } public static function number( $value ) { if ( null === $value || '' === $value || false === $value ) { return ''; } if ( ! is_numeric( $value ) ) { return (string) $value; } $text = number_format( (float) $value, 6, '.', '' ); $text = rtrim( rtrim( $text, '0' ), '.' ); return '-0' === $text ? '0' : $text; } public static function text( $html ) { $text = html_entity_decode( wp_strip_all_tags( (string) $html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ); return trim( (string) preg_replace( '/\s+/u', ' ', $text ) ); } public static function encode( array $record ) { return (string) wp_json_encode( $record, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . "\n"; } } }