$image Картинка и наложения: imageId, watermark, aiLabel. * @param string $target Назначение — одно из TARGETS. * @param array|null $variation Для каких вариаций (код атрибута → код значения); * null — товар целиком. * @param bool $add_to_gallery При вариации — положить ещё и в галерею. * @return void */ public static function record_pending( int $product_id, string $photo_session_id, string $file_format, array $image, string $target, ?array $variation, bool $add_to_gallery ): void { update_post_meta( $product_id, Meta::PENDING_SAVE, array( 'photoSessionId' => $photo_session_id, 'fileFormat' => $file_format, 'image' => $image, 'target' => $target, 'variation' => $variation, 'addToGallery' => $add_to_gallery, 'userId' => get_current_user_id(), 'createdAt' => time(), 'attempts' => 0, ) ); Scheduler::schedule_pending_save( $product_id, Scheduler::retry_delay( 0 ) ); Logger::info( 'Save recorded as pending', array( 'product_id' => $product_id, 'photo_session_id' => $photo_session_id, 'image_id' => $image['imageId'] ?? '', 'target' => $target, 'variation' => $variation, 'add_to_gallery' => $add_to_gallery, ) ); } /** * Ожидающее сохранение товара из меты. * * Запись прежнего вида — список фото и режим старых фото от плагина версии до 1.4 — * доделать нечем: она снимается здесь же, с записью в журнал, и человек сохраняет фото * из окна заново. Плагин обновляют между сеансами работы, и такие записи — редкость. * * @param int $product_id Id товара. * @return array|null Запись или null, если ожидающего нет. */ public static function pending( int $product_id ): ?array { $pending = get_post_meta( $product_id, Meta::PENDING_SAVE, true ); if ( ! is_array( $pending ) ) { return null; } if ( ! is_array( $pending['image'] ?? null ) ) { self::clear_pending( $product_id ); Logger::warning( 'Pending save recorded by an earlier plugin version was discarded; save the photo from the window again', array( 'product_id' => $product_id, 'images' => is_array( $pending['images'] ?? null ) ? count( $pending['images'] ) : 0, ) ); return null; } return $pending; } /** * Снимает отметку «ожидающее сохранение» и отменяет фоновую задачу. * * @param int $product_id Id товара. * @return void */ public static function clear_pending( int $product_id ): void { delete_post_meta( $product_id, Meta::PENDING_SAVE ); Scheduler::cancel_pending_save( $product_id ); } /** * Обрабатывает ожидающее сохранение товара. * * @param int $product_id Id товара. * @return array Что нужно скрипту страницы: изображение товара, галерея, число фото, * изображения вариаций и состояние товара для окна. * @throws Action_Failed Сохранение не удалось; признак temporary — оставлено ли оно ожидающим. */ public static function process( int $product_id ): array { $pending = self::pending( $product_id ); if ( null === $pending ) { throw new Action_Failed( __( 'There is nothing to save: the photos have already been saved or the save was cancelled. Reload the product page.', 'aimodelka' ) ); } if ( ! Product_Lock::acquire( $product_id, Meta::SAVE_LOCK, self::LOCK_TTL ) ) { throw new Action_Failed( __( 'Photos for this product are already being saved. Wait a moment and reload the product page.', 'aimodelka' ), true ); } try { return self::process_locked( $product_id, $pending ); } catch ( Action_Failed $failure ) { if ( ! $failure->temporary ) { // Повтор этого не исправит — не держим сохранение ожидающим. self::clear_pending( $product_id ); } Logger::error( 'Save failed', array( 'product_id' => $product_id, 'temporary' => $failure->temporary, 'reason' => $failure->getMessage(), ) ); throw $failure; } finally { Product_Lock::release( $product_id, Meta::SAVE_LOCK ); } } /** * Сама обработка — под отметкой «идёт сохранение». * * @param int $product_id Id товара. * @param array $pending Ожидающее сохранение. * @return array См. process(). * @throws Action_Failed Неудача. */ private static function process_locked( int $product_id, array $pending ): array { wc_set_time_limit( self::TIME_LIMIT ); wp_raise_memory_limit( 'image' ); $product = wc_get_product( $product_id ); if ( ! $product ) { throw new Action_Failed( __( 'The product no longer exists.', 'aimodelka' ) ); } $client = Client::from_config(); if ( null === $client ) { throw new Action_Failed( __( 'Add your aiModelka key in WooCommerce → aiModelka first.', 'aimodelka' ) ); } $session_id = (string) ( $pending['photoSessionId'] ?? '' ); $file_format = in_array( $pending['fileFormat'] ?? null, Settings::FILE_FORMATS, true ) ? $pending['fileFormat'] : Settings::file_format(); $image = (array) $pending['image']; // Назначение записал адрес REST после проверки; незнакомое сюда не попадает, но если // запись испорчена руками, самое безобидное — галерея: она ничего не вытесняет. $target = in_array( $pending['target'] ?? null, self::TARGETS, true ) ? $pending['target'] : self::TARGET_GALLERY; $variation = self::TARGET_MAIN === $target ? self::variation_choice( $pending['variation'] ?? null ) : null; $add_to_gallery = null !== $variation && ! empty( $pending['addToGallery'] ); $name = trim( wp_strip_all_tags( $product->get_name( 'edit' ) ) ); $old_main = (int) $product->get_image_id( 'edit' ); $old_gallery = array_map( 'intval', $product->get_gallery_image_ids( 'edit' ) ); // Папка FileBird — по фото товара до сохранения: изображение товара, иначе первое фото // галереи, лежащее в папке. Нет FileBird или папки — 0, и файл ложится как обычно. $folder_id = Media_Folders::folder_for_product( $old_main, $old_gallery ); $importer = new Image_Importer( $client, $product_id, $name, $session_id, $file_format, $folder_id ); Logger::info( 'Saving a photo to the product', array( 'product_id' => $product_id, 'photo_session_id' => $session_id, 'image_id' => $image['imageId'] ?? '', 'target' => $target, 'variation' => $variation, 'add_to_gallery' => $add_to_gallery, 'folder_id' => $folder_id, ) ); $attachment_id = $importer->import( (string) ( $image['imageId'] ?? '' ), ! empty( $image['watermark'] ), ! empty( $image['aiLabel'] ) ); $layout = array( 'main' => $old_main, 'gallery' => $old_gallery, ); $variation_images = array(); if ( self::TARGET_MAIN === $target && null !== $variation ) { $variation_images = self::set_variation_images( $product, $attachment_id, $variation ); // Галочка «Добавить в галерею товара» — то же, что «В галерею товара». if ( $add_to_gallery ) { $layout = Gallery_Layout::add_to_gallery( $attachment_id, $old_main, $old_gallery, Settings::gallery_position() ); } } elseif ( self::TARGET_MAIN === $target ) { $layout = Gallery_Layout::set_main( $attachment_id, $old_main, $old_gallery, Settings::old_main() ); } else { $layout = Gallery_Layout::add_to_gallery( $attachment_id, $old_main, $old_gallery, Settings::gallery_position() ); } // Товар записывается, только если изображение или галерея изменились: сохранение // в вариацию без галочки товар не трогает. if ( $layout['main'] !== $old_main || $layout['gallery'] !== $old_gallery ) { $product->set_image_id( $layout['main'] ); $product->set_gallery_image_ids( $layout['gallery'] ); $product->save(); } // Счётчик и дата для колонки и строки под кнопкой: считаются изображение товара // и галерея, изображения вариаций в счёт не входят; дата — любого сохранения. $saved_count = count( Image_Importer::made_by_aimodelka( array_merge( array( $layout['main'] ), $layout['gallery'] ) ) ); update_post_meta( $product_id, Meta::SAVED_COUNT, $saved_count ); update_post_meta( $product_id, Meta::LAST_SAVED_AT, time() ); self::clear_pending( $product_id ); Notices::remove_failed_save( $product_id ); // Витрина должна показать новое фото сразу, а не после «Обновить» в редакторе. Product_Caches::clear( $product_id ); Logger::info( 'Photo saved to the product', array( 'product_id' => $product_id, 'photo_session_id' => $session_id, 'attachment_id' => $attachment_id, 'target' => $target, 'main_image' => $layout['main'], 'gallery' => $layout['gallery'], 'variations' => array_column( $variation_images, 'variationId' ), 'aimodelka_photos' => $saved_count, ) ); $gallery_images = array(); foreach ( $layout['gallery'] as $gallery_attachment_id ) { $gallery_images[] = array( 'id' => $gallery_attachment_id, 'thumbUrl' => (string) wp_get_attachment_image_url( $gallery_attachment_id, 'thumbnail' ), ); } return array( 'featuredImageId' => $layout['main'], 'galleryImages' => $gallery_images, 'savedCount' => $saved_count, 'variationImages' => $variation_images, // Состояние товара после сохранения — окно обновит пометки без отдельного // запроса. Изображение и галерея — те, что только что записаны: страница // тут же ставит их в форму. 'state' => Product_State::for_window( $product, $layout['main'], $layout['gallery'] ), ); } /** * Ставит вложение изображением всем вариациям, подходящим под выбор. * * Прежние изображения вариаций остаются в медиатеке и никуда не переезжают: своего * места в карточке у них нет. Изображение товара не меняется. * * @param \WC_Product $product Товар с вариациями. * @param int $attachment_id Вложение. * @param array $variation Выбор: код атрибута → код значения. * @return array Что записано — для страницы товара. * @throws Action_Failed Под выбор не подошла ни одна вариация. */ private static function set_variation_images( \WC_Product $product, int $attachment_id, array $variation ): array { $matched = Variation_Matcher::matching( Product_State::variations( $product ), $variation ); if ( array() === $matched ) { throw new Action_Failed( __( 'No variation of this product matches the chosen attributes. Check the product’s variations and try again.', 'aimodelka' ) ); } $result = array(); $thumb_url = (string) wp_get_attachment_image_url( $attachment_id, 'thumbnail' ); foreach ( $matched as $variation_id ) { $item = wc_get_product( $variation_id ); if ( ! $item || ! $item->is_type( 'variation' ) ) { continue; } $item->set_image_id( $attachment_id ); $item->save(); $result[] = array( 'variationId' => $variation_id, 'attachmentId' => $attachment_id, 'thumbUrl' => $thumb_url, ); } return $result; } /** * Выбор вариации из записи ожидающего сохранения: только непустые строки; пусто — null * (товар целиком). * * @param mixed $value Что лежит в записи. * @return array|null */ private static function variation_choice( mixed $value ): ?array { if ( ! is_array( $value ) ) { return null; } $choice = array(); foreach ( $value as $code => $chosen ) { if ( is_string( $code ) && '' !== $code && is_string( $chosen ) && '' !== $chosen ) { $choice[ $code ] = $chosen; } } return array() === $choice ? null : $choice; } }