db=$db;$this->load=$load;$this->timezone=$timezone;$this->config=$config; $this->model=new PAShopCustomerDevices($db,$load,$timezone); } private function query($sql,$args=[]){$s=$this->db->prepare($sql);$s->execute($args);return $s;} private function allowed(int $admin,?int $client=null): array {return PAShopAdminGate::resolve($this->db,$this->config,'DEVICE_SUBSCRIPTIONS',$admin,$client);} private function readable(int $admin,int $client): void { $gate=$this->allowed($admin); if($client<1||(($gate['AllowAllClients']??false)!==true&&!in_array($client,$gate['AllowedClientIDs']??[],true)))throw new RuntimeException('Customer is outside the permitted scope.'); if((int)$this->query('SELECT COUNT(*) FROM Client WHERE ClientID=? AND RecordStatus IN (0,1)',[$client])->fetchColumn()!==1)throw new RuntimeException('Customer identity needs verification.'); } private function identity(int $admin,int $id): array { $this->allowed($admin); $rows=$this->query('SELECT d.*,c.UserName AS customer_email FROM ClientDevices d JOIN Client c ON c.ClientID=d.ClientID WHERE d.ClientDevicesID=? AND d.RecordStatus=0 AND c.RecordStatus IN (0,1) AND d.ClientID>0',[$id])->fetchAll(PDO::FETCH_ASSOC); if(count($rows)!==1)throw new RuntimeException('Device or customer is unavailable.');$d=$rows[0];$this->readable($admin,(int)$d['ClientID']); $users=$this->query('SELECT ID FROM wp_users WHERE user_email=?',[$d['customer_email']])->fetchAll(PDO::FETCH_COLUMN); $d['shop_user_id']=count($users)===1?(int)$users[0]:null;return $d; } private function local($date): ?string { $d=is_string($date)?DateTimeImmutable::createFromFormat('!Y-m-d H:i:s',$date,$this->timezone):false; return $d&&$d->format('Y-m-d H:i:s')===$date?$d->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s'):null; } private function row(int $admin,array $d): array { $id=(int)$d['ClientDevicesID'];$buyer=$d['shop_user_id']; $m=['review'=>true,'reviewReason'=>'Shop customer link needs verification.','subscription'=>null,'subscriptionID'=>null,'canCancel'=>false,'autoRenew'=>false,'status'=>'','paidThroughUTC'=>$this->local($d['EndDateTime'])]; if($buyer){try{$m=$this->model->device($buyer,$id);}catch(Throwable $e){$m['reviewReason']='Device and subscription identities need verification.';}} try{if((int)$this->query("SELECT COUNT(*) FROM PA_ShopAdminSubscriptionAction WHERE ClientDevicesID=? AND State IN ('started','review_required')",[$id])->fetchColumn()>0){$m['review']=true;$m['reviewReason']='An earlier Admin cancellation needs verification.';}} catch(Throwable $e){$m['review']=true;$m['reviewReason']='Admin action audit is unavailable.';} $sub=$m['subscription']; if(!$sub){ $ids=$this->query("SELECT DISTINCT OrderID FROM ClientDeviceTransaction WHERE ClientID=? AND TransactionType='subscription' AND (DeviceID=? OR ICCID=? OR SimHash=?)",[$d['ClientID'],$d['DeviceID'],$d['ICCID'],$d['SimHash']])->fetchAll(PDO::FETCH_COLUMN); if(count($ids)===1&&$buyer){$candidate=call_user_func($this->load,(int)$ids[0]);if($candidate&&(int)$candidate->get_customer_id()===$buyer)$sub=$candidate;} } $alerts=(int)$this->query("SELECT COUNT(*) FROM PART_Dash WHERE ClientDevicesID=? AND Status='Active' AND RecordStatus=0",[$id])->fetchColumn(); $carrier='Unknown';try{$carrier=PACommonCarrier_Detect((string)$d['ICCID'],$this->config['CARRIER']??[]);}catch(Throwable $e){} $status=$sub?$sub->get_status():'unlinked';$names=['active'=>'Active','on-hold'=>'On hold','pending'=>'Awaiting payment','pending-cancel'=>'Renewal stopped','cancelled'=>'Canceled','expired'=>'Expired','unlinked'=>'No linked subscription']; $items=$sub?$sub->get_items():[];$item=$items?reset($items):null; $cancel=$m['canCancel']&&!$m['review']&&$alerts===0; return ['device_id'=>$id,'device_key'=>$d['DeviceID'],'device_code'=>$d['SimHash'],'device_name'=>trim((string)$d['NameTag'])?:'Device', 'client_id'=>(int)$d['ClientID'],'customer_email'=>$d['customer_email'],'subscription_id'=>$sub?(int)$sub->get_id():null, 'plan'=>$item&&method_exists($item,'get_name')?$item->get_name():'Not linked','currency'=>$sub?$sub->get_currency():null,'amount'=>$sub?(string)$sub->get_total():null, 'billing_period'=>$sub?$sub->get_billing_period():null,'billing_interval'=>$sub?(int)$sub->get_billing_interval():null, 'billing_status'=>$status,'billing_label'=>$names[$status]??'Needs review','renewal_mode'=>$sub?($status==='pending-cancel'?'Stopped':($sub->is_manual()?'Manual':'Automatic')):'Not set', 'next_payment_utc'=>$sub?$sub->get_date('next_payment','gmt'):null,'paid_through_utc'=>$m['paidThroughUTC'], 'scheduled_end_utc'=>$sub?$sub->get_date('end','gmt'):null,'cancel_end_utc'=>$m['cancelEndUTC']??null, 'service_enabled'=>(int)$d['Enabled']===1,'paid_period_ended'=>$m['paidThroughUTC']&&$m['paidThroughUTC']<=gmdate('Y-m-d H:i:s'), 'carrier'=>$carrier,'review'=>$m['review'],'review_reason'=>$m['reviewReason']??null,'open_alerts'=>$alerts, 'can_cancel'=>$cancel,'shop_user_id'=>$buyer,'_model'=>$m,'_sub'=>$sub,'_device'=>$d]; } private function publicRow(array $row): array {unset($row['_model'],$row['_sub'],$row['_device'],$row['shop_user_id']);return $row;} public function customers(int $admin,string $search='',string $filter='all',int $offset=0,int $limit=20,string $sort='customer',string $direction='asc'): array { $gate=$this->allowed($admin); $sorts=['customer'=>"COALESCE(NULLIF(a.customer_name,''),c.UserName)",'devices'=>'device_count','purchases'=>'purchase_count','subscriptions'=>'subscription_count','service'=>'active_service_count']; if(!in_array($limit,[15,20,25,50,100],true)||!isset($sorts[$sort])||!in_array($direction,['asc','desc'],true))throw new RuntimeException('Invalid table ordering or page size.'); if(strlen($search)>100||preg_match('/[\x00-\x1f\x7f]/',$search)||!in_array($filter,['all','with_activity','with_devices','without_devices','ending30','ending14','ending7','expired_enabled','exceptions'],true)||$offset<0||$offset>1000000)throw new RuntimeException('Invalid search, filter or page.'); $where='c.RecordStatus IN (0,1)';$args=[]; if(($gate['AllowAllClients']??false)!==true){ $ids=array_values(array_filter($gate['AllowedClientIDs']??[],fn($v)=>is_int($v)&&$v>0)); if(!$ids)return ['rows'=>[],'total'=>0,'offset'=>$offset,'next_offset'=>null]; $where.=' AND c.ClientID IN ('.implode(',',array_fill(0,count($ids),'?')).')';$args=$ids; } $owned="SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND COALESCE(t.DeviceID,'')<>''"; if(in_array($filter,['with_devices','without_devices'],true))$where.=' AND '.($filter==='without_devices'?'NOT ':'').'EXISTS('.$owned.')'; if($filter==='with_activity')$where.=" AND EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID)"; if(in_array($filter,['ending30','ending14','ending7'],true)){ $days=(int)substr($filter,6);$where.=' AND EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.EndDateTime>NOW() AND t.EndDateTime<=DATE_ADD(NOW(),INTERVAL '.$days.' DAY))'; } if($filter==='expired_enabled')$where.=" AND EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.EndDateTime<=NOW() AND t.EndDateTime>'2000-01-01' AND (t.IsActive=1 OR EXISTS(SELECT 1 FROM ClientDevices x WHERE x.DeviceID=t.DeviceID AND x.ClientID=t.ClientID AND x.Enabled=1)))"; if($filter==='exceptions')$where.=" AND EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND ( COALESCE(t.DeviceID,'')='' OR COALESCE(t.ICCID,'')='' OR COALESCE(t.SimHash,'')='' OR (SELECT COUNT(*) FROM ClientDevices x WHERE x.DeviceID=t.DeviceID OR x.ICCID=t.ICCID OR x.SimHash=t.SimHash)<>1 OR (t.IsActive=1 AND t.EndDateTime<=NOW()) OR EXISTS(SELECT 1 FROM ClientDeviceTransaction x WHERE x.ClientDeviceTransactionID<>t.ClientDeviceTransactionID AND x.DeviceID=t.DeviceID AND x.IsActive=1) OR EXISTS(SELECT 1 FROM PA_ShopRenewalAction x WHERE x.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND x.State IN ('started','review_required')) OR EXISTS(SELECT 1 FROM PA_ShopDeviceRenewalOrder x WHERE x.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND x.State IN ('creating','processing','review_required')) OR EXISTS(SELECT 1 FROM PA_ShopNotification x WHERE x.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND x.State IN ('failed','review_required')) OR EXISTS(SELECT 1 FROM wp_wc_orders o WHERE o.id=t.OrderID AND t.TransactionType='purchase' AND o.status IN ('wc-failed','wc-cancelled','wc-refunded','wc-pending')) OR EXISTS(SELECT 1 FROM wp_wc_orders o WHERE o.id=t.OrderID AND t.TransactionType='subscription' AND o.status='wc-on-hold' AND NOT EXISTS(SELECT 1 FROM PA_ShopRenewalPreference p WHERE p.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND p.Mode='pause')) OR EXISTS(SELECT 1 FROM wp_wc_orders o JOIN wp_wc_orders_meta m ON m.order_id=o.id AND m.meta_key='_subscription_renewal' WHERE t.TransactionType='subscription' AND m.meta_value=CAST(t.OrderID AS CHAR) AND o.status IN ('wc-failed','wc-pending')) OR EXISTS(SELECT 1 FROM PA_ShopTermination x WHERE x.SubscriptionID=t.OrderID AND t.TransactionType='subscription' AND x.State<>'completed') OR EXISTS(SELECT 1 FROM PA_ShopBillingControl x WHERE x.SubscriptionID=t.OrderID AND t.TransactionType='subscription' AND x.State IN ('started','review_required')) OR EXISTS(SELECT 1 FROM PA_ShopActivation x WHERE x.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND (x.Stage<>'completed' OR x.LastErrorCode IS NOT NULL)) OR EXISTS(SELECT 1 FROM PA_ShopRenewal x LEFT JOIN wp_wc_orders o ON o.id=x.RenewalOrderID WHERE x.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND (o.id IS NULL OR o.status NOT IN ('wc-processing','wc-completed') OR EXISTS(SELECT 1 FROM wp_wc_orders f WHERE f.parent_order_id=o.id AND f.type='shop_order_refund'))) ))"; $names="SELECT ClientID,MAX(CONCAT(COALESCE(FirstName,''),' ',COALESCE(LastName,''))) AS customer_name FROM ClientAccounts WHERE RecordStatus IN (0,1) GROUP BY ClientID"; if($search!==''){ $like='%'.strtr($search,['='=>'==','%'=>'=%','_'=>'=_']).'%'; $where.=" AND (c.UserName LIKE ? ESCAPE '=' OR a.customer_name LIKE ? ESCAPE '=' OR EXISTS(SELECT 1 FROM ClientDevices d WHERE d.ClientID=c.ClientID AND d.RecordStatus=0 AND (d.SimHash LIKE ? ESCAPE '=' OR d.NameTag LIKE ? ESCAPE '=' OR d.DeviceID LIKE ? ESCAPE '=')) OR EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND CAST(t.OrderID AS CHAR) LIKE ? ESCAPE '='))"; array_push($args,$like,$like,$like,$like,$like,$like); } $from=' FROM Client c LEFT JOIN ('.$names.') a ON a.ClientID=c.ClientID WHERE '.$where; $total=(int)$this->query('SELECT COUNT(*)'.$from,$args)->fetchColumn(); $rows=$this->query("SELECT c.ClientID AS client_id,c.UserName AS customer_email,c.RecordStatus AS customer_record_status,a.customer_name, (SELECT COUNT(DISTINCT t.DeviceID) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND COALESCE(t.DeviceID,'')<>'') AS device_count, (SELECT COUNT(DISTINCT t.DeviceID) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.IsActive=1 AND COALESCE(t.DeviceID,'')<>'') AS enabled_count, (SELECT COUNT(*) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.IsActive=1 AND t.StartDateTime<=NOW() AND t.EndDateTime>NOW()) AS active_service_count, (SELECT COUNT(DISTINCT t.OrderID) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.TransactionType='purchase') AS purchase_count, (SELECT COUNT(DISTINCT t.OrderID) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.TransactionType='subscription') AS subscription_count, (SELECT COUNT(DISTINCT t.OrderID) FROM ClientDeviceTransaction t WHERE t.ClientID=c.ClientID AND t.TransactionType='subscription' AND t.IsActive=1 AND t.SubscriptionStatus='active') AS active_subscription_count".$from.' ORDER BY '.$sorts[$sort].' '.$direction.',c.ClientID LIMIT '.$limit.' OFFSET '.$offset,$args)->fetchAll(PDO::FETCH_ASSOC); foreach($rows as &$r){foreach(['client_id','device_count','enabled_count','purchase_count','subscription_count','active_subscription_count','active_service_count','customer_record_status'] as $k)$r[$k]=(int)$r[$k];$r['customer_name']=trim((string)$r['customer_name']);}unset($r); return ['rows'=>$rows,'total'=>$total,'offset'=>$offset,'next_offset'=>$offset+$limit<$total?$offset+$limit:null]; } private function transactionRow(int $admin,array $t): array { $this->readable($admin,(int)$t['ClientID']); $email=$this->query('SELECT UserName FROM Client WHERE ClientID=?',[$t['ClientID']])->fetchColumn(); $matches=$t['DeviceID']&&$t['ICCID']&&$t['SimHash']?$this->query('SELECT ClientDevicesID FROM ClientDevices WHERE ClientID=? AND DeviceID=? AND ICCID=? AND SimHash=? AND RecordStatus=0',[$t['ClientID'],$t['DeviceID'],$t['ICCID'],$t['SimHash']])->fetchAll(PDO::FETCH_COLUMN):[]; $r=count($matches)===1?$this->publicRow($this->row($admin,$this->identity($admin,(int)$matches[0]))): ['device_id'=>null,'device_name'=>'Awaiting device assignment','device_code'=>$t['SimHash']?:'Not assigned','customer_email'=>$email,'client_id'=>(int)$t['ClientID'],'subscription_id'=>null,'plan'=>'Not assigned','amount'=>null,'currency'=>null,'billing_period'=>null,'billing_interval'=>null,'billing_status'=>'pending','billing_label'=>'Awaiting device assignment','renewal_mode'=>'Not configured','next_payment_utc'=>null,'service_enabled'=>false,'carrier'=>'Not assigned','open_alerts'=>0,'review'=>true,'review_reason'=>'Device assignment needs verification.','can_cancel'=>false]; $r+=['transaction_id'=>(int)$t['ClientDeviceTransactionID'],'transaction_type'=>$t['TransactionType'],'order_id'=>(int)$t['OrderID'],'order_item_id'=>(int)$t['OrderItemID'],'product_id'=>(int)$t['ProductID']]; $r['service_end_recorded']=$t['EndDateTime']; $r['paid_through_utc']=$this->local($t['EndDateTime']); $r['service_start_utc']=$this->local($t['StartDateTime']); $r['entitlement_active']=(int)$t['IsActive']===1&&$r['service_start_utc']&&$r['service_start_utc']<=gmdate('Y-m-d H:i:s')&&$r['paid_through_utc']&&$r['paid_through_utc']>gmdate('Y-m-d H:i:s'); if($t['TransactionType']==='purchase'){ $r['subscription_id']=null;$r['plan']='Device purchase';$r['billing_status']='purchase';$r['billing_label']='One-time purchase';$r['renewal_mode']='No automatic renewal';$r['next_payment_utc']=null;$r['amount']=null;$r['can_cancel']=false; }elseif((int)$r['subscription_id']!==(int)$t['OrderID']){$r['can_cancel']=false;$r['review']=true;$r['review_reason']='Subscription and current transaction must match.';} if(class_exists('PAShopRenewalControl')){ $control=new PAShopRenewalControl($this->db,$this->load,'wc_get_order',$this->timezone,$this->config); $r['payment']=$control->payment($t); $end=$this->local($t['EndDateTime']);$days=$end?(int)ceil((strtotime($end.' UTC')-time())/86400):null; $r['expiry_label']=$days===null?'Service dates not recorded':($days<=0?($r['service_enabled']?'Expired but backend enabled':'Service period ended'):($days<=30?'Ends in '.$days.' day'.($days===1?'':'s'):'')); $r['renewal_control']=null;$r['renewal_control_reason']=null; try{$s=$control->state(['kind'=>'admin','id'=>$admin],(int)$t['ClientDeviceTransactionID']);$r['renewal_control']=['mode'=>$s['mode'],'transaction_id'=>(int)$t['ClientDeviceTransactionID']];} catch(Throwable $e){$r['renewal_control_reason']=$e instanceof PDOException?'Renewal management is unavailable.':$e->getMessage();} $r['payment_link']=rtrim($this->config['SHOP']['CUSTOMER_PORTAL']['AccountURL']??'','/').'/?renew_device='.(int)$r['device_id']; } return $r; } public function list(int $admin,string $search='',int $offset=0,?int $client=null): array { $gate=$this->allowed($admin);if(strlen($search)>100||preg_match('/[\x00-\x1f\x7f]/',$search))throw new RuntimeException('Invalid search.'); if($offset<0||$offset>1000000)throw new RuntimeException('Invalid page.'); $where='c.RecordStatus IN (0,1) AND d.ClientID>0';$args=[]; if($client!==null){$this->readable($admin,$client);$where.=' AND d.ClientID=?';$args[]=$client;} if(($gate['AllowAllClients']??false)!==true){$ids=array_values(array_filter($gate['AllowedClientIDs']??[],fn($v)=>is_int($v)&&$v>0));if(!$ids)return ['rows'=>[],'total'=>0,'offset'=>$offset,'next_offset'=>null,'timezone'=>$this->timezone->getName(),'unlinked'=>[],'unlinked_count'=>0];$where.=' AND d.ClientID IN ('.implode(',',array_fill(0,count($ids),'?')).')';array_push($args,...$ids);} if($search!==''){ $like='%'.strtr($search,['='=>'==','%'=>'=%','_'=>'=_']).'%'; $where.=" AND (d.SimHash LIKE ? ESCAPE '=' OR d.DeviceID LIKE ? ESCAPE '=' OR d.TransactionType LIKE ? ESCAPE '=' OR c.UserName LIKE ? ESCAPE '=' OR CAST(d.OrderID AS CHAR) LIKE ? ESCAPE '=')"; array_push($args,$like,$like,$like,$like,$like); } $from=' FROM ClientDeviceTransaction d JOIN Client c ON c.ClientID=d.ClientID WHERE '.$where; $total=(int)$this->query('SELECT COUNT(*)'.$from,$args)->fetchColumn(); $rows=$this->query('SELECT d.*'.$from.' ORDER BY d.ClientDeviceTransactionID DESC LIMIT 20 OFFSET '.$offset,$args)->fetchAll(PDO::FETCH_ASSOC); $out=[];foreach($rows as $t)$out[]=$this->transactionRow($admin,$t); $unlinked=[];$unlinkedCount=0; if(($gate['AllowAllClients']??false)===true||$client!==null){ $pending="FROM wp_wc_orders o WHERE o.type='shop_subscription' AND o.status IN ('wc-active','wc-on-hold','wc-pending','wc-pending-cancel') AND NOT EXISTS(SELECT 1 FROM ClientDeviceTransaction t WHERE t.OrderID=o.id AND t.TransactionType='subscription' AND COALESCE(t.DeviceID,'')<>'' AND COALESCE(t.ICCID,'')<>'' AND COALESCE(t.SimHash,'')<>'')"; $pendingArgs=[]; if($client!==null){ $email=$this->query('SELECT UserName FROM Client WHERE ClientID=? AND RecordStatus IN (0,1)',[$client])->fetchColumn(); $owners=$this->query('SELECT ID FROM wp_users WHERE user_email=?',[$email])->fetchAll(PDO::FETCH_COLUMN); if(count($owners)!==1)$pending.=' AND 1=0';else{$pending.=' AND o.customer_id=?';$pendingArgs[]=(int)$owners[0];} } $unlinkedCount=(int)$this->query('SELECT COUNT(*) '.$pending,$pendingArgs)->fetchColumn(); $unlinked=$this->query('SELECT o.id AS subscription_id,o.status AS billing_status,o.billing_email AS customer_email '.$pending.' ORDER BY o.id DESC LIMIT 20',$pendingArgs)->fetchAll(PDO::FETCH_ASSOC); foreach($unlinked as &$u){$s=call_user_func($this->load,(int)$u['subscription_id']);$items=$s?$s->get_items():[];$item=$items?reset($items):null; $u+=['plan'=>$item&&method_exists($item,'get_name')?$item->get_name():'Not recorded','amount'=>$s?(string)$s->get_total():null,'currency'=>$s?$s->get_currency():null,'billing_period'=>$s?$s->get_billing_period():null,'billing_interval'=>$s?(int)$s->get_billing_interval():null,'next_payment_utc'=>$s?$s->get_date('next_payment','gmt'):null];}unset($u); } return ['rows'=>$out,'total'=>$total,'offset'=>$offset,'next_offset'=>$offset+20<$total?$offset+20:null,'timezone'=>$this->timezone->getName(),'unlinked'=>$unlinked,'unlinked_count'=>$unlinkedCount]; } public function details(int $admin,int $id): array { $r=$this->row($admin,$this->identity($admin,$id));$public=$this->publicRow($r); $public['backend_transactions']=$this->query('SELECT ClientDeviceTransactionID,TransactionType,OrderID,SubscriptionStatus,IsActive,StartDateTime,EndDateTime FROM ClientDeviceTransaction WHERE ClientID=? AND DeviceID=? ORDER BY ClientDeviceTransactionID DESC LIMIT 20',[$r['client_id'],$r['device_key']])->fetchAll(PDO::FETCH_ASSOC); $public['history_available']=true; try{$public['transaction_history']=$this->query('SELECT EventType,OrderID,TransactionDate,StartDateTime,EndDateTime,SubscriptionStatus FROM ClientDeviceTransactionHistory WHERE ClientID=? AND DeviceID=? ORDER BY TransactionDate DESC,ClientDeviceTransactionID DESC LIMIT 20',[$r['client_id'],$r['device_key']])->fetchAll(PDO::FETCH_ASSOC);} catch(Throwable $e){$public['history_available']=false;$public['transaction_history']=[];} $noticeSQL='FROM PA_ShopNotification n JOIN ClientDeviceTransaction t ON t.ClientDeviceTransactionID=n.ClientDeviceTransactionID WHERE n.ClientID=? AND t.ClientID=n.ClientID AND t.DeviceID=?'; $public['notices_available']=true; try{$args=[$r['client_id'],$r['device_key']];$public['notice_count']=(int)$this->query('SELECT COUNT(*) '.$noticeSQL,$args)->fetchColumn(); $public['notices']=$this->query('SELECT n.NotificationID,n.TemplateName,n.State,n.RecipientEmail,n.ActualRecipientEmail,n.ProviderStatus,n.ProviderMessageID,n.InsertDateTimeUTC,n.AttemptDateTimeUTC,n.UpdateDateTimeUTC '.$noticeSQL.' ORDER BY n.NotificationID DESC LIMIT 20',$args)->fetchAll(PDO::FETCH_ASSOC); }catch(Throwable $e){$public['notices_available']=false;$public['notices']=[];} $public['audit_available']=true; try{$public['audit']=$this->query('SELECT AdminID,Action,Reason,State,ServiceEndUTC,ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopAdminSubscriptionAction WHERE ClientDevicesID=? ORDER BY InsertDateTimeUTC DESC,RequestID DESC LIMIT 20',[$id])->fetchAll(PDO::FETCH_ASSOC); $public['billing_audit']=$r['subscription_id']?$this->query('SELECT AdminID,Action,Reason,State,LastErrorCode AS ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopBillingControl WHERE SubscriptionID=? ORDER BY InsertDateTimeUTC DESC,RequestID DESC LIMIT 20',[$r['subscription_id']])->fetchAll(PDO::FETCH_ASSOC):[]; }catch(Throwable $e){$public['audit_available']=false;$public['audit']=[];$public['billing_audit']=[];} $public['billing_actions']=[];$public['billing_control_reason']=null; if(!$r['review']&&$r['subscription_id']){ try{ if(!class_exists('PAShopBillingControl',false))require_once '/opt/SA/DEV/WEB/SHOP/wp-content/plugins/pa-device-transaction/PA_SHOP_BILLING_CONTROL.php'; $gate=PAShopAdminGate::subscription($this->db,$this->config,'BILLING_CONTROL',$admin,$r['subscription_id']); $worker=new PAShopBillingControl($this->db,$this->load,$this->timezone,$gate); $action=$r['billing_status']==='active'?'pause':'resume';$worker->inspect($admin,$r['subscription_id'],$action,$action==='pause'?'keep':'auto'); $public['billing_actions']=[$action]; }catch(Throwable $e){$public['billing_control_reason']='Billing controls require a supported gateway, confirmed activation and unchanged paid dates.';} } return $public; } public function transactionDetails(int $admin,int $id): array { $t=$this->query('SELECT * FROM ClientDeviceTransaction WHERE ClientDeviceTransactionID=?',[$id])->fetch(PDO::FETCH_ASSOC); if(!$t)throw new RuntimeException('Current transaction unavailable.'); $r=$this->transactionRow($admin,$t); $details=$r['device_id']?$this->details($admin,$r['device_id']):['notices_available'=>true,'notices'=>[],'notice_count'=>0,'audit_available'=>true,'audit'=>[],'billing_audit'=>[],'billing_actions'=>[],'billing_control_reason'=>null]; $details=array_replace($details,$r); $details['backend_transactions']=[$t];$details['history_available']=true; try{$details['transaction_history']=$this->query("SELECT EventType,OrderID,TransactionDate,StartDateTime,EndDateTime,SubscriptionStatus FROM ClientDeviceTransactionHistory WHERE ClientID=? AND (ClientDeviceTransactionID=? OR (DeviceID<>'' AND DeviceID=?)) ORDER BY TransactionDate DESC LIMIT 20",[$t['ClientID'],$id,$t['DeviceID']??''])->fetchAll(PDO::FETCH_ASSOC);} catch(Throwable $e){$details['history_available']=false;$details['transaction_history']=[];} if($t['TransactionType']!=='subscription'){$details['billing_actions']=[];$details['billing_control_reason']=null;} if(class_exists('PAShopRenewalControl')){ $details['billing_actions']=[]; $details['renewal_audit']=$this->query('SELECT ActorKind,ActorID,Mode AS Action,Reason,State,ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopRenewalAction WHERE ClientDeviceTransactionID=? ORDER BY InsertDateTimeUTC DESC LIMIT 20',[$id])->fetchAll(PDO::FETCH_ASSOC); } return $details; } public function export(int $admin,int $id): array { $t=$this->query('SELECT * FROM ClientDeviceTransaction WHERE ClientDeviceTransactionID=?',[$id])->fetch(PDO::FETCH_ASSOC); if(!$t)throw new RuntimeException('Current transaction unavailable.');$this->readable($admin,(int)$t['ClientID']); $groups=['Export metadata'=>[['GeneratedUTC'=>gmdate('Y-m-d H:i:s'),'TimeBasis'=>'UTC-suffixed fields are UTC. Legacy backend dates are exported exactly as recorded.','AdminID'=>$admin]],'Current record'=>[$t]]; if(class_exists('PAShopRenewalControl'))$groups['Payment verification']=[(new PAShopRenewalControl($this->db,$this->load,'wc_get_order',$this->timezone,$this->config))->payment($t)]; $groups['Transaction history']=$this->query("SELECT EventType,OrderID,OrderItemID,TransactionDate,StartDateTime,EndDateTime,SubscriptionStatus FROM ClientDeviceTransactionHistory WHERE ClientID=? AND (ClientDeviceTransactionID=? OR (DeviceID<>'' AND DeviceID=?)) ORDER BY TransactionDate LIMIT 10001",[$t['ClientID'],$id,$t['DeviceID']??''])->fetchAll(PDO::FETCH_ASSOC); $groups['Email notices']=$this->query('SELECT TemplateName,State,RecipientEmail,ActualRecipientEmail,ProviderStatus,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopNotification WHERE ClientID=? AND ClientDeviceTransactionID=? ORDER BY NotificationID LIMIT 10001',[$t['ClientID'],$id])->fetchAll(PDO::FETCH_ASSOC); $groups['Renewal changes']=$this->query('SELECT ActorKind,ActorID,Mode,Reason,State,ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopRenewalAction WHERE ClientID=? AND ClientDeviceTransactionID=? ORDER BY InsertDateTimeUTC LIMIT 10001',[$t['ClientID'],$id])->fetchAll(PDO::FETCH_ASSOC); $groups['Device renewal payments']=$this->query('SELECT OrderID,OrderItemID,Period,Price,Currency,OldEndUTC,NewEndUTC,State,ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopDeviceRenewalOrder WHERE ClientID=? AND ClientDeviceTransactionID=? ORDER BY InsertDateTimeUTC LIMIT 10001',[$t['ClientID'],$id])->fetchAll(PDO::FETCH_ASSOC); if($t['TransactionType']==='subscription')$groups['Billing actions']=$this->query('SELECT AdminID,Action,Reason,State,LastErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopBillingControl WHERE ClientID=? AND SubscriptionID=? ORDER BY InsertDateTimeUTC LIMIT 10001',[$t['ClientID'],$t['OrderID']])->fetchAll(PDO::FETCH_ASSOC); $groups['Admin cancellations']=$this->query('SELECT AdminID,Action,Reason,State,ServiceEndUTC,ErrorCode,InsertDateTimeUTC,UpdateDateTimeUTC FROM PA_ShopAdminSubscriptionAction WHERE ClientID=? AND ClientDevicesID IN (SELECT ClientDevicesID FROM ClientDevices WHERE ClientID=? AND DeviceID=?) ORDER BY InsertDateTimeUTC LIMIT 10001',[$t['ClientID'],$t['ClientID'],$t['DeviceID']??''])->fetchAll(PDO::FETCH_ASSOC); $stream=fopen('php://temp','w+');fputcsv($stream,['Section','Record','Field','Value']); foreach($groups as $name=>$records){if(count($records)>10000)throw new RuntimeException('Export exceeds 10,000 entries in a section. Contact support for a full archive.');foreach($records as $i=>$record)foreach($record as $key=>$value){$value=(string)$value;if(preg_match('/^[\s]*[=+@-]/',$value))$value="'".$value;fputcsv($stream,[$name,$i+1,$key,$value]);}} rewind($stream);$csv=stream_get_contents($stream);fclose($stream); return ['filename'=>'PinkAngels-device-transaction-'.$id.'-'.gmdate('Ymd').'.csv','csv'=>$csv]; } private function fingerprint(array $r): string { $s=$r['subscription'];$d=$this->query('SELECT DeviceID,ICCID,SimHash,ClientID,EndDateTime,Subscription_EndDateTime,Enabled,RecordStatus FROM ClientDevices WHERE ClientDevicesID=?',[$r['deviceID']])->fetch(PDO::FETCH_ASSOC); return hash('sha256',json_encode([$d,$r['subscriptionID'],$r['status'],$r['paidThroughUTC'],$r['cancelEndUTC'], $s->get_customer_id(),$s->get_date('next_payment','gmt'),$s->get_payment_method(),$s->is_manual(),$s->get_total(),$s->get_currency()],JSON_THROW_ON_ERROR)); } public function cancellation(int $admin,int $id,int $subscription): array { $r=$this->row($admin,$this->identity($admin,$id)); if(!$r['can_cancel']||$r['subscription_id']!==$subscription)throw new RuntimeException('Cancellation requires a confirmed, independently linked device with no active alert.'); return ['device_id'=>$id,'subscription_id'=>$subscription,'client_id'=>$r['client_id'],'shop_user_id'=>$r['shop_user_id'], 'device_name'=>$r['device_name'],'device_code'=>$r['device_code'],'customer_email'=>$r['customer_email'], 'service_end_utc'=>$r['cancel_end_utc'],'fingerprint'=>$this->fingerprint($r['_model'])]; } public function cancel(int $admin,array $proof): array { $this->allowed($admin,(int)$proof['client_id']);$request=$proof['request_id'];$reason=$proof['reason']; if(!is_string($request)||!preg_match('/^[a-f0-9]{32}$/D',$request)||!is_string($reason)||strlen(trim($reason))<8||strlen($reason)>500||preg_match('/[\x00-\x1f\x7f]/',$reason))throw new RuntimeException('A valid cancellation reference and reason are required.'); $old=$this->query('SELECT * FROM PA_ShopAdminSubscriptionAction WHERE RequestID=?',[$request])->fetch(PDO::FETCH_ASSOC); if($old){ if((int)$old['AdminID']!==$admin||(int)$old['ClientDevicesID']!==$proof['device_id']||(int)$old['SubscriptionID']!==$proof['subscription_id']||(int)$old['ClientID']!==$proof['client_id']||$old['ExpectedFingerprint']!==$proof['fingerprint']||$old['Reason']!==$reason||$old['ServiceEndUTC']!==$proof['service_end_utc'])throw new RuntimeException('Cancellation replay identity changed.'); return ['state'=>$old['State'],'replayed'=>true,'service_end_utc'=>$old['ServiceEndUTC']]; } $identity=$this->identity($admin,(int)$proof['device_id']); if($identity['shop_user_id']!==$proof['shop_user_id']||(int)$identity['ClientID']!==$proof['client_id'])throw new RuntimeException('Device ownership changed.'); $started=false; try{ $result=$this->model->cancel($proof['shop_user_id'],$proof['device_id'],$proof['subscription_id'],$proof['service_end_utc'], 'Admin #'.$admin.' confirmed cancellation: '.$reason, function($row)use($admin,$proof,$request,$reason,&$started){ $this->allowed($admin,(int)$proof['client_id']); if(!hash_equals($proof['fingerprint'],$this->fingerprint($row)))throw new RuntimeException('Billing or device details changed. Review again.'); if((int)$this->query("SELECT COUNT(*) FROM PA_ShopAdminSubscriptionAction WHERE ClientDevicesID=? AND State IN ('started','review_required')",[$proof['device_id']])->fetchColumn()>0)throw new RuntimeException('An earlier cancellation needs verification.'); $audit=$proof;unset($audit['token'],$audit['expires']); $this->query("INSERT INTO PA_ShopAdminSubscriptionAction (RequestID,AdminID,ClientDevicesID,SubscriptionID,ClientID,Action,Reason,ExpectedFingerprint,ServiceEndUTC,BeforeJSON,State,InsertDateTimeUTC,UpdateDateTimeUTC) VALUES (?,?,?,?,?,'cancel',?,?,?,?,'started',UTC_TIMESTAMP(),UTC_TIMESTAMP())",[$request,$admin,$proof['device_id'],$proof['subscription_id'],$proof['client_id'],$reason,$proof['fingerprint'],$proof['service_end_utc'],json_encode($audit,JSON_THROW_ON_ERROR)]);$started=true; }); if(!$started)throw new RuntimeException('Cancellation changed since confirmation. Review the recorded status.'); $this->query("UPDATE PA_ShopAdminSubscriptionAction SET State='completed',UpdateDateTimeUTC=UTC_TIMESTAMP() WHERE RequestID=?",[$request]); return ['state'=>'completed','replayed'=>false,'service_end_utc'=>$result['endUTC']]; }catch(Throwable $e){ if($started){ try{$this->query("UPDATE PA_ShopAdminSubscriptionAction SET State='review_required',ErrorCode='cancellation_unconfirmed',UpdateDateTimeUTC=UTC_TIMESTAMP() WHERE RequestID=?",[$request]);}catch(Throwable $ledgerError){error_log('PA Admin cancellation audit requires review | RequestID='.$request);} $sub=call_user_func($this->load,$proof['subscription_id']);if($sub){$sub->update_meta_data('_pa_lifecycle_review','required');$sub->save();} return ['state'=>'review_required','replayed'=>false]; }throw $e; } } public function carrierStatus(int $admin,int $id): array { $d=$this->identity($admin,$id); $matches=(int)$this->query('SELECT COUNT(*) FROM ClientDevices WHERE DeviceID=? OR ICCID=? OR SimHash=?',[$d['DeviceID'],$d['ICCID'],$d['SimHash']])->fetchColumn(); if($matches!==1||!$d['DeviceID']||!$d['ICCID']||!$d['SimHash'])throw new RuntimeException('SIM identity requires review.'); if(!class_exists('PAShopCarrier',false))require_once '/opt/SA/DEV/WEB/SHOP/wp-content/plugins/pa-device-transaction/PA_SHOP_CARRIER.php'; $once=$this->config['CARRIER']['ONCE']??[];$carrier=new PAShopCarrier($once['URLAUTH']??'',$once['APIKEY']??'',null,null,$this->config['CARRIER']??[]); $result=$carrier->readEnabled((string)$d['ICCID']); return ['confirmed'=>($result['confirmed']??false)===true,'enabled'=>$result['enabled']??null,'carrier'=>PACommonCarrier_Detect((string)$d['ICCID'],$this->config['CARRIER']??[]),'checked_utc'=>gmdate('Y-m-d H:i:s')]; } }