'bundles', 'AIEO_DMM_Offer_Definition' => 'offer-definition', 'AIEO_DMM_Offer_Registry' => 'offer-registry', 'AIEO_DMM_Offer_Store' => 'offer-store', 'AIEO_DMM_Offer_Writer' => 'offer-writer', 'AIEO_DMM_Schedule' => 'schedule', 'AIEO_DMM_Offer_Reports' => 'offer-reports' ) as $class => $file ) { if ( ! class_exists( $class, false ) ) { require_once __DIR__ . '/class-aieo-dmm-' . $file . '.php'; } } } public static function saving(): bool { return self::$saving > 0; } public static function save_offer( array $set, callable $write_row, array $args = array() ) { self::load(); ++self::$saving; try { return self::save_set( $set, $write_row, $args ); } finally { --self::$saving; } } public static function archive_offer( int $set_id, string $reason = '' ) { self::load(); $out = array( 'archived' => array() ); ++self::$saving; try { foreach ( self::linked( $set_id, true ) as $offer_id ) { $done = AIEO_DMM_Offer_Writer::archive( $offer_id, $reason ); if ( is_wp_error( $done ) ) { return $done; } $out['archived'][] = $offer_id; } } finally { --self::$saving; } return $out; } private static function save_set( array $set, callable $write_row, array $args ) { $together = $set['together'] ?? ''; if ( ! is_string( $together ) || ( '' !== $together && ! in_array( $together, AIEO_DMM_Bundles::RESULTS, true ) ) ) { return self::refusal( 'together', 'invalid', __( 'Choose what buying the set together gives.', 'ai-eshop-optimizer' ) ); } $set_id = max( 0, (int) ( $set['id'] ?? 0 ) ); $own = self::offer_of_set( $set_id ); $dry = ! empty( $args['dry_run'] ); $writer = array( 'confirmed' => true, 'by' => isset( $args['by'] ) ? (string) $args['by'] : 'user', 'reason' => isset( $args['reason'] ) ? (string) $args['reason'] : '', ); if ( '' === $together ) { return self::save_off( $set_id, $own, $write_row, $writer, $dry ); } if ( ! AIEO_DMM_Offer_Store::reads_unified() ) { return new WP_Error( 'bundle_not_ready', __( '"Bought together" needs the new offers, which this shop has not switched to yet.', 'ai-eshop-optimizer' ) ); } $type = 'gift' === $together ? 'gift' : 'discount'; $same = $own && $type === (string) $own['type'] ? $own : null; $replaced = $own && ! $same ? (int) $own['id'] : 0; $enabled = ! empty( $set['enabled'] ); $members = self::members( $set['members'] ?? null ); $definition = self::definition( $set, $together, $members, $same ); $valid = AIEO_DMM_Offer_Definition::validate( $definition, $type ); if ( is_wp_error( $valid ) ) { return $valid; } $usual = self::usual( $members ); $refused = self::catalogue_refusal( $members, $definition['effect'], $usual ); if ( $refused ) { return $refused; } $label = isset( $set['label'] ) && is_scalar( $set['label'] ) ? trim( (string) $set['label'] ) : ''; if ( '' === $label ) { $label = sprintf( __( '%s set', 'ai-eshop-optimizer' ), $usual['members'][ $members[0]['p'] ]['name'] ); } $offer = array( 'type' => $type, 'label' => $label, 'enabled' => $enabled ? 1 : 0, 'definition' => $definition, 'source_kind' => AIEO_DMM_Bundles::SOURCE_KIND, 'source_id' => $set_id, ); if ( $same ) { $offer['id'] = (int) $same['id']; } else { $writer['origin'] = AIEO_DMM_Bundles::ORIGIN; } foreach ( array( 'starts' => 'start_date', 'ends' => 'end_date' ) as $key => $column ) { if ( array_key_exists( $key, $set ) ) { $offer[ $column ] = is_string( $set[ $key ] ) ? $set[ $key ] : ''; } } $written_definition = AIEO_DMM_Offer_Definition::normalise( $definition ); if ( $dry || $replaced ) { $would = AIEO_DMM_Offer_Writer::save( $offer, $writer + array( AIEO_DMM_Offer_Writer::DRY_RUN => true ) ); if ( is_wp_error( $would ) ) { return $would; } if ( $dry ) { return self::result( $set_id, $same ? (int) $same['id'] : 0, $same ? (int) $same['revision'] + 1 : 1, ! $same, $replaced, ! $enabled, $written_definition ); } } if ( $replaced ) { $archived = AIEO_DMM_Offer_Writer::archive( $replaced, $writer['reason'] ); if ( is_wp_error( $archived ) ) { return $archived; } } $written = 0; $inside = static function ( $offer_id ) use ( $write_row, &$written ) { $answer = self::row_written( $write_row, (int) $offer_id ); if ( is_wp_error( $answer ) ) { return $answer; } $written = $answer; return array( 'source_id' => $answer ); }; $saved = AIEO_DMM_Offer_Writer::save( $offer, $writer + array( AIEO_DMM_Offer_Writer::INSIDE => $inside ) ); if ( is_wp_error( $saved ) ) { return $replaced ? self::after_archive( $saved, $replaced ) : $saved; } return self::result( (int) $written, (int) $saved['id'], (int) $saved['revision'], ! $same, $replaced, ! $enabled, $written_definition ); } private static function save_off( int $set_id, ?array $own, callable $write_row, array $writer, bool $dry ) { $pause = $own && ! empty( $own['enabled'] ); $result = self::result( $set_id, 0, $own ? (int) $own['revision'] + ( $pause ? 1 : 0 ) : 0, false, 0, null !== $own, null ); if ( $dry ) { return $result; } $written = 0; if ( $pause ) { $inside = static function () use ( $write_row, &$written ) { $written = self::row_written( $write_row, 0 ); return $written; }; $saved = AIEO_DMM_Offer_Writer::save( array( 'id' => (int) $own['id'], 'enabled' => 0, ), $writer + array( AIEO_DMM_Offer_Writer::INSIDE => $inside ) ); if ( is_wp_error( $saved ) ) { return $saved; } $result['revision'] = (int) $saved['revision']; } else { $written = self::row_written( $write_row, 0 ); if ( is_wp_error( $written ) ) { return $written; } } $result['set_id'] = (int) $written; return $result; } private static function row_written( callable $write_row, int $offer_id ) { try { $answer = call_user_func( $write_row, $offer_id ); } catch ( \Throwable $e ) { return new WP_Error( 'write_failed', __( 'The set could not be saved.', 'ai-eshop-optimizer' ), array( 'error' => $e->getMessage() ) ); } if ( is_wp_error( $answer ) ) { return $answer; } if ( ! is_numeric( $answer ) || (int) $answer <= 0 ) { return new WP_Error( 'write_failed', __( 'The set could not be saved.', 'ai-eshop-optimizer' ) ); } return (int) $answer; } private static function members( $members ): array { $out = array(); foreach ( is_array( $members ) ? array_values( $members ) : array() as $member ) { if ( ! is_array( $member ) ) { $out[] = $member; continue; } $one = array(); foreach ( array( 'p', 'min', 'max' ) as $key ) { $value = $member[ $key ] ?? 0; $one[ $key ] = is_numeric( $value ) && (float) (int) $value === (float) $value ? (int) $value : $value; } $out[] = $one; } return $out; } private static function definition( array $set, string $together, array $members, ?array $same ): array { $value = isset( $set['value'] ) && is_numeric( $set['value'] ) ? $set['value'] + 0 : 0; switch ( $together ) { case 'set_price': $effect = array( 'e' => 'set_price', 'price' => $value, ); break; case 'percent': $effect = array( 'e' => 'percent', 'value' => $value, ); break; case 'amount': $effect = array( 'e' => 'amount', 'value' => $value, 'per' => 'set', ); break; default: $gift = isset( $set['gift'] ) && is_array( $set['gift'] ) ? $set['gift'] : array(); $effect = array( 'e' => 'gift', 'products' => array_values( array_map( 'intval', array_filter( (array) ( $gift['products'] ?? array() ), 'is_numeric' ) ) ), 'choose' => empty( $gift['choose'] ) || ! is_numeric( $gift['choose'] ) ? 1 : (int) $gift['choose'], ); } $per = $set['per'] ?? ''; $allocation = ''; if ( 'set' === $per ) { $allocation = 'per_set'; } elseif ( 'once' === $per ) { $allocation = 'once'; } elseif ( '' === $per || null === $per ) { $allocation = 'gift' === $together ? 'once' : 'per_set'; } $kept = $same && isset( $same['_definition'] ) && is_array( $same['_definition'] ) ? $same['_definition'] : array(); $part = static function ( string $key, array $none ) use ( $kept ): array { return isset( $kept[ $key ] ) && is_array( $kept[ $key ] ) ? $kept[ $key ] : $none; }; return array( 'v' => isset( $kept['v'] ) ? (int) $kept['v'] : 1, 'target' => AIEO_DMM_Offer_Definition::bundle_target( $members ), 'when' => $part( 'when', array( 'all' => array() ) ), 'bundle' => $members, 'effect' => $effect, 'scope' => 'group', 'allocation' => $allocation, 'limits' => $part( 'limits', array() ), 'parameters' => $part( 'parameters', array() ), 'display' => $part( 'display', array() ), ); } private static function catalogue_refusal( array $members, array $effect, array $usual ): ?WP_Error { foreach ( $members as $i => $member ) { $p = (int) $member['p']; $name = self::named( $p, (string) $usual['members'][ $p ]['name'] ); if ( ! self::published( $p, false ) ) { return self::refusal( 'bundle.' . $i . '.p', 'not_found', sprintf( __( '%s is not a published product any more. Take it out of the set.', 'ai-eshop-optimizer' ), $name ) ); } if ( $usual['members'][ $p ]['from'] <= 0 ) { return self::refusal( 'bundle.' . $i . '.p', 'no_price', sprintf( __( '%s has no regular price, so it cannot be part of a set that is bought together.', 'ai-eshop-optimizer' ), $name ) ); } } if ( 'gift' === $effect['e'] ) { foreach ( $effect['products'] as $gift ) { if ( ! self::published( (int) $gift, true ) ) { $product = wc_get_product( (int) $gift ); $name = self::named( (int) $gift, $product instanceof WC_Product ? (string) $product->get_name() : '' ); return self::refusal( 'effect.products', 'not_found', sprintf( __( 'The gift %s is not a published product any more. Choose another gift.', 'ai-eshop-optimizer' ), $name ) ); } } } if ( 'set_price' === $effect['e'] && (float) $effect['price'] >= $usual['to'] ) { return self::refusal( 'effect.price', 'not_below', __( 'The set would cost more than its products: it would never apply.', 'ai-eshop-optimizer' ) ); } if ( 'amount' === $effect['e'] && (float) $effect['value'] >= $usual['from'] ) { return self::refusal( 'effect.value', 'not_below', __( 'The amount is as much as the set\'s products cost, or more: choose a smaller amount.', 'ai-eshop-optimizer' ) ); } return null; } private static function published( int $id, bool $variations ): bool { $product = $id > 0 ? wc_get_product( $id ) : false; return $product instanceof WC_Product && 'publish' === $product->get_status() && ( $variations || ! $product->is_type( 'variation' ) ); } private static function named( int $id, string $name ): string { return '' !== $name ? $name : '#' . $id; } private static function refusal( string $path, string $reason, string $message ): WP_Error { return new WP_Error( 'invalid_bundle', $message, array( 'path' => $path, 'reason' => $reason, ) ); } private static function after_archive( WP_Error $error, int $archived ): WP_Error { $data = $error->get_error_data(); return new WP_Error( $error->get_error_code(), trim( $error->get_error_message() . ' ' . __( 'The earlier offer of the set was archived and "Bought together" is off for now: save the set again to make the new offer.', 'ai-eshop-optimizer' ) ), array( 'archived' => $archived ) + ( is_array( $data ) ? $data : array() ) ); } private static function result( int $set_id, int $offer_id, int $revision, bool $made, int $archived, bool $paused, ?array $definition ): array { return array( 'set_id' => $set_id, 'offer_id' => $offer_id, 'revision' => $revision, 'made' => $made, 'archived' => $archived, 'paused' => $paused, 'definition' => $definition, ); } public static function offer_of_set( int $set_id ): ?array { global $wpdb; if ( $set_id <= 0 ) { return null; } self::load(); $table = $wpdb->prefix . 'aieo_dmm_offers'; $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE source_kind = %s AND source_id = %d AND state <> 'archived' ORDER BY id DESC LIMIT 1", AIEO_DMM_Bundles::SOURCE_KIND, $set_id ), ARRAY_A ); if ( ! is_array( $row ) ) { return null; } $row['_definition'] = AIEO_DMM_Offer_Definition::for_row( $row ); return $row; } public static function offers_of_set( int $set_id ): array { return self::linked( $set_id, false ); } private static function linked( int $set_id, bool $live ): array { global $wpdb; if ( $set_id <= 0 ) { return array(); } $table = $wpdb->prefix . 'aieo_dmm_offers'; $where = $live ? " AND state <> 'archived'" : ''; return array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$table} WHERE source_kind = %s AND source_id = %d{$where} ORDER BY id DESC", AIEO_DMM_Bundles::SOURCE_KIND, $set_id ) ) ); } public static function usual( array $members ): array { global $wpdb; $out = array( 'from' => 0.0, 'to' => 0.0, 'members' => array(), ); $counts = array(); $variable = array(); foreach ( $members as $member ) { if ( ! is_array( $member ) || ! isset( $member['p'] ) || ! is_numeric( $member['p'] ) || (int) $member['p'] <= 0 ) { continue; } $p = (int) $member['p']; $min = isset( $member['min'] ) && is_numeric( $member['min'] ) ? max( 1, (int) $member['min'] ) : 1; $max = isset( $member['max'] ) && is_numeric( $member['max'] ) ? max( $min, (int) $member['max'] ) : $min; $entry = array( 'from' => 0.0, 'to' => 0.0, 'variable' => false, 'name' => '', ); $product = wc_get_product( $p ); if ( $product instanceof WC_Product ) { $entry['name'] = (string) $product->get_name(); if ( $product instanceof WC_Product_Variable ) { $entry['variable'] = true; $variable[ $p ] = $p; } else { $price = $product->get_regular_price( 'edit' ); $entry['from'] = is_numeric( $price ) ? max( 0.0, (float) $price ) : 0.0; $entry['to'] = $entry['from']; } } $out['members'][ $p ] = $entry; $counts[ $p ] = array( $min, $max ); } if ( $variable ) { $marks = implode( ',', array_fill( 0, count( $variable ), '%d' ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT v.post_parent AS parent_id, MIN( CAST( m.meta_value AS DECIMAL(20,6) ) ) AS lowest, MAX( CAST( m.meta_value AS DECIMAL(20,6) ) ) AS highest FROM {$wpdb->posts} v INNER JOIN {$wpdb->postmeta} m ON m.post_id = v.ID AND m.meta_key = '_regular_price' WHERE v.post_parent IN ({$marks}) AND v.post_type = 'product_variation' AND v.post_status = 'publish' AND m.meta_value <> '' AND CAST( m.meta_value AS DECIMAL(20,6) ) > 0 GROUP BY v.post_parent", array_values( $variable ) ), ARRAY_A ); foreach ( (array) $rows as $row ) { $parent = (int) $row['parent_id']; if ( isset( $out['members'][ $parent ] ) ) { $out['members'][ $parent ]['from'] = (float) $row['lowest']; $out['members'][ $parent ]['to'] = (float) $row['highest']; } } } foreach ( $counts as $p => $count ) { $out['from'] += $out['members'][ $p ]['from'] * $count[0]; $out['to'] += $out['members'][ $p ]['to'] * $count[1]; } $out['from'] = round( $out['from'], 6 ); $out['to'] = round( $out['to'], 6 ); return $out; } public static function given_for_set( int $set_id, int $days = 30 ): ?array { $offers = self::offers_of_set( $set_id ); if ( ! $offers ) { return null; } self::load(); $to = (string) AIEO_DMM_Schedule::today(); $from = gmdate( 'Y-m-d', strtotime( $to . ' 12:00:00 UTC' ) - ( max( 1, $days ) - 1 ) * DAY_IN_SECONDS ); $out = array( 'sets' => 0, 'units' => 0, 'given' => 0.0, 'orders' => 0, ); foreach ( $offers as $offer_id ) { $one = AIEO_DMM_Offer_Reports::bundle_given( $offer_id, $from, $to ); if ( ! is_array( $one ) ) { continue; } $out['sets'] += (int) ( $one['sets'] ?? 0 ); $out['units'] += (int) ( $one['units'] ?? 0 ); $out['given'] += (float) ( $one['given'] ?? 0 ); $out['orders'] += (int) ( $one['orders'] ?? 0 ); } $own = self::offer_of_set( $set_id ); $out['offer_id'] = $own ? (int) $own['id'] : 0; return $out; } } }