, */ /** * Klasa zawierajaca akcje dla modulu allegro * * @package stAllegroPlugin * @subpackage actions */ class stAllegroBackendActions extends autoStAllegroBackendActions { public function preExecute() { sfLoader::loadHelpers(array('Helper')); sfRichTextEditorTinyMCE::addWebResources(); $config = stConfig::getInstance('stAllegroBackend'); $i18n = $this->getContext()->getI18N(); if (!$config->get('enable') && $this->getActionName() != 'config') { $this->setFlash('warning', $i18n->__('Aby korzystać z Allegro musisz je wpierw włączyć w konfiguracji')); return $this->redirect('@stAllegroPlugin?action=config'); } if ($config->get('access_token') && !$this->hasRequestParameter('code') && !$this->hasRequestParameter('login')) { try { $api = stAllegroApi::getInstance(); $api->getBasicInfoAboutUser(); } catch(stAllegroException $e) { $message = stAllegroApi::getLastErrorsAsString('
'); if ($message == 'Unauthorized') { $message = $i18n->__('Błędna autoryzacja, sprawdź poprawność wprowadzonych danych dostępowych do API', null, 'stAllegroBackend'); } if (strpos($message, 'Invalid refresh token') !== false || strpos($message, 'Access token expired') !== false) { $message = $i18n->__('Token dostępu nie może zostać odświeżony automatycznie proszę ponownie zalogować się do Allegro', null, 'stAllegroBackend'); } $this->setFlash('error', $message, $this->getActionName() != 'config'); if ($this->getActionName() != 'config') { return $this->redirect('@stAllegroPlugin?action=config'); } } } elseif (!$config->get('access_token') && $this->getActionName() != 'config') { $this->setFlash('error', $i18n->__('Błędna autoryzacja, sprawdź poprawność wprowadzonych danych dostępowych do API', null, 'stAllegroBackend')); return $this->redirect('@stAllegroPlugin?action=config'); } } public function executeCreate() { if (!$this->getRequestParameter('product_id')) { return $this->redirect('@stAllegroPlugin?action=chooseProductCreate'); } return parent::executeCreate(); } public function executeAjaxCategoryTree() { $this->path = $this->getRequestParameter('path') ? explode(",", $this->getRequestParameter('path')) : array(); $params = array('status' => 'open', 'children' => $this->getAjaxTreeChildren()); $this->tree = stJQueryToolsHelper::getJsTreeHtmlRow(0, $this->getContext()->getI18N()->__('Kategorie'), $params); } public function executeAjaxSelectAllegroProduct() { $id = $this->getRequestParameter('product'); try { $api = stAllegroApi::getInstance(); $product = $api->getProduct($id); $path = $api->getCategoryPath($product->category->id); } catch(stAllegroException $e) { $errors = stAllegroApi::getLastErrorsAsString('
'); return $this->renderJSON(array( 'errors' => $errors, )); } return $this->renderJSON(array( 'product' => $product, 'category_path' => $path, )); } public function executeAjaxProductSearch() { $api = stAllegroApi::getInstance(); $request = $this->getRequest(); $i18n = $this->getContext()->getI18N(); $params = $request->getParameter('product_search'); if (empty($params['phrase'])) { $this->result = null; } else { try { if (stBarcodeValidator::IsValidEAN13($params['phrase'])) { if (isset($params['category.id']) && $params['category_id']) { unset($params['category.id']); } $params['mode'] = 'GTIN'; } $result = $api->getProducts($params); $this->result = clone $result; unset($result->products); } catch(stAllegroException $e) { $errors = array(); foreach (stAllegroApi::getLastErrors() as $error) { $errors[] = $error->userMessage; } $this->setFlash('warning', $i18n->__('Wystąpił błąd podczas wyszukiwania (%error%)', array('%error%' => implode(', ', $errors))), false); } } } public function executeAjaxCategoryToken() { $query = $this->getRequestParameter('q'); $api = stAllegroApi::getInstance(); $results = array(); try { if (is_numeric($query)) { $response = $api->getCategory($query); if ($response) { if (!$response->leaf) { return $this->renderJson(array()); } $path = array(); $ids = array(); foreach ($api->getCategoryPath($response->id) as $category) { $path[] = $category->name; $ids[] = $category->id; } $id = end($ids); $results[] = array( 'id' => $response->id, 'name' => implode(' / ', $path)." ($id)", 'ids' => implode(",", $ids), ); } } else { $categories = $api->getMatchingCategories($query); $categoryPathHelper = function($category, array &$names = null, array &$ids = null) use (&$categoryPathHelper) { if (null === $names) { $names = array(); } if (null === $ids) { $ids = array(); } if (null !== $category->parent) { $categoryPathHelper($category->parent, $names, $ids); } $names[] = $category->name; $ids[] = $category->id; return array($names, $ids); }; foreach ($categories as $category) { list($names, $ids) = $categoryPathHelper($category); $id = end($ids); $results[] = array( 'id' => $category->id, 'name' => implode(' / ', $names)." ($id)", 'ids' => implode(',', $ids), ); } } } catch(stAllegroException $e) { } return $this->renderJson($results); } public function executeAjaxCategoryChildren() { $this->path = $this->getRequestParameter('path') ? explode(",", $this->getRequestParameter('path')) : array(); $this->id = $this->getRequestParameter('id'); return $this->renderText($this->getAjaxTreeChildren($this->id)); } public function getAjaxTreeChildren($parentId = null) { $api = stAllegroApi::getInstance(); $categories = $api->getCategories($parentId); $tree = ''; foreach ($categories as $category) { $id = $category->id; if (!$category->leaf) { if (!empty($this->path) && in_array($id, $this->path)) $params = array( 'status' => 'open', 'content' => stJQueryToolsHelper::getJsTreeHtmlDefaultControl("jstree-category-id", $id, false, true), 'children' => $this->getAjaxTreeChildren($id), ); else $params = array( 'status' => 'closed', 'content' => stJQueryToolsHelper::getJsTreeHtmlDefaultControl("jstree-category-id", $id, false, true), ); $name = $category->name; } else { $params = array( 'status' => 'leaf', 'content' => stJQueryToolsHelper::getJsTreeHtmlDefaultControl("jstree-category-id", $id, in_array($id, $this->path)), ); $name = $category->name . ' (' . $id . ')'; } $tree .= stJQueryToolsHelper::getJsTreeHtmlRow($id, htmlspecialchars(strtr($name, array("\n" => "", "\r" => "")), ENT_QUOTES), $params); } return $tree; } public function executeAjaxUploadOfferImages() { if ($this->getRequest()->getMethod() == sfRequest::POST) { $images = $this->getRequestParameter('images'); $api = stAllegroApi::getInstance(); $i18n = $this->getContext()->getI18N(); $results = array(); $errors = array(); $c = new Criteria(); $c->add(sfAssetPeer::ID, $images, Criteria::IN); $images = sfAssetPeer::doSelectJoinsfAssetFolder($c); if (!$images) { $errors[] = $i18n->__('Musisz wybrać przynajmniej jedno zdjęcie.'); } else { foreach ($images as $image) { try { $response = $api->uploadImage($image->getFullPath('allegro')); $results[] = $response->location; } catch (stAllegroException $e) { foreach (stAllegroApi::getLastErrors() as $error) { $errors[] = $error->userMessage; } } } } if (!$errors) { return $this->renderJSON(array( 'images' => $results, )); } else { $this->setFlash('error', implode('
', $errors), false); } } $this->product = ProductPeer::retrieveByPK($this->getRequestParameter('product')); } public function executeAjaxUpdateOfferForm() { $api = stAllegroApi::getInstance(); $options = $this->getRequestParameter('options'); if ($this->getRequestParameter('id')) { $offer = AllegroApiOfferPeer::retrieveByPK($this->getRequestParameter('id')); $offer->setCategory(array( 'id' => $this->getRequestParameter('category_id') )); $auction = $offer->getAllegroAuction(); if ($options) { $auction->setProductOptions($options); } $auction->getProductOptionsArray(); $product = $auction->getProduct(); } elseif ($this->getRequestParameter('product_id')) { $product = ProductPeer::retrieveByPK($this->getRequestParameter('product_id')); $auction = new AllegroAuction(); $auction->setProduct($product); if ($options) { $auction->setProductOptions($options); } $auction->getProductOptionsArray(); $offer = $this->getDefaultOffer($product); $offer->setCategory(array( 'id' => $this->getRequestParameter('category_id'), )); } $this->getUser()->setParameter('auction', $auction, 'soteshop/stAllegroPlugin'); if (!isset($offer->promotion)) { $offer->setPromotion(array( "bold" => false, "departmentPage" => false, "emphasized" => false, "emphasizedHighlightBoldPackage" => false, "highlight" => false, )); } if ($this->getRequestParameter('parameters')) { $offer->setParameters($this->getRequestParameter('parameters')); } $content = $this->getRenderComponent('stAllegroBackend', 'offerForm', array('offer' => $offer)); return $this->renderText($content); } public function executeDuplicate() { try { $i18n = $this->getContext()->getI18N(); $this->labels = $this->getLabels(); $id = $this->getRequestParameter('id'); $offer = AllegroApiOfferPeer::retrieveByPK($id); $offer = clone $offer; $offer->save(); $this->setFlash('success', $i18n->__('Oferta została zduplikowana pomyślnie')); return $this->redirect('@stAllegroPlugin?action=edit&id=' . $offer->getId(). '&product_id=' . $this->getRequestParameter('product_id')); } catch (stAllegroException $e) { $messages = array(); foreach (stAllegroApi::getLastErrors() as $error) { $messages[] = $error->userMessage; } $this->setFlash('error', implode('
', $messages)); return $this->redirect('@stAllegroPlugin?action=list'); } } public function executeAjaxGetProductOptionsPicker() { $id = $this->getRequestParameter('id'); $product = ProductPeer::retrieveByPK($id); $content = ''; if ($product && $product->getOptHasOptions() > 1) { $content = $this->getRenderComponent('stProductOptionsBackend', 'optionPicker', array('product' => $product, 'namespace' => 'allegro_api_offer[shop_product_options]', 'selected' => null)); } return $this->renderText($content); } public function executeEnd() { try { $i18n = $this->getContext()->getI18N(); $id = $this->getRequestParameter('id'); $product_id = $this->getRequestParameter('product_id'); $allegroApiOffer = AllegroApiOfferPeer::retrieveByPK($id); $allegroApiOffer->end(); sleep(1); $this->setFlash('notice', $i18n->__('Twoja oferta zostanie wkrótce zakończona', null, 'stAdminGeneratorPlugin')); return $this->redirect('@stAllegroPlugin?action=edit&id='.$id.'&product_id='.$product_id); } catch(stAllegroException $e) { $messages = array(); foreach (stAllegroApi::getLastErrors() as $error) { $messages[] = $error->userMessage; } $this->setFlash('warning', implode('
', $messages)); return $this->redirect('@stAllegroPlugin?action=edit&id='.$id.'&product_id='.$product_id); } } public function executeAjaxFeePreviewUpdate() { $id = $this->getRequestParameter('id'); $status = $this->getRequestParameter('status'); $offer = $this->getRequestParameter('allegro_api_offer'); $content = $this->getRenderComponent('stAllegroBackend', 'pricingFeePreview', array( 'category' => $offer['category']['id'], 'quantity' => $offer['stock']['available'], 'price' => $offer['selling_mode']['price']['amount'], "bold" => isset($offer['promotion']['bold']), "highlight" => isset($offer['promotion']['highlight']), "departmentPage" => isset($offer['promotion']['department_page']), "emphasized" => isset($offer['promotion']['emphasized']), "emphasizedHighlightBoldPackage" => isset($offer['promotion']['emphasized_highlight_bold_package']), "offerId" => $id ? $id : null, "status" => $status ? $status : null, )); return $this->renderText($content); } public function executeAssignProductEdit() { $result = parent::executeAssignProductEdit(); if (!$this->allegro_api_offer->getAllegroAuction()->productHasOptions()) { $this->hideField('shop_product_options'); } return $result; } public function validateEdit() { $request = $this->getRequest(); $this->related_object = ProductPeer::retrieveByPK($this->getRequestParameter('product_id')); $this->getAllegroApiOfferOrCreate(); if ($request->getMethod() == sfRequest::POST) { $this->updateAllegroApiOfferFromRequest(); } if ($this->allegro_api_offer->getStockAvailable() > $this->allegro_api_offer->getShopProductStock()) { $i18n = $this->getContext()->getI18N(); $this->getRequest()->setError('allegro_api_offer{stock}', $i18n->__("Zwiększ stan magazynowy produktu")); } return !$request->hasErrors(); } public function executeEdit() { try { parent::executeEdit(); } catch (stAllegroException $e) { $messages = array(); $errors = stAllegroApi::getLastErrors(); foreach ($errors as $error) { $messages[] = $error->userMessage; } $this->setFlash('error', implode('
', $messages), false); if ($errors[0]->code == 'NOT_FOUND') { return $this->redirect('@stAllegroPlugin?action=list'); } } if ($this->allegro_api_offer->getValidation() && $this->allegro_api_offer->getValidation()->errors) { $messages = array(); foreach ($this->allegro_api_offer->getValidation()->errors as $error) { $messages[] = $error->userMessage; } $this->getRequest()->setError('{allegro_api}', implode('
', $messages)); } } public function handleErrorEdit() { sfLoader::loadHelpers(array('Helper')); sfRichTextEditorTinyMCE::addWebResources(); return parent::handleErrorEdit(); } public function executeImportOrder() { $api = stAllegroApi::getInstance(); $forms = $api->getOrderCheckoutForms(); $this->count = $forms->totalCount; } public function executeConfig() { $this->config = $this->loadConfigOrCreate(); if ($this->hasRequestParameter('code')) { try { $response = AllegroRestApi::generateToken($this->getRequestParameter('code'), $this->config->get('client_id'), $this->config->get('client_secret'), stAllegroApi::redirectAuthUri(), $this->config->get('sandbox')); if ($response) { $this->config->set('access_token', $response->access_token); $this->config->set('refresh_token', $response->refresh_token); $this->config->set('expires', $response->expires_in + time()); $this->config->set('seller_id', $response->seller_id); $this->config->save(true); return $this->redirect('stAllegroBackend/config'); } } catch(stAllegroException $e) { $errors = AllegroRestApi::getLastErrorsAsString('
'); if ($errors == 'Unauthorized') { $errors = $this->getContext()->getI18N()->__('Błędna autoryzacja, sprawdź poprawność danych dostępowych do API'); } $this->setFlash('error', $errors, false); } } return parent::executeConfig(); } protected function processDelete($id) { $result = parent::processDelete($id); sleep(1); return $result; } protected function updateConfigFromRequest() { $offer_product_commission = $this->config->get('offer_product_commission'); parent::updateConfigFromRequest(); $this->getRequest()->setParameter('require_offer_sync', $offer_product_commission != $this->config->get('offer_product_commission')); } protected function saveConfig() { parent::saveConfig(); if ($this->getRequest()->getParameter('require_offer_sync')) { AllegroAuctionPeer::updateRequiresSync(); } if (floatval(phpversion()) >= 7.1) { stTaskScheluder::forceTaskInitialization(); } if ($this->hasRequestParameter('login')) { return $this->redirect(AllegroRestApi::getAuthLink($this->config->get('client_id'), stAllegroApi::redirectAuthUri(), $this->config->get('sandbox'))); } } protected function getConfigLabels() { $labels = parent::getConfigLabels(); $i18n = $this->getContext()->getI18N(); $labels['API'] = $i18n->__('Allegro REST API'); return $labels; } public function validateConfig() { $i18n = $this->getContext()->getI18N(); if ($this->getRequest()->getMethod() == sfRequest::POST) { $config = $this->getRequestParameter('config'); if (!$config['client_id']) { $this->getRequest()->setError('config{client_id}', $i18n->__('Uzupełnij Client Id')); } if (!$config['client_secret']) { $this->getRequest()->setError('config{client_secret}', $i18n->__('Uzupełnij Client Secret')); } if (!$config['allegro_pl_state']) { $this->getRequest()->setError('config{allegro_pl_state}', $i18n->__('Uzupełnij region')); } if (!$config['allegro_pl_city']) { $this->getRequest()->setError('config{allegro_pl_city}', $i18n->__('Uzupełnij miasto')); } if (!$config['allegro_pl_post_code']) { $this->getRequest()->setError('config{allegro_pl_post_code}', $i18n->__('Uzupełnij kod pocztowy')); } } return !$this->getRequest()->hasErrors(); } protected function getDefaultOffer(Product $product) { $config = stConfig::getInstance('stAllegroBackend'); $allegroCommission = new AllegroCommission(); $offer = new AllegroApiOffer(stAllegroApi::arrayToObject(array( 'id' => null, 'product' => null, 'category' => null, 'parameters' => null, 'publication' => null, 'afterSalesServices' => null, 'sizeTable' => null, 'discounts' => null, 'location' => array( 'city' => $config->get('allegro_pl_city'), 'countryCode' => 'PL', 'postCode' => $config->get('allegro_pl_post_code'), 'province' => strtoupper($config->get('allegro_pl_state')), ), 'images' => null, 'tax' => null, 'name' => $product->getName(), 'external' => array( 'id' => $product->getId(), ), 'sellingMode' => array( 'format' => 'BUY_NOW', 'price' => array( 'amount' => $allegroCommission->calculatePrice($product->getPriceBrutto()), 'currency' => 'PLN', ), ), 'stock' => array( 'available' => $product->getStock(), 'unit' => 'UNIT', ), 'description' => array( 'sections' => array( array( 'items' => array( array( 'type' => 'TEXT', 'content' => $product->getDescription() ? $product->getDescription() : $product->getShortDescription(), ) ) ) ) ), 'delivery' => array( 'shippingRates' => array( 'id' => $config->get('delivery_shipping_rates_id') ), 'handlingTime' => $config->get('delivery_handling_time'), ), 'payments' => array( 'invoice' => $config->get('payments_invoice'), ), 'validation' => null, 'promotion' => null, ))); $afterSalesServices = array(); if ($config->get('return_policy')) { $afterSalesServices['returnPolicy'] = array( 'id' => $config->get('return_policy'), ); } if ($config->get('implied_warranty')) { $afterSalesServices['impliedWarranty'] = array( 'id' => $config->get('implied_warranty'), ); } if ($config->get('warranty')) { $afterSalesServices['warranty'] = array( 'id' => $config->get('warranty'), ); } if ($afterSalesServices) { $offer->setAfterSalesServices($afterSalesServices); } $offer->getAllegroAuction()->setProduct($product); return $offer; } protected function getAllegroApiOfferOrCreate($id = 'id') { if (!isset($this->allegro_api_offer)) { $allegroApiOffer = parent::getAllegroApiOfferOrCreate($id); $allegroApiOffer->getAllegroAuction()->getProductOptionsArray(); if ($allegroApiOffer->isNew()) { $allegroApiOffer = $this->getDefaultOffer($allegroApiOffer->getShopProduct()); } if (!$allegroApiOffer->isNew() && (!$allegroApiOffer->getAllegroAuction() || !$allegroApiOffer->getAllegroAuction()->getProduct())) { return $this->redirect('@stAllegroPlugin?action=assignProductEdit&id='.$allegroApiOffer->getId()); } if (!$allegroApiOffer->getAllegroAuction()->productHasOptions()) { $this->hideField('shop_product_options'); } $this->allegro_api_offer = $allegroApiOffer; } return $this->allegro_api_offer; } protected function getChooseProductAllegroApiOfferOrCreate($id = 'id') { $allegroApiOffer = parent::getChooseProductAllegroApiOfferOrCreate($id); if (!$allegroApiOffer->getAllegroAuction()->productHasOptions()) { $this->hideField('shop_product_options'); } return $allegroApiOffer; } protected function getAssignProductAllegroApiOfferOrCreate($id = 'id') { $allegroApiOffer = parent::getAssignProductAllegroApiOfferOrCreate($id); if (!$allegroApiOffer->getAllegroAuction()->productHasOptions()) { $this->hideField('shop_product_options'); } return $allegroApiOffer; } protected function saveAllegroApiOffer($allegro_api_offer) { try { parent::saveAllegroApiOffer($allegro_api_offer); if ($this->allegro_api_offer->getValidation() && $this->allegro_api_offer->getValidation()->errors) { $messages = array(); foreach ($this->allegro_api_offer->getValidation()->errors as $error) { $messages[] = $error->userMessage; } $this->getRequest()->setError('{allegro_api}', implode('
', $messages)); } elseif ($this->hasRequestParameter('publish')) { $i18n = $this->getContext()->getI18N(); $allegro_api_offer->publish(); $this->setFlash('success', $i18n->__('Oferta została przekazana do publikacji', null, 'stAdminGeneratorPlugin')); } sleep(1); } catch (stAllegroException $e) { $messages = array(); $errors = stAllegroApi::getLastErrors(); foreach ($errors as $error) { $messages[] = $error->userMessage; } $this->getRequest()->setError('{allegro_api}', implode('
', $messages)); if ($errors[0]->code == 'NOT_FOUND') { return $this->redirect('@stAllegroPlugin?action=list'); } } } protected function saveChooseProductAllegroApiOffer($allegro_api_offer) { return $this->redirect('@stAllegroPlugin?action=create&product_id='.$allegro_api_offer->getShopProductId()); } protected function saveAssignProductAllegroApiOffer($allegro_api_offer) { try { parent::saveAssignProductAllegroApiOffer($allegro_api_offer); $i18n = $this->getContext()->getI18N(); if ($this->allegro_api_offer->getValidation() && $this->allegro_api_offer->getValidation()->errors) { $messages = array(); foreach ($this->allegro_api_offer->getValidation()->errors as $error) { $messages[] = $error->userMessage; } $this->getRequest()->setError('{allegro_api}', implode('
', $messages)); } else { $this->setFlash('success', $i18n->__('Twoje zmiany zostały zapisane'), true); } } catch (stAllegroException $e) { $messages = array(); $errors = stAllegroApi::getLastErrors(); foreach ($errors as $error) { $messages[] = $error->userMessage; } $this->getRequest()->setError('{allegro_api}', implode('
', $messages)); if ($errors[0]->code == 'NOT_FOUND') { return $this->redirect('@stAllegroPlugin?action=list'); } } if (!$this->getRequest()->hasErrors()) { return $this->redirect('@stAllegroPlugin?action=edit&id='.$allegro_api_offer->getId().'&product_id='.$this->forward_parameters['product_id']); } } protected function updateAllegroApiOfferFromRequest() { parent::updateAllegroApiOfferFromRequest(); $data = $this->getRequestParameter('allegro_api_offer'); if ($data) { $this->allegro_api_offer->setFromArray($data); } } protected function getLabels() { $labels = parent::getLabels(); $labels['{allegro_api}'] = 'Allegro API'; $labels['allegro_api_offer{stock}'] = 'Ilość'; return $labels; } protected function getAssignProductLabels() { $labels = parent::getAssignProductLabels(); $labels['{allegro_api}'] = 'Allegro API'; return $labels; } protected function addFiltersCriteria($c) { parent::addFiltersCriteria($c); if (isset($this->filters['price']['from']) && "" !== $this->filters['price']['from']) { $c->add(AllegroApiOfferPeer::PRICE_AMOUNT_FROM, $this->filters['price']['from']); } if (isset($this->filters['price']['to']) && "" !== $this->filters['price']['to']) { $c->add(AllegroApiOfferPeer::PRICE_AMOUNT_TO, $this->filters['price']['to']); } if (isset($this->filters['status']) && "" !== $this->filters['status']) { $c->add(AllegroApiOfferPeer::STATUS, $this->filters['status']); } } }