Skip to content

Commit 81e210b

Browse files
Added ajax call to start all product and categories sync after MBE onboarding flow (#409)
* Post FBE onboarding Catalog sync triggered * Added ajx call to trigger all products and category upload after MBE onboarding flow * Unused config removed * Static errors fixed * static errors fixed * PR comments fixed --------- Co-authored-by: Alex Zarichnyi <[email protected]>
1 parent 0e07a17 commit 81e210b

File tree

8 files changed

+289
-12
lines changed

8 files changed

+289
-12
lines changed

app/code/Meta/BusinessExtension/Block/Adminhtml/Setup.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,16 @@ public function fetchConfigurationAjaxRoute()
224224
return $this->fbeHelper->getUrl('fbeadmin/ajax/persistConfiguration');
225225
}
226226

227+
/**
228+
* Fetch configuration ajax route
229+
*
230+
* @return mixed
231+
*/
232+
public function fetchPostFBEOnboardingSyncAjaxRoute()
233+
{
234+
return $this->fbeHelper->getUrl('fbeadmin/ajax/postFBEOnboardingSync');
235+
}
236+
227237
/**
228238
* Get delete asset ids ajax route
229239
*
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Copyright (c) Meta Platforms, Inc. and affiliates.
7+
*
8+
* Licensed under the Apache License, Version 2.0 (the "License");
9+
* you may not use this file except in compliance with the License.
10+
* You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing, software
15+
* distributed under the License is distributed on an "AS IS" BASIS,
16+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
* See the License for the specific language governing permissions and
18+
* limitations under the License.
19+
*/
20+
21+
namespace Meta\BusinessExtension\Controller\Adminhtml\Ajax;
22+
23+
use Meta\BusinessExtension\Helper\FBEHelper;
24+
use Meta\BusinessExtension\Model\System\Config as SystemConfig;
25+
use Meta\Catalog\Helper\CatalogSyncHelper;
26+
use Magento\Backend\App\Action\Context;
27+
use Magento\Framework\Controller\Result\JsonFactory;
28+
29+
class PostFBEOnboardingSync extends AbstractAjax
30+
{
31+
private const ACCESS_TOKEN_NOT_SET_ERROR_MESSAGE =
32+
'Access token is not successfully set after FBE onboarding for store';
33+
34+
/**
35+
* @var FBEHelper
36+
*/
37+
private $fbeHelper;
38+
39+
/**
40+
* @var SystemConfig
41+
*/
42+
private $systemConfig;
43+
44+
/**
45+
* @var CatalogSyncHelper
46+
*/
47+
private $catalogSyncHelper;
48+
49+
/**
50+
* Construct
51+
*
52+
* @param Context $context
53+
* @param JsonFactory $resultJsonFactory
54+
* @param FBEHelper $fbeHelper
55+
* @param SystemConfig $systemConfig
56+
* @param CatalogSyncHelper $catalogSyncHelper
57+
*/
58+
public function __construct(
59+
Context $context,
60+
JsonFactory $resultJsonFactory,
61+
FBEHelper $fbeHelper,
62+
SystemConfig $systemConfig,
63+
CatalogSyncHelper $catalogSyncHelper
64+
) {
65+
parent::__construct($context, $resultJsonFactory, $fbeHelper);
66+
$this->fbeHelper = $fbeHelper;
67+
$this->systemConfig = $systemConfig;
68+
$this->catalogSyncHelper = $catalogSyncHelper;
69+
}
70+
71+
/**
72+
* Execute for json
73+
*
74+
* @return array
75+
*/
76+
public function executeForJson(): array
77+
{
78+
$storeId = $this->getRequest()->getParam('storeId');
79+
if (!$storeId) {
80+
$response['success'] = false;
81+
$response['message'] = __('StoreId param is not set for Post FBE onboarding sync');
82+
$this->fbeHelper->log('StoreId param is not set for Post FBE onboarding sync');
83+
return $response;
84+
}
85+
86+
try {
87+
$storeName = $this->systemConfig->getStoreManager()->getStore($storeId)->getName();
88+
if (!$this->systemConfig->getAccessToken($storeId)) {
89+
$response['success'] = false;
90+
$response['message'] = __(
91+
'%1 %2',
92+
self::ACCESS_TOKEN_NOT_SET_ERROR_MESSAGE,
93+
$storeName
94+
);
95+
$this->fbeHelper->log(sprintf(
96+
'%s %s',
97+
self::ACCESS_TOKEN_NOT_SET_ERROR_MESSAGE,
98+
$storeName
99+
));
100+
return $response;
101+
}
102+
103+
// Immediately after onboarding we initiate full catalog sync.
104+
// It syncs all products and all categories to Meta Catalog
105+
$this->catalogSyncHelper->syncFullCatalog($storeId);
106+
107+
$response['success'] = true;
108+
$response['message'] = 'Post FBE Onboarding Sync successful';
109+
return $response;
110+
} catch (\Throwable $e) {
111+
$response['success'] = false;
112+
$response['message'] = $e->getMessage();
113+
$this->fbeHelper->logExceptionImmediatelyToMeta(
114+
$e,
115+
[
116+
'store_id' => $storeId,
117+
'event' => 'post_fbe_onboarding',
118+
'event_type' => 'post_fbe_onboarding_sync'
119+
]
120+
);
121+
return $response;
122+
}
123+
}
124+
}

app/code/Meta/BusinessExtension/composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"magento/module-eav": "*",
1414
"magento/module-security": "*",
1515
"magento/module-store": "*",
16+
"meta/module-catalog": "*",
1617
"facebook/php-business-sdk": "^15.0.0"
1718
},
1819
"autoload": {

app/code/Meta/BusinessExtension/view/adminhtml/templates/setup.phtml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
setAccessToken: '<?= $escaper->escapeHtml($block->getAccessTokenAjaxRoute()) ?>',
1616
setProfilesData: '<?= $escaper->escapeHtml($block->getProfilesAjaxRoute()) ?>',
1717
saveConfig: '<?= $escaper->escapeHtml($block->fetchConfigurationAjaxRoute()) ?>',
18+
postFBEOnboardingSync: '<?= $escaper->escapeHtml($block->fetchPostFBEOnboardingSyncAjaxRoute()) ?>',
1819
cleanConfigCacheUrl: '<?= $escaper->escapeHtml($block->getCleanCacheAjaxRoute()) ?>',
1920
fbeLoginUrl: "https://business.facebook.com/fbe-iframe-get-started/?",
2021
deleteConfigKeys: '<?= $escaper->escapeHtml($block->getDeleteAssetIdsAjaxRoute()) ?>',

app/code/Meta/BusinessExtension/view/adminhtml/web/js/fbe_allinone.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ jQuery('#store').on('change', function() {
255255
_this.saveConfig(accessToken, catalogId, pageId, commercePartnerIntegrationId);
256256
_this.saveInstalledFeatures(installedFeatures);
257257
_this.cleanConfigCache();
258+
_this.postFBEOnboardingSync();
258259

259260
if (window.facebookBusinessExtensionConfig.isCommerceEmbeddedExtensionEnabled) {
260261
window.location.reload();
@@ -453,6 +454,25 @@ jQuery('#store').on('change', function() {
453454
}
454455
});
455456
},
457+
postFBEOnboardingSync: function postFBEOnboardingSync() {
458+
var _this = this;
459+
jQuery.ajax({
460+
type: 'post',
461+
url: ajaxify(window.facebookBusinessExtensionConfig.postFBEOnboardingSync),
462+
async : true,
463+
data: ajaxParam({
464+
storeId: window.facebookBusinessExtensionConfig.storeId,
465+
}),
466+
success: function onSuccess(data, _textStatus, _jqXHR) {
467+
if(data.success) {
468+
_this.consoleLog('Post FBE Onboarding sync completed');
469+
}
470+
},
471+
error: function() {
472+
console.error('There was a problem with Post FBE onboarding sync');
473+
}
474+
});
475+
},
456476
deleteFBAssets: function deleteFBAssets() {
457477
var _this = this;
458478
jQuery.ajax({

app/code/Meta/BusinessExtension/view/adminhtml/web/js/lib/fbe.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ jQuery('#store').on('change', function() {
117117
_this.saveConfig(accessToken, catalogId, pageId, commercePartnerIntegrationId);
118118
_this.saveInstalledFeatures(installedFeatures);
119119
_this.cleanConfigCache();
120+
_this.postFBEOnboardingSync();
120121

121122
if (window.facebookBusinessExtensionConfig.isCommerceEmbeddedExtensionEnabled) {
122123
window.location.reload();
@@ -315,6 +316,25 @@ jQuery('#store').on('change', function() {
315316
}
316317
});
317318
},
319+
postFBEOnboardingSync: function postFBEOnboardingSync() {
320+
var _this = this;
321+
jQuery.ajax({
322+
type: 'post',
323+
url: ajaxify(window.facebookBusinessExtensionConfig.postFBEOnboardingSync),
324+
async : true,
325+
data: ajaxParam({
326+
storeId: window.facebookBusinessExtensionConfig.storeId,
327+
}),
328+
success: function onSuccess(data, _textStatus, _jqXHR) {
329+
if(data.success) {
330+
_this.consoleLog('Post FBE Onboarding sync completed');
331+
}
332+
},
333+
error: function() {
334+
console.error('There was a problem with Post FBE onboarding sync');
335+
}
336+
});
337+
},
318338
deleteFBAssets: function deleteFBAssets() {
319339
var _this = this;
320340
jQuery.ajax({
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Copyright (c) Meta Platforms, Inc. and affiliates.
7+
*
8+
* Licensed under the Apache License, Version 2.0 (the "License");
9+
* you may not use this file except in compliance with the License.
10+
* You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing, software
15+
* distributed under the License is distributed on an "AS IS" BASIS,
16+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
* See the License for the specific language governing permissions and
18+
* limitations under the License.
19+
*/
20+
21+
namespace Meta\Catalog\Helper;
22+
23+
use Meta\BusinessExtension\Helper\FBEHelper;
24+
use Meta\BusinessExtension\Model\System\Config as SystemConfig;
25+
use Meta\Catalog\Model\Feed\CategoryCollection;
26+
use Meta\Catalog\Model\Product\Feed\Uploader;
27+
28+
class CatalogSyncHelper
29+
{
30+
31+
/**
32+
* @var FBEHelper
33+
*/
34+
private $fbeHelper;
35+
36+
/**
37+
* @var SystemConfig
38+
*/
39+
private $systemConfig;
40+
41+
/**
42+
* @var Uploader
43+
*/
44+
private $uploader;
45+
46+
/**
47+
* @var CategoryCollection
48+
*/
49+
private $categoryCollection;
50+
51+
/**
52+
* Helper class for syncing Catalog
53+
*
54+
* @param FBEHelper $fbeHelper
55+
* @param SystemConfig $systemConfig
56+
* @param Uploader $uploader
57+
* @param CategoryCollection $categoryCollection
58+
*/
59+
public function __construct(
60+
FBEHelper $fbeHelper,
61+
SystemConfig $systemConfig,
62+
Uploader $uploader,
63+
CategoryCollection $categoryCollection
64+
) {
65+
$this->fbeHelper = $fbeHelper;
66+
$this->systemConfig = $systemConfig;
67+
$this->uploader = $uploader;
68+
$this->categoryCollection = $categoryCollection;
69+
}
70+
71+
/**
72+
* Syncs all products and categories to Meta Catalog
73+
*
74+
* @param int $storeId
75+
* @return void
76+
*/
77+
public function syncFullCatalog(int $storeId)
78+
{
79+
try {
80+
if ($this->systemConfig->isCatalogSyncEnabled($storeId)) {
81+
$this->uploader->uploadFullCatalog($storeId);
82+
$this->categoryCollection->pushAllCategoriesToFbCollections($storeId);
83+
}
84+
} catch (\Throwable $e) {
85+
$context = [
86+
'store_id' => $storeId,
87+
'event' => 'full_catalog_sync',
88+
'event_type' => 'all_products_and_categories_sync',
89+
'catalog_id' => $this->systemConfig->getCatalogId($storeId),
90+
];
91+
$this->fbeHelper->logExceptionImmediatelyToMeta($e, $context);
92+
}
93+
}
94+
}

app/code/Meta/Catalog/Model/Product/Feed/Method/FeedApi.php

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,11 @@ private function getFbFeedId()
144144
/**
145145
* Creates new feed and save it
146146
*
147-
* @param $catalogId
148-
* @param $feedName
147+
* @param string $catalogId
148+
* @param string $feedName
149149
* @throws GuzzleException
150150
*/
151-
private function createNewFeedAndSave($catalogId, $feedName)
151+
private function createNewFeedAndSave(string $catalogId, string $feedName)
152152
{
153153
$feedId = $this->graphApiAdapter->createEmptyFeed($catalogId, $feedName);
154154

@@ -173,10 +173,11 @@ private function createNewFeedAndSave($catalogId, $feedName)
173173
/**
174174
* Verify is feed exists in Meta Catalog, if not returns null
175175
*
176-
* @param $feedId
177-
* @param $catalogFeeds
176+
* @param string $feedId
177+
* @param array $catalogFeeds
178+
* @return string|null
178179
*/
179-
private function verifyFeedExistsInMetaCatalog($feedId, $catalogFeeds)
180+
private function verifyFeedExistsInMetaCatalog(string $feedId, array $catalogFeeds): ?string
180181
{
181182
// make sure feed exists on meta side, not deleted
182183
if ($feedId) {
@@ -193,10 +194,10 @@ private function verifyFeedExistsInMetaCatalog($feedId, $catalogFeeds)
193194
/**
194195
* Saves FB Feed ID to configurations
195196
*
196-
* @param $feedId
197+
* @param string $feedId
197198
* @return void
198199
*/
199-
private function saveFeedId($feedId): void
200+
private function saveFeedId(string $feedId): void
200201
{
201202
$this->systemConfig->saveConfig(
202203
SystemConfig::XML_PATH_FACEBOOK_BUSINESS_EXTENSION_FEED_ID,
@@ -282,23 +283,29 @@ private function generateProductFeed()
282283
* Execute function
283284
*
284285
* @param int|null $storeId
285-
* @return bool|mixed
286-
* @throws Exception
286+
* @throws \Throwable
287287
*/
288288
public function execute($storeId = null)
289289
{
290290
$this->storeId = $storeId;
291291
$this->builder->setStoreId($this->storeId);
292+
$accessToken = $this->systemConfig->getAccessToken($storeId);
293+
if ($accessToken === null) {
294+
$this->logger->critical(
295+
"Full Catalog Sync: can't find access token"
296+
);
297+
return null;
298+
}
292299
$this->graphApiAdapter->setDebugMode($this->systemConfig->isDebugMode($storeId))
293-
->setAccessToken($this->systemConfig->getAccessToken($storeId));
300+
->setAccessToken($accessToken);
294301
try {
295302
$feedId = $this->getFbFeedId();
296303
if (!$feedId) {
297304
throw new LocalizedException(__('Cannot fetch feed ID'));
298305
}
299306
$feed = $this->generateProductFeed();
300307
return $this->graphApiAdapter->pushProductFeed($feedId, $feed);
301-
} catch (Exception $e) {
308+
} catch (\Throwable $e) {
302309
$this->logger->critical($e);
303310
throw $e;
304311
}

0 commit comments

Comments
 (0)