db = $db; } private function rows($sql, $args = []) { $s = $this->db->prepare($sql); if (!$s || !$s->execute($args)) throw new RuntimeException('Shop database operation failed.'); return $s->fetchAll(PDO::FETCH_ASSOC); } private function write($sql, $args) { $s = $this->db->prepare($sql); if (!$s || !$s->execute($args)) throw new RuntimeException('Shop database operation failed.'); return $s->rowCount(); } public static function physicalOrderSQL($alias = 'o') { // Alias is code-owned, never request input. Deleted products remain visible for review. if ($alias !== 'o') throw new InvalidArgumentException('Invalid order alias'); return "NOT EXISTS (SELECT 1 FROM wp_wc_orders_meta rm WHERE rm.order_id=o.id AND rm.meta_key IN ('_subscription_renewal','_subscription_resubscribe','_subscription_switch')) AND EXISTS (SELECT 1 FROM wp_woocommerce_order_items pi JOIN wp_woocommerce_order_itemmeta pm ON pm.order_item_id=pi.order_item_id AND pm.meta_key='_product_id' WHERE pi.order_id=o.id AND pi.order_item_type='line_item' AND NOT EXISTS (SELECT 1 FROM wp_postmeta vm WHERE vm.post_id=CAST(pm.meta_value AS UNSIGNED) AND vm.meta_key='_virtual' AND vm.meta_value='yes'))"; } public static function stockSQL() { return "SELECT d.SimHash, d.DeviceID FROM ClientDevices d WHERE d.ClientID=0 AND COALESCE(d.order_id,0)=0 AND NOT EXISTS (SELECT 1 FROM ClientDeviceTransaction t WHERE (t.DeviceID<>'' AND t.DeviceID=d.DeviceID) OR (t.ICCID<>'' AND t.ICCID=d.ICCID) OR (t.SimHash<>'' AND t.SimHash=d.SimHash)) ORDER BY d.SimHash"; } public function searchStock($term, $includeUnavailable = false) { $code = strtoupper(trim($term)); if (!preg_match('/^[A-Z0-9-]{2,9}$/D', $code)) return []; $raw = str_replace('-', '', $code); if (strlen($raw) < 2 || strlen($raw) > 8) return []; $prefix = strlen($raw) > 4 ? substr($raw, 0, 4) . '-' . substr($raw, 4) : $raw; // Only an exact-code warning lookup may include unavailable inventory. if ($includeUnavailable && strlen($raw) !== 8) return []; $availability = $includeUnavailable ? '' : " HAVING unavailable_reason=''"; return $this->rows("SELECT d.SimHash, CASE WHEN COALESCE(d.order_id,0)>0 THEN CONCAT('Already assigned - order #',d.order_id) WHEN COALESCE(d.ClientID,0)<>0 THEN 'Already assigned to a customer' WHEN EXISTS (SELECT 1 FROM ClientDeviceTransaction t WHERE (t.DeviceID<>'' AND t.DeviceID=d.DeviceID) OR (t.ICCID<>'' AND t.ICCID=d.ICCID) OR (t.SimHash<>'' AND t.SimHash=d.SimHash)) THEN 'Already linked to a transaction' WHEN EXISTS (SELECT 1 FROM ClientDevices other WHERE other.SimHash=d.SimHash AND other.ClientDevicesID<>d.ClientDevicesID) THEN 'Duplicate code - review required' WHEN COALESCE(d.DeviceID,'')='' OR COALESCE(d.ICCID,'')='' OR d.SimHash NOT REGEXP '^[A-Z0-9]{4}-[A-Z0-9]{4}$' THEN 'Incomplete inventory - review required' ELSE '' END AS unavailable_reason FROM ClientDevices d WHERE d.SimHash LIKE ?" . $availability . " ORDER BY d.SimHash,d.ClientDevicesID LIMIT 20", [$prefix . '%']); } public function deviceAssignmentDetails($code) { if (!preg_match('/^[A-Z0-9]{4}-[A-Z0-9]{4}$/D', $code)) return null; $devices = $this->rows('SELECT ClientDevicesID,SimHash,DeviceID,ClientID,order_id FROM ClientDevices WHERE SimHash=? ORDER BY ClientDevicesID LIMIT 2', [$code]); if (count($devices) !== 1) return null; $device = $devices[0]; $device['transactions'] = $this->rows("SELECT t.ClientDeviceTransactionID,t.ClientID,t.OrderID, t.TransactionType,t.IsActive,t.SubscriptionStatus,t.StartDateTime,t.EndDateTime, o.type AS order_type,o.parent_order_id FROM ClientDeviceTransaction t LEFT JOIN wp_wc_orders o ON o.id=t.OrderID WHERE (t.SimHash<>'' AND t.SimHash=?) OR (t.DeviceID<>'' AND t.DeviceID=?) OR (t.ICCID<>'' AND t.ICCID=(SELECT ICCID FROM ClientDevices WHERE ClientDevicesID=?)) ORDER BY t.ClientDeviceTransactionID DESC LIMIT 20", [$code,$device['DeviceID'],$device['ClientDevicesID']]); $clientIDs = array_values(array_unique(array_filter(array_merge( [(int)$device['ClientID']], array_map('intval', array_column($device['transactions'], 'ClientID')) )))); $device['customers'] = []; if ($clientIDs) { $placeholders = implode(',', array_fill(0, count($clientIDs), '?')); $device['customers'] = $this->rows("SELECT c.ClientID,a.FirstName,a.LastName, COALESCE(NULLIF(l.Email,''),c.UserName) AS Email,l.Telephone, l.Address1,l.Address2,l.City,l.State,l.ZipCode,l.CountryCode FROM Client c LEFT JOIN ClientAccounts a ON a.ClientID=c.ClientID LEFT JOIN ClientLocation l ON l.ClientLocationID=a.ClientLocationID AND l.ClientID=c.ClientID AND l.RecordStatus=0 WHERE c.ClientID IN ($placeholders) ORDER BY c.ClientID", $clientIDs); foreach ($device['customers'] as &$customer) { // Historical purchases may predate contact details in the customer profile. foreach ($device['transactions'] as $transaction) { if ((int)$transaction['ClientID'] !== (int)$customer['ClientID']) continue; $orderID = (int)$transaction['parent_order_id'] ?: (int)$transaction['OrderID']; $billing = $this->rows("SELECT phone,address_1,address_2,city,state,postcode,country FROM wp_wc_order_addresses WHERE order_id=? AND address_type='billing' LIMIT 1", [$orderID]); if ($billing) { $b = $billing[0]; if (empty($customer['Telephone']) && !empty($b['phone'])) { $customer['Telephone'] = $b['phone']; $customer['phone_order_id'] = $orderID; } if (empty($customer['Address1']) && !empty($b['address_1'])) { foreach (['Address1'=>'address_1','Address2'=>'address_2','City'=>'city','State'=>'state','ZipCode'=>'postcode','CountryCode'=>'country'] as $key=>$column) $customer[$key] = $b[$column]; $customer['address_order_id'] = $orderID; } } break; } if (!filter_var($customer['Email'], FILTER_VALIDATE_EMAIL)) $customer['Email'] = null; } unset($customer); } return $device; } public static function pendingUnitsSQL() { return "SELECT COALESCE(SUM(GREATEST(CAST(q.meta_value AS UNSIGNED)- (SELECT COUNT(*) FROM ClientDeviceTransaction t WHERE t.ProductID=CAST(p.meta_value AS UNSIGNED) AND COALESCE(t.DeviceID,'')<>'' AND COALESCE(t.ICCID,'')<>'' AND COALESCE(t.SimHash,'')<>'' AND ((t.TransactionType='purchase' AND t.OrderID=o.id AND t.OrderItemID=i.order_item_id) OR (t.TransactionType='subscription' AND t.OrderID IN (SELECT id FROM wp_wc_orders WHERE type='shop_subscription' AND parent_order_id=o.id) AND (COALESCE(u.meta_value,'')='' OR EXISTS(SELECT 1 FROM wp_woocommerce_order_itemmeta um WHERE um.order_item_id=t.OrderItemID AND um.meta_key='_pa_unit_key' AND um.meta_value=u.meta_value))))),0)),0) AS v FROM wp_wc_orders o JOIN wp_woocommerce_order_items i ON i.order_id=o.id AND i.order_item_type='line_item' JOIN wp_woocommerce_order_itemmeta q ON q.order_item_id=i.order_item_id AND q.meta_key='_qty' JOIN wp_woocommerce_order_itemmeta p ON p.order_item_id=i.order_item_id AND p.meta_key='_product_id' LEFT JOIN wp_woocommerce_order_itemmeta u ON u.order_item_id=i.order_item_id AND u.meta_key='_pa_unit_key' WHERE o.type='shop_order' AND o.status='wc-processing' AND ".self::physicalOrderSQL()." AND NOT EXISTS(SELECT 1 FROM wp_postmeta v WHERE v.post_id=CAST(p.meta_value AS UNSIGNED) AND v.meta_key='_virtual' AND v.meta_value='yes')"; } public function inspect($orderID) { $orders = $this->rows('SELECT id,status FROM wp_wc_orders o WHERE id=? AND type=\'shop_order\' AND ' . self::physicalOrderSQL(), [$orderID]); if (!$orders) return ['physical' => false, 'units' => [], 'expected' => 0, 'assigned' => 0, 'issues' => [], 'ready' => false]; $issues = []; $items = $this->rows("SELECT i.order_item_id,i.order_item_name, MAX(CASE WHEN m.meta_key='_product_id' THEN m.meta_value END) product_id, MAX(CASE WHEN m.meta_key='_variation_id' THEN m.meta_value END) variation_id, MAX(CASE WHEN m.meta_key='_pa_unit_key' THEN m.meta_value END) unit_key, MAX(CASE WHEN m.meta_key='_line_total' THEN m.meta_value END) line_total, MAX(CASE WHEN m.meta_key='_line_tax' THEN m.meta_value END) line_tax, MAX(CASE WHEN m.meta_key='_qty' THEN m.meta_value END) quantity FROM wp_woocommerce_order_items i JOIN wp_woocommerce_order_itemmeta m ON m.order_item_id=i.order_item_id WHERE i.order_id=? AND i.order_item_type='line_item' GROUP BY i.order_item_id,i.order_item_name", [$orderID]); $units = []; $expected = 0; $assigned = 0; $products = []; $clientIDs = []; $unitKeys = []; $transactionIDs = []; foreach ($items as $item) { $pid = intval($item['product_id']); $meta = $this->rows("SELECT meta_key,meta_value FROM wp_postmeta WHERE post_id=? AND meta_key IN ('_virtual','_pa_shop_plan_key')", [$pid]); $values = array_column($meta, 'meta_value', 'meta_key'); if (($values['_virtual'] ?? '') === 'yes') continue; $qty = intval($item['quantity']); if ($qty < 1 || (float)$item['quantity'] !== (float)$qty) { $issues[] = 'Invalid hardware quantity on item ' . $item['order_item_id']; continue; } $expected += $qty; $unitKey = $item['unit_key'] ?? ''; if ($unitKey !== '' && (!preg_match('/^[a-f0-9]{32}$/D', $unitKey) || $qty !== 1 || isset($unitKeys[$unitKey]))) { $issues[] = 'Invalid or duplicate tracker unit identity for item ' . $item['order_item_id']; continue; } if ($unitKey !== '') $unitKeys[$unitKey] = true; if (intval($item['variation_id']) > 0 || ($unitKey === '' && isset($products[$pid]))) { $issues[] = 'Ambiguous product/unit mapping for item ' . $item['order_item_id']; continue; } $products[$pid] = true; // Known legacy tracker products, or explicitly classified new tracker offers. if (!in_array($pid, [636,717], true) && !in_array($values['_pa_shop_plan_key'] ?? '', ['tracker-only','tracker-monthly','tracker-annual'], true)) { $issues[] = 'Hardware classification needs review for item ' . $item['order_item_id']; continue; } $matches = $this->rows("SELECT t.* FROM ClientDeviceTransaction t WHERE t.ProductID=? AND ( (t.TransactionType='purchase' AND t.OrderID=? AND t.OrderItemID=?) OR (t.TransactionType='subscription' AND t.OrderID IN (SELECT id FROM wp_wc_orders WHERE type='shop_subscription' AND parent_order_id=?) AND (?='' OR EXISTS (SELECT 1 FROM wp_woocommerce_order_itemmeta um WHERE um.order_item_id=t.OrderItemID AND um.meta_key='_pa_unit_key' AND um.meta_value=?)))) ORDER BY t.ClientDeviceTransactionID", [$pid,$orderID,$item['order_item_id'],$orderID,$unitKey,$unitKey]); if (count($matches) !== $qty) $issues[] = 'Backend units do not match purchased quantity for item ' . $item['order_item_id']; foreach ($matches as $tx) { if (isset($transactionIDs[$tx['ClientDeviceTransactionID']])) { $issues[] = 'Backend transaction is mapped to more than one order unit.'; continue; } $transactionIDs[$tx['ClientDeviceTransactionID']] = true; $linked = !empty($tx['DeviceID']) || !empty($tx['SimHash']) || !empty($tx['ICCID']); if ($linked && (empty($tx['DeviceID']) || empty($tx['SimHash']) || empty($tx['ICCID']))) $issues[] = 'Incomplete device link on transaction ' . $tx['ClientDeviceTransactionID']; $clientIDs[intval($tx['ClientID'])] = true; if ($linked) $assigned++; $units[] = ['transaction_id' => intval($tx['ClientDeviceTransactionID']), 'item_id' => intval($item['order_item_id']), 'subscription_id' => $tx['TransactionType'] === 'subscription' ? intval($tx['OrderID']) : null, 'unit_total' => number_format(((float)$item['line_total'] + (float)$item['line_tax']) / $qty, 2, '.', ''), 'product' => $item['order_item_name'], 'assigned' => $linked, 'simhash' => $tx['SimHash'], 'client_id' => intval($tx['ClientID'])]; } } if (count($clientIDs) !== 1 || isset($clientIDs[0])) $issues[] = 'Customer transaction mapping needs review.'; if ($this->rows("SELECT id FROM wp_wc_orders WHERE parent_order_id=? AND type='shop_order_refund' LIMIT 1", [$orderID])) $issues[] = 'Refunded order requires fulfillment review.'; return ['physical' => true, 'units' => $units, 'expected' => $expected, 'assigned' => $assigned, 'issues' => array_values(array_unique($issues)), 'ready' => !$issues && $expected > 0 && $assigned === $expected]; } public function assign($orderID, $transactionID, $simHash) { if ($orderID < 1 || $transactionID < 1 || !preg_match('/^[A-Z0-9]{4}-[A-Z0-9]{4}$/D', $simHash)) throw new RuntimeException('Select a valid order unit and device code.'); $this->db->beginTransaction(); try { $orders = $this->rows("SELECT id,status FROM wp_wc_orders WHERE id=? AND type='shop_order' FOR UPDATE", [$orderID]); if (!$orders || !in_array($orders[0]['status'], ['wc-processing','wc-completed'], true)) throw new RuntimeException('Order is not eligible for shipping.'); $state = $this->inspect($orderID); if (!$state['physical'] || $state['issues']) throw new RuntimeException($state['issues'] ? implode(' ', $state['issues']) : 'This order has no tracker shipment.'); $selected = array_values(array_filter($state['units'], function($u) use ($transactionID) { return $u['transaction_id'] === $transactionID; })); if (count($selected) !== 1) throw new RuntimeException('Selected unit does not belong to this order.'); $unit = $selected[0]; if ($unit['assigned']) { if ($unit['simhash'] !== $simHash) throw new RuntimeException('This unit already has another device. Refresh the order.'); $this->db->commit(); return $state + ['replayed' => true]; } if ($orders[0]['status'] !== 'wc-processing') throw new RuntimeException('Completed order requires review before another assignment.'); $devices = $this->rows('SELECT ClientDevicesID,ClientID,DeviceID,ICCID,SimHash,order_id FROM ClientDevices WHERE SimHash=? FOR UPDATE', [$simHash]); if (count($devices) !== 1 || intval($devices[0]['ClientID']) !== 0 || intval($devices[0]['order_id']) !== 0) throw new RuntimeException('Device is unavailable or reserved.'); $device = $devices[0]; if (empty($device['DeviceID']) || empty($device['ICCID'])) throw new RuntimeException('Device inventory identifiers are incomplete.'); if ($this->rows("SELECT ClientDeviceTransactionID FROM ClientDeviceTransaction WHERE DeviceID=? OR ICCID=? OR SimHash=? LIMIT 1", [$device['DeviceID'],$device['ICCID'],$simHash])) throw new RuntimeException('Device is already linked to another transaction.'); $changed = $this->write("UPDATE ClientDeviceTransaction SET DeviceID=?,ICCID=?,SimHash=?,IsActive=1,UpdateDateTime=NOW() WHERE ClientDeviceTransactionID=? AND (DeviceID IS NULL OR DeviceID='') AND ICCID='' AND SimHash=''", [$device['DeviceID'],$device['ICCID'],$simHash,$transactionID]); if ($changed !== 1) throw new RuntimeException('Unit changed during assignment; refresh and retry.'); if ($this->write('UPDATE ClientDevices SET order_id=?,UpdateDateTime=NOW() WHERE ClientDevicesID=? AND ClientID=0 AND order_id=0', [$orderID,$device['ClientDevicesID']]) !== 1) throw new RuntimeException('Could not reserve device.'); $this->write("INSERT INTO ClientDeviceTransactionHistory (ClientDeviceTransactionID,ClientID,ProductID,DeviceID,ICCID,SimHash,EventType,OrderID,OrderItemID,TransactionDate,StartDateTime,EndDateTime,SubscriptionStatus) SELECT ClientDeviceTransactionID,ClientID,ProductID,DeviceID,ICCID,SimHash,'device_shipped',OrderID,OrderItemID,NOW(),StartDateTime,EndDateTime,SubscriptionStatus FROM ClientDeviceTransaction WHERE ClientDeviceTransactionID=?", [$transactionID]); $state = $this->inspect($orderID); $this->db->commit(); return $state + ['replayed' => false]; } catch (Throwable $e) { if ($this->db->inTransaction()) $this->db->rollBack(); throw $e; } } }