reverb.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 clearListingId($product_id) {
  273. $this->db->query("
  274. UPDATE `" . DB_PREFIX . "reverb_product_map`
  275. SET `reverb_listing_id` = '', `last_synced_at` = NULL
  276. WHERE `product_id` = '" . (int)$product_id . "'
  277. ");
  278. }
  279. public function clearSyncLog() {
  280. $this->db->query("DELETE FROM `" . DB_PREFIX . "reverb_sync_log`");
  281. }
  282. public function getSyncLog($limit = 100) {
  283. $query = $this->db->query("
  284. SELECT l.*, pd.name AS product_name
  285. FROM `" . DB_PREFIX . "reverb_sync_log` l
  286. LEFT JOIN `" . DB_PREFIX . "product_description` pd
  287. ON pd.product_id = l.product_id
  288. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  289. ORDER BY l.created_at DESC
  290. LIMIT " . (int)$limit
  291. );
  292. return $query->rows;
  293. }
  294. // -------------------------------------------------------------------------
  295. // Sync helpers
  296. // -------------------------------------------------------------------------
  297. /**
  298. * Push a single product to Reverb. Creates or updates the listing and uploads images.
  299. *
  300. * @param array $product Product row (product_id, name, model, price, quantity, image, ...).
  301. * @param array $reverb_data Row from reverb_product_map.
  302. * @param array $settings Global Reverb settings array.
  303. * @return string The Reverb listing ID.
  304. */
  305. public function syncProductToReverb(array $product, array $reverb_data, array $settings) {
  306. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  307. require_once(DIR_SYSTEM . 'library/reverb/ProductMapper.php');
  308. $api = $this->getApi();
  309. $payload = ProductMapper::toReverb($product, $reverb_data, $settings);
  310. // Photos are plain URL strings sent inside the listing payload (Reverb API v3)
  311. $store_url = $settings['store_url'] ?? '';
  312. $images = $this->getProductImages($product['product_id']);
  313. if (!empty($store_url) && !empty($images)) {
  314. $base = rtrim($store_url, '/') . '/image/';
  315. $photos = [];
  316. foreach ($images as $path) {
  317. if (!empty($path)) {
  318. $photos[] = $base . ltrim($path, '/');
  319. }
  320. }
  321. if (!empty($photos)) {
  322. $payload['photos'] = $photos;
  323. $payload['publish'] = true;
  324. $this->log($product['product_id'], 'push', 'success', 'Including ' . count($photos) . ' photo(s): ' . implode(', ', $photos));
  325. }
  326. } elseif (empty($store_url)) {
  327. $this->log($product['product_id'], 'push', 'error', 'Photo upload skipped: store URL not configured (check System > Settings > Store URL)');
  328. } else {
  329. $this->log($product['product_id'], 'push', 'error', 'No images found for this product in OpenCart.');
  330. }
  331. $listing_id = !empty($reverb_data['reverb_listing_id']) ? $reverb_data['reverb_listing_id'] : null;
  332. if ($listing_id) {
  333. $api->updateListing($listing_id, $payload);
  334. } else {
  335. $response = $api->createListing($payload);
  336. $listing_id = $response['id'] ?? ($response['listing']['id'] ?? null);
  337. if (!$listing_id) {
  338. throw new RuntimeException('Reverb did not return a listing ID after create.');
  339. }
  340. $this->updateListingId($product['product_id'], $listing_id);
  341. }
  342. return $listing_id;
  343. }
  344. // -------------------------------------------------------------------------
  345. // Order import (Reverb → OpenCart)
  346. // -------------------------------------------------------------------------
  347. public function importOrdersFromReverb(array $settings) {
  348. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  349. $this->migrate();
  350. $api = $this->getApi();
  351. $last_sync = $this->config->get('module_reverb_order_last_sync');
  352. $imported = 0;
  353. $skipped = 0;
  354. $page = 1;
  355. do {
  356. $response = $api->getOrders($page, 50, $last_sync ?: null);
  357. $orders = $response['orders'] ?? [];
  358. $total_pages = (int)($response['total_pages'] ?? 1);
  359. foreach ($orders as $reverb_order) {
  360. $order_number = $reverb_order['order_number'] ?? null;
  361. if (!$order_number) { $skipped++; continue; }
  362. // Skip already-imported orders
  363. $existing = $this->db->query("
  364. SELECT order_id FROM `" . DB_PREFIX . "reverb_order_map`
  365. WHERE `reverb_order_number` = '" . $this->db->escape($order_number) . "'
  366. ");
  367. if ($existing->num_rows) { $skipped++; continue; }
  368. // Skip cancelled/unpaid
  369. $status = $reverb_order['status'] ?? '';
  370. if (in_array($status, ['cancelled', 'blocked', 'unpaid', 'payment_pending', 'pending_review'])) {
  371. $skipped++; continue;
  372. }
  373. $order_id = $this->createOcOrderFromReverb($reverb_order, $settings);
  374. if ($order_id) {
  375. $this->db->query("
  376. INSERT INTO `" . DB_PREFIX . "reverb_order_map`
  377. (`reverb_order_number`, `order_id`, `reverb_status`, `created_at`)
  378. VALUES (
  379. '" . $this->db->escape($order_number) . "',
  380. '" . (int)$order_id . "',
  381. '" . $this->db->escape($status) . "',
  382. NOW()
  383. )
  384. ");
  385. $this->log(0, 'pull', 'success', 'Imported Reverb order #' . $order_number . ' → OC order #' . $order_id);
  386. $imported++;
  387. }
  388. }
  389. $page++;
  390. } while ($page <= $total_pages);
  391. // Save timestamp so next import only fetches newer orders
  392. $this->load->model('setting/setting');
  393. $this->model_setting_setting->editSettingValue('module_reverb', 'module_reverb_order_last_sync', date('c'));
  394. return ['imported' => $imported, 'skipped' => $skipped];
  395. }
  396. private function createOcOrderFromReverb(array $o, array $settings) {
  397. // Buyer name
  398. $buyer_name = trim($o['buyer_name'] ?? 'Reverb Buyer');
  399. $np = explode(' ', $buyer_name, 2);
  400. $firstname = $np[0];
  401. $lastname = $np[1] ?? '';
  402. // Shipping address
  403. $addr = $o['shipping_address'] ?? [];
  404. $anp = explode(' ', trim($addr['name'] ?? $buyer_name), 2);
  405. $ship_first = $anp[0];
  406. $ship_last = $anp[1] ?? '';
  407. // Amounts
  408. $product_amt = (float)($o['amount_product']['amount'] ?? $o['amount_product'] ?? 0);
  409. $shipping_amt = (float)($o['shipping']['amount'] ?? $o['shipping'] ?? 0);
  410. $total_amt = (float)($o['total']['amount'] ?? $o['total'] ?? ($product_amt + $shipping_amt));
  411. $currency = $o['total']['currency'] ?? $settings['currency'] ?? 'AUD';
  412. // Store and quantity from settings
  413. $order_stores = $settings['order_stores'] ?? [0];
  414. $store_id = (int)($order_stores[0] ?? 0);
  415. $default_qty = max(1, (int)($settings['default_qty'] ?? 1));
  416. $qty = (int)($o['quantity'] ?? 0) ?: $default_qty;
  417. // OC order status mapping
  418. $status_map = ['paid' => 2, 'shipped' => 3, 'received' => 5, 'picked_up' => 5];
  419. $status_id = $status_map[$o['status'] ?? ''] ?? 1;
  420. // Match OC product by Reverb listing ID or SKU
  421. $listing_id = (string)($o['listing_id'] ?? $o['product_id'] ?? '');
  422. $sku = $o['sku'] ?? '';
  423. $title = $o['title'] ?? 'Reverb Item';
  424. $oc_product = ($listing_id ? $this->findOcProductByListingId($listing_id) : null)
  425. ?: ($sku ? $this->findOcProductBySku($sku) : null);
  426. $product_id = $oc_product ? (int)$oc_product['product_id'] : 0;
  427. $product_name = $oc_product ? $oc_product['name'] : $title;
  428. $product_model = $oc_product ? $oc_product['model'] : $sku;
  429. // Currency ID from OC DB
  430. $cq = $this->db->query("SELECT currency_id FROM `" . DB_PREFIX . "currency` WHERE code = '" . $this->db->escape($currency) . "' LIMIT 1");
  431. $currency_id = $cq->num_rows ? (int)$cq->row['currency_id'] : 1;
  432. $date_added = date('Y-m-d H:i:s', strtotime($o['paid_at'] ?? $o['created_at'] ?? 'now'));
  433. $store_name = $this->db->escape($this->config->get('config_name') ?? '');
  434. $store_url = $this->db->escape($settings['store_url'] ?? '');
  435. $lang_id = (int)$this->config->get('config_language_id');
  436. $comment = $this->db->escape('Reverb order #' . ($o['order_number'] ?? ''));
  437. $this->db->query("
  438. INSERT INTO `" . DB_PREFIX . "order` SET
  439. `invoice_prefix` = 'REV-',
  440. `invoice_no` = 0,
  441. `store_id` = $store_id,
  442. `store_name` = '$store_name',
  443. `store_url` = '$store_url',
  444. `customer_id` = 0,
  445. `customer_group_id` = 1,
  446. `firstname` = '" . $this->db->escape($firstname) . "',
  447. `lastname` = '" . $this->db->escape($lastname) . "',
  448. `email` = '" . $this->db->escape($o['buyer_id'] ?? '') . "',
  449. `telephone` = '" . $this->db->escape($addr['phone'] ?? '') . "',
  450. `fax` = '',
  451. `custom_field` = '{}',
  452. `payment_firstname` = '" . $this->db->escape($ship_first) . "',
  453. `payment_lastname` = '" . $this->db->escape($ship_last) . "',
  454. `payment_company` = '',
  455. `payment_address_1` = '" . $this->db->escape($addr['street_address'] ?? '') . "',
  456. `payment_address_2` = '" . $this->db->escape($addr['extended_address'] ?? '') . "',
  457. `payment_city` = '" . $this->db->escape($addr['locality'] ?? '') . "',
  458. `payment_postcode` = '" . $this->db->escape($addr['postal_code'] ?? '') . "',
  459. `payment_country` = '" . $this->db->escape($addr['country_code'] ?? '') . "',
  460. `payment_country_id` = 0,
  461. `payment_zone` = '" . $this->db->escape($addr['region'] ?? '') . "',
  462. `payment_zone_id` = 0,
  463. `payment_address_format` = '',
  464. `payment_custom_field` = '{}',
  465. `payment_method` = 'Reverb',
  466. `payment_code` = 'reverb',
  467. `shipping_firstname` = '" . $this->db->escape($ship_first) . "',
  468. `shipping_lastname` = '" . $this->db->escape($ship_last) . "',
  469. `shipping_company` = '',
  470. `shipping_address_1` = '" . $this->db->escape($addr['street_address'] ?? '') . "',
  471. `shipping_address_2` = '" . $this->db->escape($addr['extended_address'] ?? '') . "',
  472. `shipping_city` = '" . $this->db->escape($addr['locality'] ?? '') . "',
  473. `shipping_postcode` = '" . $this->db->escape($addr['postal_code'] ?? '') . "',
  474. `shipping_country` = '" . $this->db->escape($addr['country_code'] ?? '') . "',
  475. `shipping_country_id` = 0,
  476. `shipping_zone` = '" . $this->db->escape($addr['region'] ?? '') . "',
  477. `shipping_zone_id` = 0,
  478. `shipping_address_format` = '',
  479. `shipping_custom_field` = '{}',
  480. `shipping_method` = 'Reverb',
  481. `shipping_code` = 'reverb.reverb',
  482. `comment` = '$comment',
  483. `total` = '" . number_format($total_amt, 4, '.', '') . "',
  484. `order_status_id` = $status_id,
  485. `affiliate_id` = 0,
  486. `commission` = '0.0000',
  487. `marketing_id` = 0,
  488. `tracking` = '',
  489. `language_id` = $lang_id,
  490. `currency_id` = $currency_id,
  491. `currency_code` = '" . $this->db->escape($currency) . "',
  492. `currency_value` = '1.00000000',
  493. `ip` = '',
  494. `forwarded_ip` = '',
  495. `user_agent` = 'Reverb Import',
  496. `accept_language` = '',
  497. `date_added` = '" . $this->db->escape($date_added) . "',
  498. `date_modified` = NOW()
  499. ");
  500. $order_id = (int)$this->db->getLastId();
  501. if (!$order_id) return null;
  502. // Order product
  503. $unit_price = $qty > 0 ? $product_amt / $qty : $product_amt;
  504. $this->db->query("
  505. INSERT INTO `" . DB_PREFIX . "order_product` SET
  506. `order_id` = $order_id,
  507. `product_id` = $product_id,
  508. `master_id` = 0,
  509. `name` = '" . $this->db->escape($product_name) . "',
  510. `model` = '" . $this->db->escape($product_model) . "',
  511. `quantity` = $qty,
  512. `price` = '" . number_format($unit_price, 4, '.', '') . "',
  513. `total` = '" . number_format($product_amt, 4, '.', '') . "',
  514. `tax` = '0.0000',
  515. `reward` = 0
  516. ");
  517. // Totals
  518. $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");
  519. if ($shipping_amt > 0) {
  520. $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");
  521. }
  522. $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");
  523. // History
  524. $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()");
  525. // Decrement OC stock
  526. if ($product_id) {
  527. $this->db->query("UPDATE `" . DB_PREFIX . "product` SET `quantity`=GREATEST(0,`quantity`-$qty) WHERE `product_id`=$product_id");
  528. }
  529. return $order_id;
  530. }
  531. private function findOcProductByListingId($listing_id) {
  532. if (!$listing_id) return null;
  533. $q = $this->db->query("
  534. SELECT p.product_id, pd.name, p.model, p.price
  535. FROM `" . DB_PREFIX . "reverb_product_map` r
  536. JOIN `" . DB_PREFIX . "product` p ON p.product_id = r.product_id
  537. JOIN `" . DB_PREFIX . "product_description` pd ON pd.product_id = p.product_id
  538. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  539. WHERE r.reverb_listing_id = '" . $this->db->escape($listing_id) . "'
  540. LIMIT 1
  541. ");
  542. return $q->num_rows ? $q->row : null;
  543. }
  544. private function findOcProductBySku($sku) {
  545. if (!$sku) return null;
  546. $q = $this->db->query("
  547. SELECT p.product_id, pd.name, p.model, p.price
  548. FROM `" . DB_PREFIX . "product` p
  549. JOIN `" . DB_PREFIX . "product_description` pd ON pd.product_id = p.product_id
  550. AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
  551. WHERE p.model = '" . $this->db->escape($sku) . "'
  552. LIMIT 1
  553. ");
  554. return $q->num_rows ? $q->row : null;
  555. }
  556. // -------------------------------------------------------------------------
  557. // Utility
  558. // -------------------------------------------------------------------------
  559. private function getApi() {
  560. $token = $this->config->get('module_reverb_api_token');
  561. if (empty($token)) {
  562. throw new RuntimeException('Reverb API token is not configured.');
  563. }
  564. require_once(DIR_SYSTEM . 'library/reverb/ReverbApi.php');
  565. return new ReverbApi($token);
  566. }
  567. }