reverb.php 30 KB

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