reverb.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. class ModelExtensionModuleReverb extends Model {
  3. // -------------------------------------------------------------------------
  4. // Install / Uninstall
  5. // -------------------------------------------------------------------------
  6. public function install() {
  7. $this->db->query("
  8. CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "reverb_product_map` (
  9. `product_id` INT(11) NOT NULL,
  10. `reverb_listing_id` VARCHAR(64) NOT NULL DEFAULT '',
  11. `sync_enabled` TINYINT(1) NOT NULL DEFAULT 0,
  12. `condition_uuid` VARCHAR(64) NOT NULL DEFAULT '',
  13. `reverb_category_uuid` VARCHAR(64) NOT NULL DEFAULT '',
  14. `handmade` TINYINT(1) NOT NULL DEFAULT 0,
  15. `upc_does_not_apply` TINYINT(1) NOT NULL DEFAULT 1,
  16. `last_synced_at` DATETIME NULL DEFAULT NULL,
  17. PRIMARY KEY (`product_id`)
  18. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
  19. ");
  20. $this->migrate();
  21. $this->db->query("
  22. CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "reverb_order_map` (
  23. `reverb_order_number` VARCHAR(64) NOT NULL,
  24. `order_id` INT(11) NOT NULL DEFAULT 0,
  25. `reverb_status` VARCHAR(32) NOT NULL DEFAULT '',
  26. `created_at` DATETIME NOT NULL,
  27. PRIMARY KEY (`reverb_order_number`)
  28. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
  29. ");
  30. $this->db->query("
  31. CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "reverb_sync_log` (
  32. `log_id` INT(11) NOT NULL AUTO_INCREMENT,
  33. `product_id` INT(11) NOT NULL DEFAULT 0,
  34. `direction` ENUM('push','pull') NOT NULL DEFAULT 'push',
  35. `status` ENUM('success','error') NOT NULL DEFAULT 'success',
  36. `message` TEXT NOT NULL,
  37. `created_at` DATETIME NOT NULL,
  38. PRIMARY KEY (`log_id`),
  39. KEY `product_id` (`product_id`),
  40. KEY `created_at` (`created_at`)
  41. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
  42. ");
  43. }
  44. public function uninstall() {
  45. $this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "reverb_product_map`");
  46. $this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "reverb_sync_log`");
  47. $this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "reverb_order_map`");
  48. }
  49. public function migrate() {
  50. static $done = false;
  51. if ($done) return;
  52. $done = true;
  53. $this->addColumnIfMissing(DB_PREFIX . 'reverb_product_map', 'handmade', 'TINYINT(1) NOT NULL DEFAULT 0');
  54. $this->addColumnIfMissing(DB_PREFIX . 'reverb_product_map', 'upc_does_not_apply', 'TINYINT(1) NOT NULL DEFAULT 1');
  55. // Create order map table for upgrades from earlier versions
  56. $this->db->query("
  57. CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "reverb_order_map` (
  58. `reverb_order_number` VARCHAR(64) NOT NULL,
  59. `order_id` INT(11) NOT NULL DEFAULT 0,
  60. `reverb_status` VARCHAR(32) NOT NULL DEFAULT '',
  61. `created_at` DATETIME NOT NULL,
  62. PRIMARY KEY (`reverb_order_number`)
  63. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  64. ");
  65. }
  66. private function addColumnIfMissing($table, $column, $definition) {
  67. $r = $this->db->query("
  68. SELECT COUNT(*) AS cnt FROM information_schema.COLUMNS
  69. WHERE TABLE_SCHEMA = DATABASE()
  70. AND TABLE_NAME = '" . $this->db->escape($table) . "'
  71. AND COLUMN_NAME = '" . $this->db->escape($column) . "'
  72. ");
  73. if (empty($r->row['cnt'])) {
  74. $this->db->query("ALTER TABLE `" . $table . "` ADD COLUMN `" . $column . "` " . $definition);
  75. }
  76. }
  77. // -------------------------------------------------------------------------
  78. // Product map CRUD
  79. // -------------------------------------------------------------------------
  80. public function getProductMap($product_id) {
  81. $this->migrate();
  82. $query = $this->db->query("
  83. SELECT * FROM `" . DB_PREFIX . "reverb_product_map`
  84. WHERE `product_id` = '" . (int)$product_id . "'
  85. ");
  86. return $query->num_rows ? $query->row : null;
  87. }
  88. public function saveProductMap($product_id, array $data) {
  89. $this->migrate();
  90. $existing = $this->getProductMap($product_id);
  91. $sync_enabled = isset($data['sync_enabled']) ? (int)(bool)$data['sync_enabled'] : 0;
  92. $condition_uuid = isset($data['condition_uuid']) ? $this->db->escape($data['condition_uuid']) : '';
  93. $reverb_category_uuid = isset($data['reverb_category_uuid']) ? $this->db->escape($data['reverb_category_uuid']) : '';
  94. $reverb_listing_id = isset($data['reverb_listing_id']) ? $this->db->escape($data['reverb_listing_id']) : '';
  95. $last_synced_at = isset($data['last_synced_at']) ? "'" . $this->db->escape($data['last_synced_at']) . "'" : 'NULL';
  96. $handmade = isset($data['handmade']) ? (int)(bool)$data['handmade'] : 0;
  97. $upc_does_not_apply = isset($data['upc_does_not_apply']) ? (int)(bool)$data['upc_does_not_apply'] : 1;
  98. if ($existing) {
  99. $this->db->query("
  100. UPDATE `" . DB_PREFIX . "reverb_product_map`
  101. SET `sync_enabled` = $sync_enabled,
  102. `condition_uuid` = '$condition_uuid',
  103. `reverb_category_uuid` = '$reverb_category_uuid',
  104. `handmade` = $handmade,
  105. `upc_does_not_apply` = $upc_does_not_apply"
  106. . (!empty($reverb_listing_id) ? ", `reverb_listing_id` = '$reverb_listing_id'" : '')
  107. . (isset($data['last_synced_at']) ? ", `last_synced_at` = $last_synced_at" : '')
  108. . " WHERE `product_id` = '" . (int)$product_id . "'"
  109. );
  110. } else {
  111. $this->db->query("
  112. INSERT INTO `" . DB_PREFIX . "reverb_product_map`
  113. (`product_id`, `sync_enabled`, `condition_uuid`, `reverb_category_uuid`,
  114. `reverb_listing_id`, `handmade`, `upc_does_not_apply`, `last_synced_at`)
  115. VALUES (
  116. '" . (int)$product_id . "',
  117. $sync_enabled,
  118. '$condition_uuid',
  119. '$reverb_category_uuid',
  120. '$reverb_listing_id',
  121. $handmade,
  122. $upc_does_not_apply,
  123. $last_synced_at
  124. )
  125. ");
  126. }
  127. }
  128. public function updateListingId($product_id, $listing_id) {
  129. $this->db->query("
  130. UPDATE `" . DB_PREFIX . "reverb_product_map`
  131. SET `reverb_listing_id` = '" . $this->db->escape($listing_id) . "',
  132. `last_synced_at` = NOW()
  133. WHERE `product_id` = '" . (int)$product_id . "'
  134. ");
  135. }
  136. /**
  137. * Return all products eligible for sync (sync_enabled = 1, in allowed categories).
  138. *
  139. * @param array $allowed_category_ids List of OC category IDs.
  140. * @return array
  141. */
  142. public function getSyncEnabledProducts(array $allowed_category_ids) {
  143. if (empty($allowed_category_ids)) {
  144. return [];
  145. }
  146. $ids = implode(',', array_map('intval', $allowed_category_ids));
  147. $query = $this->db->query("
  148. SELECT p.product_id, pd.name, pd.description, p.model, p.price, p.quantity, p.image,
  149. r.reverb_listing_id, r.condition_uuid, r.reverb_category_uuid,
  150. r.handmade, r.upc_does_not_apply,
  151. m.name AS manufacturer
  152. FROM `" . DB_PREFIX . "product` p
  153. INNER JOIN `" . DB_PREFIX . "product_description` pd
  154. ON pd.product_id = p.product_id AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  155. INNER JOIN `" . DB_PREFIX . "product_to_category` ptc
  156. ON ptc.product_id = p.product_id AND ptc.category_id IN ($ids)
  157. INNER JOIN `" . DB_PREFIX . "reverb_product_map` r
  158. ON r.product_id = p.product_id AND r.sync_enabled = 1
  159. LEFT JOIN `" . DB_PREFIX . "manufacturer` m
  160. ON m.manufacturer_id = p.manufacturer_id
  161. WHERE p.status = 1
  162. GROUP BY p.product_id
  163. ");
  164. return $query->rows;
  165. }
  166. // -------------------------------------------------------------------------
  167. // Product images
  168. // -------------------------------------------------------------------------
  169. public function getProductImages($product_id) {
  170. $images = [];
  171. $product_query = $this->db->query("
  172. SELECT image FROM `" . DB_PREFIX . "product`
  173. WHERE product_id = '" . (int)$product_id . "'
  174. ");
  175. if ($product_query->num_rows && !empty($product_query->row['image'])) {
  176. $images[] = $product_query->row['image'];
  177. }
  178. $gallery_query = $this->db->query("
  179. SELECT image FROM `" . DB_PREFIX . "product_image`
  180. WHERE product_id = '" . (int)$product_id . "'
  181. ORDER BY sort_order ASC
  182. ");
  183. foreach ($gallery_query->rows as $row) {
  184. $images[] = $row['image'];
  185. }
  186. return $images;
  187. }
  188. // -------------------------------------------------------------------------
  189. // Category mappings (OC category → Reverb category UUID)
  190. // -------------------------------------------------------------------------
  191. public function getCategoryMappings() {
  192. $raw = $this->config->get('module_reverb_category_mappings');
  193. return $raw ? json_decode($raw, true) : [];
  194. }
  195. public function saveCategoryMappings(array $mappings) {
  196. $this->load->model('setting/setting');
  197. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_category_mappings', json_encode($mappings));
  198. }
  199. // -------------------------------------------------------------------------
  200. // Reverb metadata cache (conditions + categories)
  201. // -------------------------------------------------------------------------
  202. public function getListingConditions() {
  203. $cached = $this->config->get('module_reverb_conditions_cache');
  204. $cached_at = (int)$this->config->get('module_reverb_conditions_cached_at');
  205. if ($cached && (time() - $cached_at) < 86400) {
  206. return json_decode($cached, true);
  207. }
  208. try {
  209. $api = $this->getApi();
  210. $resp = $api->getListingConditions();
  211. $conditions = isset($resp['conditions']) ? $resp['conditions'] : [];
  212. $this->load->model('setting/setting');
  213. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_conditions_cache', json_encode($conditions));
  214. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_conditions_cached_at', time());
  215. return $conditions;
  216. } catch (Exception $e) {
  217. return $cached ? json_decode($cached, true) : [];
  218. }
  219. }
  220. public function getReverbCategories() {
  221. $cached = $this->config->get('module_reverb_categories_cache');
  222. $cached_at = (int)$this->config->get('module_reverb_categories_cached_at');
  223. if ($cached && (time() - $cached_at) < 86400) {
  224. return json_decode($cached, true);
  225. }
  226. try {
  227. $api = $this->getApi();
  228. $resp = $api->getCategories();
  229. $categories = isset($resp['categories']) ? $resp['categories'] : [];
  230. $this->load->model('setting/setting');
  231. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_categories_cache', json_encode($categories));
  232. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_categories_cached_at', time());
  233. return $categories;
  234. } catch (Exception $e) {
  235. return $cached ? json_decode($cached, true) : [];
  236. }
  237. }
  238. /**
  239. * Return Reverb categories grouped by their root (top-level) category name.
  240. * Parses the full_name field (e.g. "Guitars > Electric Guitars > Solidbody").
  241. *
  242. * @return array ['Root Name' => [['uuid'=>..., 'full_name'=>..., 'name'=>...], ...], ...]
  243. */
  244. public function getReverbCategoriesGrouped() {
  245. $flat = $this->getReverbCategories();
  246. $grouped = [];
  247. foreach ($flat as $cat) {
  248. $full = $cat['full_name'] ?? $cat['name'] ?? '';
  249. $parts = array_map('trim', explode('>', $full));
  250. $root = $parts[0] ?: 'Other';
  251. $grouped[$root][] = $cat;
  252. }
  253. ksort($grouped);
  254. return $grouped;
  255. }
  256. // -------------------------------------------------------------------------
  257. // Sync log
  258. // -------------------------------------------------------------------------
  259. public function log($product_id, $direction, $status, $message) {
  260. $this->db->query("
  261. INSERT INTO `" . DB_PREFIX . "reverb_sync_log`
  262. (`product_id`, `direction`, `status`, `message`, `created_at`)
  263. VALUES (
  264. '" . (int)$product_id . "',
  265. '" . $this->db->escape($direction) . "',
  266. '" . $this->db->escape($status) . "',
  267. '" . $this->db->escape(substr($message, 0, 65535)) . "',
  268. NOW()
  269. )
  270. ");
  271. }
  272. public function clearSyncLog() {
  273. $this->db->query("DELETE FROM `" . DB_PREFIX . "reverb_sync_log`");
  274. }
  275. public function getSyncLog($limit = 100) {
  276. $query = $this->db->query("
  277. SELECT l.*, pd.name AS product_name
  278. FROM `" . DB_PREFIX . "reverb_sync_log` l
  279. LEFT JOIN `" . DB_PREFIX . "product_description` pd
  280. ON pd.product_id = l.product_id
  281. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  282. ORDER BY l.created_at DESC
  283. LIMIT " . (int)$limit
  284. );
  285. return $query->rows;
  286. }
  287. // -------------------------------------------------------------------------
  288. // Sync helpers
  289. // -------------------------------------------------------------------------
  290. /**
  291. * Push a single product to Reverb. Creates or updates the listing and uploads images.
  292. *
  293. * @param array $product Product row (product_id, name, model, price, quantity, image, ...).
  294. * @param array $reverb_data Row from reverb_product_map.
  295. * @param array $settings Global Reverb settings array.
  296. * @return string The Reverb listing ID.
  297. */
  298. public function syncProductToReverb(array $product, array $reverb_data, array $settings) {
  299. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  300. require_once(DIR_SYSTEM . 'library/reverb/ProductMapper.php');
  301. $api = $this->getApi();
  302. $payload = ProductMapper::toReverb($product, $reverb_data, $settings);
  303. // Photos are plain URL strings sent inside the listing payload (Reverb API v3)
  304. $store_url = $settings['store_url'] ?? '';
  305. $images = $this->getProductImages($product['product_id']);
  306. if (!empty($store_url) && !empty($images)) {
  307. $base = rtrim($store_url, '/') . '/image/';
  308. $photos = [];
  309. foreach ($images as $path) {
  310. if (!empty($path)) {
  311. $photos[] = $base . ltrim($path, '/');
  312. }
  313. }
  314. if (!empty($photos)) {
  315. $payload['photos'] = $photos;
  316. $payload['publish'] = true;
  317. $this->log($product['product_id'], 'push', 'success', 'Including ' . count($photos) . ' photo(s): ' . implode(', ', $photos));
  318. }
  319. } elseif (empty($store_url)) {
  320. $this->log($product['product_id'], 'push', 'error', 'Photo upload skipped: store URL not configured (check System > Settings > Store URL)');
  321. } else {
  322. $this->log($product['product_id'], 'push', 'error', 'No images found for this product in OpenCart.');
  323. }
  324. $listing_id = !empty($reverb_data['reverb_listing_id']) ? $reverb_data['reverb_listing_id'] : null;
  325. if ($listing_id) {
  326. $api->updateListing($listing_id, $payload);
  327. } else {
  328. $response = $api->createListing($payload);
  329. $listing_id = $response['id'] ?? ($response['listing']['id'] ?? null);
  330. if (!$listing_id) {
  331. throw new RuntimeException('Reverb did not return a listing ID after create.');
  332. }
  333. $this->updateListingId($product['product_id'], $listing_id);
  334. }
  335. return $listing_id;
  336. }
  337. // -------------------------------------------------------------------------
  338. // Order import (Reverb → OpenCart)
  339. // -------------------------------------------------------------------------
  340. public function importOrdersFromReverb(array $settings) {
  341. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  342. $this->migrate();
  343. $api = $this->getApi();
  344. $last_sync = $this->config->get('module_reverb_order_last_sync');
  345. $imported = 0;
  346. $skipped = 0;
  347. $page = 1;
  348. do {
  349. $response = $api->getOrders($page, 50, $last_sync ?: null);
  350. $orders = $response['orders'] ?? [];
  351. $total_pages = (int)($response['total_pages'] ?? 1);
  352. foreach ($orders as $reverb_order) {
  353. $order_number = $reverb_order['order_number'] ?? null;
  354. if (!$order_number) { $skipped++; continue; }
  355. // Skip already-imported orders
  356. $existing = $this->db->query("
  357. SELECT order_id FROM `" . DB_PREFIX . "reverb_order_map`
  358. WHERE `reverb_order_number` = '" . $this->db->escape($order_number) . "'
  359. ");
  360. if ($existing->num_rows) { $skipped++; continue; }
  361. // Skip cancelled/unpaid
  362. $status = $reverb_order['status'] ?? '';
  363. if (in_array($status, ['cancelled', 'blocked', 'unpaid', 'payment_pending', 'pending_review'])) {
  364. $skipped++; continue;
  365. }
  366. $order_id = $this->createOcOrderFromReverb($reverb_order, $settings);
  367. if ($order_id) {
  368. $this->db->query("
  369. INSERT INTO `" . DB_PREFIX . "reverb_order_map`
  370. (`reverb_order_number`, `order_id`, `reverb_status`, `created_at`)
  371. VALUES (
  372. '" . $this->db->escape($order_number) . "',
  373. '" . (int)$order_id . "',
  374. '" . $this->db->escape($status) . "',
  375. NOW()
  376. )
  377. ");
  378. $this->log(0, 'pull', 'success', 'Imported Reverb order #' . $order_number . ' → OC order #' . $order_id);
  379. $imported++;
  380. }
  381. }
  382. $page++;
  383. } while ($page <= $total_pages);
  384. // Save timestamp so next import only fetches newer orders
  385. $this->load->model('setting/setting');
  386. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_order_last_sync', date('c'));
  387. return ['imported' => $imported, 'skipped' => $skipped];
  388. }
  389. private function createOcOrderFromReverb(array $o, array $settings) {
  390. // Buyer name
  391. $buyer_name = trim($o['buyer_name'] ?? 'Reverb Buyer');
  392. $np = explode(' ', $buyer_name, 2);
  393. $firstname = $np[0];
  394. $lastname = $np[1] ?? '';
  395. // Shipping address
  396. $addr = $o['shipping_address'] ?? [];
  397. $anp = explode(' ', trim($addr['name'] ?? $buyer_name), 2);
  398. $ship_first = $anp[0];
  399. $ship_last = $anp[1] ?? '';
  400. // Amounts
  401. $product_amt = (float)($o['amount_product']['amount'] ?? $o['amount_product'] ?? 0);
  402. $shipping_amt = (float)($o['shipping']['amount'] ?? $o['shipping'] ?? 0);
  403. $total_amt = (float)($o['total']['amount'] ?? $o['total'] ?? ($product_amt + $shipping_amt));
  404. $currency = $o['total']['currency'] ?? $settings['currency'] ?? 'AUD';
  405. $qty = (int)($o['quantity'] ?? 1);
  406. // OC order status mapping
  407. $status_map = ['paid' => 2, 'shipped' => 3, 'received' => 5, 'picked_up' => 5];
  408. $status_id = $status_map[$o['status'] ?? ''] ?? 1;
  409. // Match OC product by Reverb listing ID or SKU
  410. $listing_id = (string)($o['listing_id'] ?? $o['product_id'] ?? '');
  411. $sku = $o['sku'] ?? '';
  412. $title = $o['title'] ?? 'Reverb Item';
  413. $oc_product = ($listing_id ? $this->findOcProductByListingId($listing_id) : null)
  414. ?: ($sku ? $this->findOcProductBySku($sku) : null);
  415. $product_id = $oc_product ? (int)$oc_product['product_id'] : 0;
  416. $product_name = $oc_product ? $oc_product['name'] : $title;
  417. $product_model = $oc_product ? $oc_product['model'] : $sku;
  418. // Currency ID from OC DB
  419. $cq = $this->db->query("SELECT currency_id FROM `" . DB_PREFIX . "currency` WHERE code = '" . $this->db->escape($currency) . "' LIMIT 1");
  420. $currency_id = $cq->num_rows ? (int)$cq->row['currency_id'] : 1;
  421. $date_added = date('Y-m-d H:i:s', strtotime($o['paid_at'] ?? $o['created_at'] ?? 'now'));
  422. $store_name = $this->db->escape($this->config->get('config_name') ?? '');
  423. $store_url = $this->db->escape($settings['store_url'] ?? '');
  424. $lang_id = (int)$this->config->get('config_language_id');
  425. $comment = $this->db->escape('Reverb order #' . ($o['order_number'] ?? ''));
  426. $this->db->query("
  427. INSERT INTO `" . DB_PREFIX . "order` SET
  428. `invoice_prefix` = 'REV-',
  429. `invoice_no` = 0,
  430. `store_id` = 0,
  431. `store_name` = '$store_name',
  432. `store_url` = '$store_url',
  433. `customer_id` = 0,
  434. `customer_group_id` = 1,
  435. `firstname` = '" . $this->db->escape($firstname) . "',
  436. `lastname` = '" . $this->db->escape($lastname) . "',
  437. `email` = '" . $this->db->escape($o['buyer_id'] ?? '') . "',
  438. `telephone` = '" . $this->db->escape($addr['phone'] ?? '') . "',
  439. `fax` = '',
  440. `custom_field` = '{}',
  441. `payment_firstname` = '" . $this->db->escape($ship_first) . "',
  442. `payment_lastname` = '" . $this->db->escape($ship_last) . "',
  443. `payment_company` = '',
  444. `payment_address_1` = '" . $this->db->escape($addr['street_address'] ?? '') . "',
  445. `payment_address_2` = '" . $this->db->escape($addr['extended_address'] ?? '') . "',
  446. `payment_city` = '" . $this->db->escape($addr['locality'] ?? '') . "',
  447. `payment_postcode` = '" . $this->db->escape($addr['postal_code'] ?? '') . "',
  448. `payment_country` = '" . $this->db->escape($addr['country_code'] ?? '') . "',
  449. `payment_country_id` = 0,
  450. `payment_zone` = '" . $this->db->escape($addr['region'] ?? '') . "',
  451. `payment_zone_id` = 0,
  452. `payment_address_format` = '',
  453. `payment_custom_field` = '{}',
  454. `payment_method` = 'Reverb',
  455. `payment_code` = 'reverb',
  456. `shipping_firstname` = '" . $this->db->escape($ship_first) . "',
  457. `shipping_lastname` = '" . $this->db->escape($ship_last) . "',
  458. `shipping_company` = '',
  459. `shipping_address_1` = '" . $this->db->escape($addr['street_address'] ?? '') . "',
  460. `shipping_address_2` = '" . $this->db->escape($addr['extended_address'] ?? '') . "',
  461. `shipping_city` = '" . $this->db->escape($addr['locality'] ?? '') . "',
  462. `shipping_postcode` = '" . $this->db->escape($addr['postal_code'] ?? '') . "',
  463. `shipping_country` = '" . $this->db->escape($addr['country_code'] ?? '') . "',
  464. `shipping_country_id` = 0,
  465. `shipping_zone` = '" . $this->db->escape($addr['region'] ?? '') . "',
  466. `shipping_zone_id` = 0,
  467. `shipping_address_format` = '',
  468. `shipping_custom_field` = '{}',
  469. `shipping_method` = 'Reverb',
  470. `shipping_code` = 'reverb.reverb',
  471. `comment` = '$comment',
  472. `total` = '" . number_format($total_amt, 4, '.', '') . "',
  473. `order_status_id` = $status_id,
  474. `affiliate_id` = 0,
  475. `commission` = '0.0000',
  476. `marketing_id` = 0,
  477. `tracking` = '',
  478. `language_id` = $lang_id,
  479. `currency_id` = $currency_id,
  480. `currency_code` = '" . $this->db->escape($currency) . "',
  481. `currency_value` = '1.00000000',
  482. `ip` = '',
  483. `forwarded_ip` = '',
  484. `user_agent` = 'Reverb Import',
  485. `accept_language` = '',
  486. `date_added` = '" . $this->db->escape($date_added) . "',
  487. `date_modified` = NOW()
  488. ");
  489. $order_id = (int)$this->db->getLastId();
  490. if (!$order_id) return null;
  491. // Order product
  492. $unit_price = $qty > 0 ? $product_amt / $qty : $product_amt;
  493. $this->db->query("
  494. INSERT INTO `" . DB_PREFIX . "order_product` SET
  495. `order_id` = $order_id,
  496. `product_id` = $product_id,
  497. `master_id` = 0,
  498. `name` = '" . $this->db->escape($product_name) . "',
  499. `model` = '" . $this->db->escape($product_model) . "',
  500. `quantity` = $qty,
  501. `price` = '" . number_format($unit_price, 4, '.', '') . "',
  502. `total` = '" . number_format($product_amt, 4, '.', '') . "',
  503. `tax` = '0.0000',
  504. `reward` = 0
  505. ");
  506. // Totals
  507. $this->db->query("INSERT INTO `" . DB_PREFIX . "order_total` SET `order_id`=$order_id, `code`='sub_total', `title`='Sub-Total', `value`='" . number_format($product_amt, 4, '.', '') . "', `sort_order`=1");
  508. if ($shipping_amt > 0) {
  509. $this->db->query("INSERT INTO `" . DB_PREFIX . "order_total` SET `order_id`=$order_id, `code`='shipping', `title`='Shipping', `value`='" . number_format($shipping_amt, 4, '.', '') . "', `sort_order`=3");
  510. }
  511. $this->db->query("INSERT INTO `" . DB_PREFIX . "order_total` SET `order_id`=$order_id, `code`='total', `title`='Total', `value`='" . number_format($total_amt, 4, '.', '') . "', `sort_order`=9");
  512. // History
  513. $this->db->query("INSERT INTO `" . DB_PREFIX . "order_history` SET `order_id`=$order_id, `order_status_id`=$status_id, `notify`=0, `comment`='Imported from Reverb', `date_added`=NOW()");
  514. // Decrement OC stock
  515. if ($product_id) {
  516. $this->db->query("UPDATE `" . DB_PREFIX . "product` SET `quantity`=GREATEST(0,`quantity`-$qty) WHERE `product_id`=$product_id");
  517. }
  518. return $order_id;
  519. }
  520. private function findOcProductByListingId($listing_id) {
  521. if (!$listing_id) return null;
  522. $q = $this->db->query("
  523. SELECT p.product_id, pd.name, p.model, p.price
  524. FROM `" . DB_PREFIX . "reverb_product_map` r
  525. JOIN `" . DB_PREFIX . "product` p ON p.product_id = r.product_id
  526. JOIN `" . DB_PREFIX . "product_description` pd ON pd.product_id = p.product_id
  527. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  528. WHERE r.reverb_listing_id = '" . $this->db->escape($listing_id) . "'
  529. LIMIT 1
  530. ");
  531. return $q->num_rows ? $q->row : null;
  532. }
  533. private function findOcProductBySku($sku) {
  534. if (!$sku) return null;
  535. $q = $this->db->query("
  536. SELECT p.product_id, pd.name, p.model, p.price
  537. FROM `" . DB_PREFIX . "product` p
  538. JOIN `" . DB_PREFIX . "product_description` pd ON pd.product_id = p.product_id
  539. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  540. WHERE p.model = '" . $this->db->escape($sku) . "'
  541. LIMIT 1
  542. ");
  543. return $q->num_rows ? $q->row : null;
  544. }
  545. // -------------------------------------------------------------------------
  546. // Utility
  547. // -------------------------------------------------------------------------
  548. private function getApi() {
  549. $token = $this->config->get('module_reverb_api_token');
  550. if (empty($token)) {
  551. throw new RuntimeException('Reverb API token is not configured.');
  552. }
  553. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  554. return new ReverbApi($token);
  555. }
  556. }