From: fomichev Date: Tue, 12 Nov 2024 15:05:54 +0000 (+0300) Subject: Merge branch 'refs/heads/develop' into feature_fomichev_erp_149_flowwow_feed X-Git-Tag: 1.6~13^2~2 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=2447d74eeca445d908adf9d7aa9efb07b0058114;p=erp24_rep%2Fyii-erp24%2F.git Merge branch 'refs/heads/develop' into feature_fomichev_erp_149_flowwow_feed # Conflicts: # erp24/services/MarketplaceService.php --- 2447d74eeca445d908adf9d7aa9efb07b0058114 diff --cc erp24/services/MarketplaceService.php index a227da03,975e6403..f64398fd --- a/erp24/services/MarketplaceService.php +++ b/erp24/services/MarketplaceService.php @@@ -254,480 -178,8 +254,483 @@@ class MarketplaceServic } } } + // var_dump($distribution); + + return $distribution; + } + + + /** + * Статический метод для получения всей информации по продуктам, которая необходима для создания фида. + * + * @return array + */ + public static function getAllProductsInfo($id) + { + $parents = ProductsClass::find() + ->select('category_id') + ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE]) + ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE_ADDITIONAL]) + ->column(); + + $products = Products1c::find() + ->where(['tip' => 'products']) + ->andWhere(['not', ['components' => '']]) + ->andWhere(['parent_id' => $parents]) + + ->all(); + + $count = (int)$id; + $selectedProducts = array_slice($products, 0, $count); + + $result = []; + + foreach ($selectedProducts as $product) { + + $properties = MarketplaceService::getProductPropertiesByGuid($product->id); + if (!$properties) { + $message = "Товар с GUID {$product->id} не имеет свойств в MatrixErpProperty и был исключен из фида."; + Yii::error($message, __METHOD__); + + + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'Missing properties error' + ); + continue; + } + + $price = MarketplaceService::getProductPrice($product->id); + + + if ($price == 0) { + $message = "У товара {$product->id} отсутствует цена и он будет исключен из фида."; + Yii::error($message, __METHOD__); + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'Zero price error' + ); + continue; + } + + $components = json_decode($product->components, true); + $composition = []; + + foreach ($components as $componentId => $quantity) { + $component = Products1c::findOne(['id' => $componentId]); + if ($component && $quantity > 0) { + $composition[] = [ + 'name' => $component->name, + 'quantity' => $quantity, + 'unit' => 'шт' + ]; + } + } + + $properties = MarketplaceService::getProductPropertiesByGuid($product->id); + + $result[] = [ + 'id' => $product->id, + 'name' => $properties['displayName'], + 'pictures' => [$properties['imageUrl']], + 'price' => $price, + 'oldprice' => MarketplaceService::getProductOldPrice($product->id), + 'description' => MarketplaceService::getProductDescription($product->id), + 'qty' => MarketplaceService::getProductQty($product->id), + 'amount' => MarketplaceService::getProductQty($product->id), + 'weight' => MarketplaceService::getProductWeight($product->id), + 'minorder' => MarketplaceService::getProductMinOrder($product->id), + 'composition' => $composition, + 'available' => MarketplaceService::getProductAvailability($product->id), + 'category_id' => MarketplaceService::getProductCategory($product->id), + 'category_name' => $properties['flowwowSubcategory'], + 'params' => MarketplaceService::getProductParams($product->id), + 'productLink' => MarketplaceService::getProductLinkByGuid($product->id), + ]; + } + + return $result; + } + + + public static function getProductsInfoForFeed(int $warehouseGuid, array $storeData) + { + + + if (!is_array($storeData)) { + Yii::error('Invalid data format for storeData; expected array.', __METHOD__); + return []; + } + + $store = MarketplaceStore::findOne(['warehouse_guid' => $warehouseGuid]); + if (!$store) { + Yii::error("Не найден склад для GUID {$warehouseGuid}", __METHOD__); + return []; + } + $storeGuid = $store->guid; + + + if (!isset($storeData[$storeGuid])) { + Yii::warning("Не найдено данных store GUID {$storeGuid}", __METHOD__); + return []; + } + + + $productQuantities = $storeData[$storeGuid]; + + + $products = Products1c::find() + ->where(['id' => array_keys($productQuantities)]) + ->andWhere(['!=', 'components', '']) + ->all(); + + $result = []; + + foreach ($products as $product) { + $properties = MarketplaceService::getProductPropertiesByGuid($product->id); + if (!$properties) { + $message = "Товар с GUID {$product->id} не имеет свойств в MatrixErpProperty и был исключен из фида."; + Yii::error($message, __METHOD__); + // return Json::encode($distribution); + return $distribution; + } + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'Missing properties error' + ); + continue; + } + + $price = MarketplaceService::getProductPrice($product->id); + + if ($price == 0) { + $message = "У товара {$product->id} отсутствует цена и он будет исключен из фида."; + Yii::error($message, __METHOD__); + + + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'Zero price error' + ); + continue; + } + + $components = json_decode($product->components, true); + $composition = []; + + foreach ($components as $componentId => $quantity) { + $component = Products1c::findOne(['id' => $componentId]); + if ($component && $quantity > 0) { + $composition[] = [ + 'name' => $component->name, + 'quantity' => $quantity, + 'unit' => 'шт' + ]; + } + } + + + $availableQty = $productQuantities[$product->id] ?? 0; + + $result[] = [ + 'id' => $product->id, + 'name' => $properties['displayName'], + 'pictures' => [$properties['imageUrl']], + 'price' => $price, + 'oldprice' => MarketplaceService::getProductOldPrice($product->id), + 'description' => MarketplaceService::getProductDescription($product->id), + 'qty' => $availableQty, + 'amount' => $availableQty, + 'weight' => MarketplaceService::getProductWeight($product->id), + 'minorder' => MarketplaceService::getProductMinOrder($product->id), + 'composition' => $composition, + 'available' => MarketplaceService::getProductAvailability($availableQty), + 'category_id' => MarketplaceService::getProductCategory($product->id), + 'category_name' => $properties['flowwowSubcategory'], + 'params' => MarketplaceService::getProductParams($product->id), + 'productLink' => MarketplaceService::getProductLinkByGuid($product->id), + ]; + } + + return $result; + } + + /** + * Статический метод для создания XML-фида на основе информации о продуктах. + * + * @param array $productsInfo + * @return string + */ + public static function createXMLFeed($productsInfo) + { + $xml = new \SimpleXMLElement(''); + $xml->addAttribute('date', date('Y-m-d H:i')); + + $shop = $xml->addChild('shop'); + $shop->addChild('name', 'Интернет магазин База Цветов 24'); + $shop->addChild('company', 'Интернет магазин База Цветов 24'); + $shop->addChild('url', 'https://bazacvetov24.ru'); + $shop->addChild('platform', 'BSM/Yandex/Market'); + + // Добавление валюты + $currencies = $shop->addChild('currencies'); + $currency = $currencies->addChild('currency'); + $currency->addAttribute('id', 'RUB'); + $currency->addAttribute('rate', '1'); + + // Добавление категорий (пример добавления нескольких категорий) + $uniqueCategories = []; + foreach ($productsInfo as $product) { + $categoryId = $product['category_id']; + $categoryName = $product['category_name']; + + + if (!isset($uniqueCategories[$categoryId])) { + $uniqueCategories[$categoryId] = $categoryName; + } + } + + + $categories = $shop->addChild('categories'); + foreach ($uniqueCategories as $id => $name) { + $category = $categories->addChild('category', $name); + $category->addAttribute('id', $id); + } + + // Добавление офферов (продуктов) + $offers = $shop->addChild('offers'); + foreach ($productsInfo as $product) { + $offer = $offers->addChild('offer'); + $offer->addAttribute('id', $product['id']); + $offer->addAttribute('available', $product['available'] ? 'true' : 'false'); + + // Добавление URL продукта + $offer->addChild('url', $product['productLink']); + + // Добавление цены и валюты + $offer->addChild('price', $product['price']); + // $offer->addChild('oldPrice', $product['oldprice']); + $offer->addChild('currencyId', 'RUB'); + $offer->addChild('categoryId', $product['category_id']); + + // Добавление доступности доставки + $offer->addChild('delivery', 'true'); + + // Название продукта + $offer->addChild('name', $product['name']); + + // Описание продукта + if (!empty($product['description'])) { + $offer->addChild('description', $product['description']); + } + + // Добавление веса и количества + // $offer->addChild('weight', $product['weight']); + + if (!(isset($product['category_id']) && str_starts_with((string)$product['category_id'], '1'))) { + $offer->addChild('qty', $product['qty']); + } + + + // $offer->addChild('amount', $product['amount']); + + + foreach ($product['composition'] as $component) { + $consist = $offer->addChild('consist', $component['quantity']); + $consist->addAttribute('name', $component['name']); + $consist->addAttribute('unit', $component['unit']); + + } + + // Добавление параметров + /* if (!empty($product['params'])) { + foreach ($product['params'] as $paramName => $paramValue) { + $param = $offer->addChild('param', $paramValue); + $param->addAttribute('name', $paramName); + } + }*/ + + + + // Добавление изображений продукта + if (!empty($product['pictures'])) { + foreach ($product['pictures'] as $picture) { + $offer->addChild('picture', $picture); + } + } + } + + return $xml->asXML(); + } + + + private static function getProductPropertiesByGuid($guid) { + $product = MatrixErpProperty::find() + ->where(['guid' => $guid]) + ->one(); + + if (!$product) { + return null; + } + + return [ + 'id' => $product->id, + 'description' => $product->description, + 'imageUrl' => self::getProductImageUrl($product->image_id), + 'date' => $product->date, + 'displayName' => $product->display_name, + 'externalImageUrl' => $product->external_image_url, + 'productUrl' => $product->product_url, + 'flowwowCategory' => $product->flowwow_category, + 'flowwowSubcategory' => $product->flowwow_subcategory, + ]; + } + + private static function getProductImageUrl($imageId) { + $image = Images::findOne($imageId); + $fileName = ''; + if ($image && File::src($image->filename, 'images') != null) { + $fileName = File::src($image->filename, 'images'); + return 'https://media.erp-flowers.ru/media/view-url?url=' . $fileName; + } + + + return null; + } + private static function getProductLinkByGuid($guid) { + return 'https://media.erp-flowers.ru/media/view-card?guid=' . urlencode($guid); + } + + private static function getProductPrice($productId) { + $price = Prices::find() + ->where(['product_id' => $productId]) + ->one(); + return $price['price'] ?? 0; + } + private static function getProductOldPrice($productId) { return 300; } + private static function getProductDescription($productId) { + + $product = MatrixErpProperty::find() + ->where(['guid' => $productId]) + ->one(); + + if (!$product) { + return null; + } + + return $product->description; + } + private static function getProductQty($productId) { return 9; } + private static function getProductWeight($productId) { + return 0.5; + } + private static function getProductCategory($productId) { + + $product = MatrixErpProperty::find() + ->where(['guid' => $productId]) + ->one(); + + if (!$product) { + $message = "У товара {$product-> guid} отсутствует запись в таблице свойств."; + Yii::error($message, __METHOD__); + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'No MatrixErpProperty' + ); + return null; + } + + return self::getCategorySubcategoryId($product->flowwow_category, $product->flowwow_subcategory); + } + + public static function getCategorySubcategoryId($category, $subcategory) + { + $categories = self::CATEGORIES_WITH_SUBCATEGORIES; + + if (!array_key_exists($category, $categories)) { + + $message = "У категории {$category} отсутствует запись в таблице свойств."; + Yii::error($message, __METHOD__); + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'No CATEGORIES' + ); + return null; + } + + $categoryIndex = array_search($category, array_keys($categories)) + 1; + + $subcategoryIndex = array_search($subcategory, $categories[$category]); + + if ($subcategoryIndex === false) { + $message = "У подкатегории {$subcategoryIndex} отсутствует запись в таблице свойств."; + Yii::error($message, __METHOD__); + InfoLogService::setInfoLog( + __FILE__, + __LINE__, + $message, + 'No subcategoryIndex' + ); + return null; + } + + return (string)$categoryIndex . (string)$subcategoryIndex; + } + + private static function getProductMinOrder($productId) { + return 1; + } + private static function getProductAvailability($availableQty) { + return $availableQty > 0; + } + + private static function getProductMaterial($productId) + { + // Здесь можно реализовать логику получения материала продукта + return 'Цветы'; // Пример значения + } + + private static function getProductWidth($productId) + { + // Здесь можно реализовать логику получения ширины продукта + return 18; // Пример значения + } + + private static function getProductHeight($productId) + { + // Здесь можно реализовать логику получения высоты продукта + return 20; // Пример значения + } + + private static function getProductLength($productId) + { + // Здесь можно реализовать логику получения длины продукта + return 9; // Пример значения + } + + private static function getProductParams($productId) + { + return [ + + 'Ширина, См' => self::getProductWidth($productId), + 'Высота, См' => self::getProductHeight($productId), + + ]; + } + + + }