CAST(qty.meta_value AS UNSIGNED)"; } function PAShopActivationPendingSQL() { return "SELECT q.* FROM ( SELECT a.ClientDeviceTransactionID AS transaction_id, a.ClientID AS client_id, a.SubscriptionID AS subscription_id, d.ClientDevicesID AS device_id, d.NameTag AS tracker_name, a.Stage AS stage, a.LastErrorCode AS error_code, a.ServiceStartUTC AS service_start_utc, a.ServiceEndUTC AS service_end_utc, a.UpdateDateTimeUTC AS updated_utc, a.TermsJSON AS terms_json, (SELECT h.EventType FROM PA_ShopActivationHistory h WHERE h.ClientDeviceTransactionID=a.ClientDeviceTransactionID AND h.Revision=a.Revision ORDER BY h.ActivationHistoryID DESC LIMIT 1) AS last_event FROM PA_ShopActivation a LEFT JOIN ClientDevices d ON d.DeviceID=a.DeviceID ) q WHERE q.stage <> 'completed' OR q.error_code IS NOT NULL OR COALESCE(q.last_event,'') <> 'billing_released'"; } function PAShopActivationHealth(PDO $db) { try { $sql=PAShopActivationPendingSQL(); $s=$db->query('SELECT COUNT(*) AS pending_count, COALESCE(SUM(error_code IS NOT NULL),0) AS error_count FROM ('.$sql.') pending'); if(!$s)throw new RuntimeException('Activation count unavailable'); $counts=$s->fetch(PDO::FETCH_ASSOC); $s=$db->query($sql.' ORDER BY (q.error_code IS NOT NULL) DESC, q.updated_utc, q.transaction_id LIMIT 100'); if(!$s)throw new RuntimeException('Activation list unavailable'); $rows=$s->fetchAll(PDO::FETCH_ASSOC); foreach($rows as &$row){ $row['recovery']=PAShopActivationRecoveryGuidance($row); unset($row['terms_json']); } unset($row); return ['available'=>true,'pending_count'=>(int)$counts['pending_count'], 'error_count'=>(int)$counts['error_count'],'rows'=>$rows,'limit'=>100]; } catch(Throwable $e) { return ['available'=>false,'pending_count'=>null,'error_count'=>null,'rows'=>[],'limit'=>100]; } } /** Read-only exceptions for payments that changed after service was extended. */ function PAShopRenewalPaymentExceptionsSQL() { return "SELECT r.SubscriptionID AS subscription_id, r.ClientDeviceTransactionID AS transaction_id, r.RenewalOrderID AS renewal_order_id, 'review_required' AS state, CASE WHEN o.id IS NULL THEN 'renewal_order_missing' WHEN o.type <> 'shop_order' THEN 'renewal_order_type_changed' WHEN o.status NOT IN ('wc-processing','wc-completed') THEN 'renewal_payment_status_changed' ELSE 'renewal_refunded' END AS error_code, COALESCE(o.date_updated_gmt,r.InsertDateTimeUTC) AS updated_utc FROM PA_ShopRenewal r LEFT JOIN wp_wc_orders o ON o.id=r.RenewalOrderID WHERE r.State='succeeded' AND (o.id IS NULL OR o.type <> 'shop_order' OR o.status NOT IN ('wc-processing','wc-completed') OR EXISTS (SELECT 1 FROM wp_wc_orders f WHERE f.parent_order_id=r.RenewalOrderID AND f.type='shop_order_refund'))"; } /** Read-only queue for interrupted billing, shutdowns, and renewal payments. */ function PAShopServiceActionHealth(PDO $db) { try { $billingWhere="State IN ('started','review_required')"; $terminationWhere="State IN ('prepared','carrier_confirmed')"; $billingCounts=$db->query('SELECT COUNT(*) AS total, COALESCE(SUM(LastErrorCode IS NOT NULL),0) AS errors FROM PA_ShopBillingControl WHERE '.$billingWhere)->fetch(PDO::FETCH_ASSOC); $terminationCounts=$db->query('SELECT COUNT(*) AS total, COALESCE(SUM(LastErrorCode IS NOT NULL),0) AS errors FROM PA_ShopTermination WHERE '.$terminationWhere)->fetch(PDO::FETCH_ASSOC); $paymentSQL=PAShopRenewalPaymentExceptionsSQL(); $paymentCount=$db->query('SELECT COUNT(*) FROM ('.$paymentSQL.') payment_exceptions')->fetchColumn(); if(!$billingCounts||!$terminationCounts||$paymentCount===false)throw new RuntimeException('Service action counts unavailable.'); $billing=$db->query('SELECT SubscriptionID AS subscription_id, ClientDeviceTransactionID AS transaction_id, Action AS action, ServiceMode AS service_mode, State AS state, LastErrorCode AS error_code, UpdateDateTimeUTC AS updated_utc FROM PA_ShopBillingControl WHERE '.$billingWhere.' ORDER BY UpdateDateTimeUTC DESC, RequestID DESC LIMIT 50')->fetchAll(PDO::FETCH_ASSOC); $termination=$db->query('SELECT SubscriptionID AS subscription_id, ClientDeviceTransactionID AS transaction_id, TerminalStatus AS action, State AS state, LastErrorCode AS error_code, UpdateDateTimeUTC AS updated_utc FROM PA_ShopTermination WHERE '.$terminationWhere.' ORDER BY UpdateDateTimeUTC DESC, ClientDeviceTransactionID DESC LIMIT 50')->fetchAll(PDO::FETCH_ASSOC); $payments=$db->query($paymentSQL.' ORDER BY updated_utc DESC, renewal_order_id DESC LIMIT 50')->fetchAll(PDO::FETCH_ASSOC); if(!is_array($billing)||!is_array($termination)||!is_array($payments))throw new RuntimeException('Service action list unavailable.'); foreach($billing as &$row)$row['kind']='billing'; unset($row); foreach($termination as &$row)$row['kind']='service_shutdown'; unset($row); foreach($payments as &$row)$row['kind']='renewal_payment'; unset($row); $rows=array_merge($billing,$termination,$payments); usort($rows,function($a,$b){return strcmp($b['updated_utc'],$a['updated_utc']);}); return ['available'=>true,'pending_count'=>(int)$billingCounts['total']+(int)$terminationCounts['total']+(int)$paymentCount, 'error_count'=>(int)$billingCounts['errors']+(int)$terminationCounts['errors']+(int)$paymentCount, 'billing_count'=>(int)$billingCounts['total'],'shutdown_count'=>(int)$terminationCounts['total'], 'renewal_payment_count'=>(int)$paymentCount, 'rows'=>array_slice($rows,0,50),'limit'=>50]; } catch(Throwable $e) { return ['available'=>false,'pending_count'=>null,'error_count'=>null, 'billing_count'=>null,'shutdown_count'=>null,'renewal_payment_count'=>null,'rows'=>[],'limit'=>50]; } } /** Guidance only: journal data cannot authorize a billing or carrier mutation. */ function PAShopActivationRecoveryGuidance(array $row,$now=null) { $now=$now??gmdate('Y-m-d H:i:s'); $stage=$row['stage']??'';$error=$row['error_code']??null; $review=['code'=>'manual_review','title'=>'Manual review', 'detail'=>'Verify payment, tracker ownership and saved service dates before any retry. Do not create another purchase or reset dates.']; $serviceOnly=false; if(array_key_exists('terms_json',$row)){ $terms=is_string($row['terms_json'])?json_decode($row['terms_json'],true):null; if(!is_array($terms)||!isset($terms['service_included'],$terms['hardware_required']) ||!is_bool($terms['service_included'])||!is_bool($terms['hardware_required']))return $review; $serviceOnly=$terms['service_included']===true && $terms['hardware_required']===false; } if(!in_array($stage,['prepared','carrier_confirmed','billing_scheduled','completed'],true))return $review; if($stage==='prepared' && (($row['service_start_utc']??null)!==null || ($row['service_end_utc']??null)!==null))return $review; if($stage==='completed' && $error===null && ($row['last_event']??'')==='billing_released'){ return ['code'=>'confirmed','title'=>'Activation confirmed','detail'=>'No activation recovery is needed.']; } if($stage!=='prepared'){ $start=$row['service_start_utc']??null;$end=$row['service_end_utc']??null; foreach([$start,$end] as $value){ if(!is_string($value))return $review; $date=DateTimeImmutable::createFromFormat('!Y-m-d H:i:s',$value,new DateTimeZone('UTC')); if(!$date||$date->format('Y-m-d H:i:s')!==$value)return $review; } if($start>=$end || $start>$now)return $review; if($end<=$now)return ['code'=>'expired_window','title'=>'Service period needs review', 'detail'=>'The saved service period has ended. Review service and billing before retrying; do not automatically move the original dates.']; } $expected=['prepared'=>'carrier_unconfirmed','carrier_confirmed'=>'billing_unconfirmed', 'billing_scheduled'=>'backend_commit_failed','completed'=>'billing_release_unconfirmed']; if($error!==null && $error!==$expected[$stage])return $review; if($stage==='completed')return ['code'=>'billing_confirmation','title'=>'Verify billing release', 'detail'=>'Backend activation is saved. Verify the paid subscription and saved renewal date before retrying billing confirmation. Do not repeat SIM activation or contact creation.']; if($serviceOnly)return ['code'=>'shop_retry','title'=>'Shop service retry', 'detail'=>'Review the paid order, selected tracker and reservation, then use the WordPress service retry after resolving the recorded issue. Do not repeat mobile registration, replace contacts or buy service again. Confirmed stages and original dates are retained.']; return ['code'=>'customer_retry','title'=>'Customer registration retry', 'detail'=>'After resolving the recorded issue, retry the original registration with the customer contact details and explicit SMS consent. Confirmed stages and original dates are retained; do not buy service again.']; } function PAShopActivationHistory(PDO $db,$id) { if(!is_string($id)||!preg_match('/^[1-9][0-9]{0,17}$/D',$id))throw new InvalidArgumentException('Invalid activation reference.'); $s=$db->prepare('SELECT a.Stage AS stage,a.LastErrorCode AS error_code,a.TermsJSON AS terms_json, a.ServiceStartUTC AS service_start_utc,a.ServiceEndUTC AS service_end_utc, (SELECT h.EventType FROM PA_ShopActivationHistory h WHERE h.ClientDeviceTransactionID=a.ClientDeviceTransactionID AND h.Revision=a.Revision ORDER BY h.ActivationHistoryID DESC LIMIT 1) AS last_event FROM PA_ShopActivation a WHERE a.ClientDeviceTransactionID=?'); if(!$s||!$s->execute([$id]))throw new RuntimeException('Activation history unavailable.'); $current=$s->fetch(PDO::FETCH_ASSOC); if(!$current)throw new RuntimeException('Activation record not found.'); $s=$db->prepare('SELECT EventType AS event_type, ToStage AS stage, ErrorCode AS error_code, InsertDateTimeUTC AS occurred_utc, Revision AS revision FROM PA_ShopActivationHistory WHERE ClientDeviceTransactionID=? ORDER BY ActivationHistoryID DESC LIMIT 50'); if(!$s||!$s->execute([$id]))throw new RuntimeException('Activation history unavailable.'); $rows=$s->fetchAll(PDO::FETCH_ASSOC); $s=$db->prepare('SELECT AdminID AS admin_id,Reason AS reason,Status AS status,ErrorCode AS error_code, InsertDateTimeUTC AS started_utc,UpdateDateTimeUTC AS updated_utc FROM PA_ShopActivationRecovery WHERE ClientDeviceTransactionID=? ORDER BY InsertDateTimeUTC DESC,RequestID DESC LIMIT 20'); if(!$s||!$s->execute([$id]))throw new RuntimeException('Recovery audit unavailable.'); return ['transaction_id'=>$id,'recovery'=>PAShopActivationRecoveryGuidance($current), 'rows'=>$rows,'recovery_attempts'=>$s->fetchAll(PDO::FETCH_ASSOC),'limit'=>50]; }