--- /home/innovationhub/agreements.innovation-hub.co.za/company_tab.php 2026-11-25 17:03:45.404521924 +0200 +++ /home/innovationhub/private/agreements_web/contract_qa_13301/company_tab.php 2026-11-25 11:57:12.000000000 +0200 @@ -13,13 +13,9 @@ if($code!==200||!is_array($json)||isset($json['error']))throw new RuntimeException('Bitrix authorization or REST error: '.$method); return $json; } +require_once dirname(__DIR__).'/private/agreement_bitrix_sync.php'; +require_once dirname(__DIR__).'/private/agreement_kind.php'; function hv(mixed $v):string{return e((string)($v??''));} -/** Full calendar months until expiry; negative after expiry. Days remain a separate exact value. */ -function monthsRemaining(?string $expiry):string{ - if(!$expiry)return '—'; - try{$today=new DateTimeImmutable('today');$end=new DateTimeImmutable($expiry);$diff=$today->diff($end);$months=($diff->y*12)+$diff->m;return ($diff->invert?'-':'').$months.' months';} - catch(Throwable $e){return '—';} -} /** Resolve audit actor IDs against Bitrix, cache lookups for this session, retain IDs on REST errors. */ function historyActorName(int $id):string{ if($id<=0)return 'Unknown user'; @@ -51,16 +47,17 @@ $s=$db->prepare('INSERT INTO agreement_phase2_audit(agreement_id,actor_user_id,event_type,before_json,after_json) VALUES(?,?,?,?,?)'); $s->execute([$id,$user,$event,$before===null?null:json_encode($before,JSON_THROW_ON_ERROR),json_encode($after,JSON_THROW_ON_ERROR)]); } -function agreementTabServiceLabel(mixed $value):string{$service=trim((string)($value??''));return in_array(strtolower($service),['it','remote support'],true)?'IT Remote Support':$service;} -function recordValues(array $src,array $categories):array{ +function recordValues(array $src,array $categories,?string $existingKind=null,bool $allowLegacy=false):array{ $title=trim((string)($src['title']??''));$type=trim((string)($src['type']??''));$division=(string)($src['division']??''); - $start=strictDate((string)($src['start']??''));$end=strictDate((string)($src['end']??'')); - $institution=trim((string)($src['institution']??''));$escalation=trim((string)($src['escalation']??''));$coverage=trim((string)($src['coverage']??'')); + $kind=agreement_kind_normalize($src['kind']??null,$allowLegacy&&$existingKind===null&&trim((string)($src['kind']??''))===''); + $startRaw=trim((string)($src['start']??''));$endRaw=trim((string)($src['end']??''));$start=$startRaw===''?null:strictDate($startRaw);$end=$endRaw===''?null:strictDate($endRaw); + $institution=trim((string)($src['institution']??''));$escalation=trim((string)($src['escalation']??''));$coverage=trim((string)($src['coverage']??''));$serial=trim((string)($src['serial_number']??''));$notes=trim((string)($src['notes']??'')); $status=(string)($src['status']??'active'); - if(mb_strlen($title)<3||mb_strlen($title)>255||!in_array($type,$categories,true)||!in_array($division,['ihg','innovate'],true)||!in_array($status,['active','inactive'],true))throw new InvalidArgumentException('Invalid title, category, division or status'); - if($end<$start)throw new InvalidArgumentException('Expiry must not precede start date'); - if(mb_strlen($institution)>255||mb_strlen($escalation)>255||mb_strlen($coverage)>5000)throw new InvalidArgumentException('Institution, escalation or coverage is too long'); - return ['agreement_title'=>$title,'agreement_type'=>$type,'business_division'=>$division,'starts_on'=>$start,'ends_on'=>$end,'source_issuer'=>$institution?:null,'source_escalation_value'=>$escalation?:null,'coverage_description'=>$coverage?:null,'status_override'=>$status]; + if(mb_strlen($title)<3||mb_strlen($title)>255||!in_array($type,$categories,true)||!in_array($division,['ihg','innovate'],true)||!in_array($status,['active','inactive'],true)||$serial===''||mb_strlen($serial)>255)throw new InvalidArgumentException('Invalid title, required Serial Number, service, division or status'); + if($kind!=='cash'&&($start===null||$end===null))throw new InvalidArgumentException('Contract agreements require start and expiry dates.'); + if($end!==null&&$start!==null&&$end<$start)throw new InvalidArgumentException('Expiry must not precede start date'); + if(mb_strlen($institution)>255||mb_strlen($escalation)>255||mb_strlen($coverage)>5000||mb_strlen($notes)>12000)throw new InvalidArgumentException('Institution, escalation, coverage or notes are too long'); + return ['agreement_title'=>$title,'agreement_type'=>$type,'agreement_kind'=>$kind,'business_division'=>$division,'starts_on'=>$start,'ends_on'=>$end,'source_issuer'=>$institution?:null,'source_escalation_value'=>$escalation?:null,'coverage_description'=>$coverage?:null,'serial_number'=>$serial,'notes'=>$notes,'status_override'=>$status]; } function latestAgreement(PDO $db,int $id,int $company):?array{ $s=$db->prepare('SELECT a.*,m.status_override,m.previous_agreement_id FROM agreements a LEFT JOIN agreement_phase2_meta m ON m.agreement_id=a.id WHERE a.id=? AND a.bitrix_company_id=? LIMIT 1');$s->execute([$id,$company]);$r=$s->fetch();return $r?:null; @@ -70,12 +67,12 @@ // Legacy Bitrix source rows are displayed under IHG because Innovate has not been imported. return 'ihg'; } -function insertion(PDO $db,int $company,string $name,array $v,int $user,?int $previous=null):int{ - $q=$db->prepare("INSERT INTO agreements (bitrix_company_id,customer_name_snapshot,agreement_title,agreement_type,business_division,starts_on,ends_on,source_issuer,source_escalation_value,coverage_description,lifecycle) VALUES(?,?,?,?,?,?,?,?,?,?,'needs_review')"); - $q->execute([$company,$name,$v['agreement_title'],$v['agreement_type'],$v['business_division'],$v['starts_on'],$v['ends_on'],$v['source_issuer'],$v['source_escalation_value'],$v['coverage_description']]); +function insertion(PDO $db,int $company,string $name,array $v,int $user):int{ + $q=$db->prepare("INSERT INTO agreements (bitrix_company_id,customer_name_snapshot,agreement_title,agreement_type,agreement_kind,business_division,starts_on,ends_on,source_issuer,source_escalation_value,coverage_description,lifecycle) VALUES(?,?,?,?,?,?,?,?,?,?,?,'needs_review')"); + $q->execute([$company,$name,$v['agreement_title'],$v['agreement_type'],$v['agreement_kind'],$v['business_division'],$v['starts_on'],$v['ends_on'],$v['source_issuer'],$v['source_escalation_value'],$v['coverage_description']]); $id=(int)$db->lastInsertId(); - $q=$db->prepare('INSERT INTO agreement_phase2_meta(agreement_id,status_override,previous_agreement_id,created_by_user_id) VALUES(?,?,?,?)'); - $q->execute([$id,$v['status_override'],$previous,$user]);audit2($db,$id,$user,$previous?'renew':'create',null,$v+['previous_agreement_id'=>$previous]);return $id; + $q=$db->prepare('INSERT INTO agreement_phase2_meta(agreement_id,status_override,created_by_user_id) VALUES(?,?,?)'); + $q->execute([$id,$v['status_override'],$user]);audit2($db,$id,$user,'create',null,$v);return $id; } // The Bitrix iframe delivers a verified launch token and company placement ID. if(($_POST['AUTH_ID']??'')!==''){ @@ -113,7 +110,15 @@ } } $role=$isAdmin?'administrator':$assignedRole; -$canEdit=$isAdmin||in_array($role,['management','finance_admin'],true); +$canEditByRole=$isAdmin||in_array($role,['management','finance_admin'],true); +// Development gates stay off by default. Production requires separate enablement and synthetic verification. +$bitrixMetadata=null;$bitrixMetadataError='';$bitrixAgreementWriteMappingVerified=false;$bitrixKindMapping=null; +if($canEditByRole && getenv('AGREEMENTS_BITRIX_REST_METADATA_ENABLED')==='1'){ + try{$bitrixMetadata=ab1058_fetch_field_metadata(static fn(string $method,array $params=[]):array=>api2($method,$params));$bitrixKindMapping=ab1058_agreement_kind_payload_mapping($bitrixMetadata['fields']??[]);$bitrixAgreementWriteMappingVerified=(bool)($bitrixMetadata['verification']['ok']??false);}catch(Throwable $metadataException){$bitrixMetadataError='Live Smart Process REST field metadata is unavailable or does not match the verified baseline field map.';} +} +$writeFlags= getenv('AGREEMENTS_BITRIX_WRITES_ENABLED')==='1' && getenv('AGREEMENTS_BITRIX_SYNTHETIC_TESTED')==='1' && getenv('AGREEMENTS_BITRIX_WRITE_PERMISSION_VERIFIED')==='1'; +$syncSchemaReady=false;try{$syncSchemaReady=ab1058_migration_ready($db);}catch(Throwable $ignored){} +$canEdit=$canEditByRole && $bitrixAgreementWriteMappingVerified && $writeFlags && $syncSchemaReady; $canManageMasters=$isAdmin||in_array($role,['management','finance_admin'],true); $canManageRoles=$isAdmin; $canSeeAudit=$isAdmin||in_array($role,['management','finance_admin'],true); @@ -123,17 +128,18 @@ try{$crm=$cid?getCompany($cid):null;}catch(Throwable $ex){http_response_code(403);exit('Customer record is not accessible through your Bitrix account.');} $name=(string)($crm['TITLE']??''); $categories=$db->query('SELECT category FROM agreement_categories WHERE enabled=1 ORDER BY category')->fetchAll(PDO::FETCH_COLUMN); -$categoryChoices=[];foreach($categories as $category){$category=trim((string)$category);if($category===''||in_array(strtolower($category),['it','remote support'],true))continue;$categoryChoices[$category]=$category;}foreach(['IT Remote Support','IT Gold Support','IT Platinum Support'] as $service)$categoryChoices[$service]=$service;asort($categoryChoices,SORT_NATURAL|SORT_FLAG_CASE);$categoryList=array_keys($categoryChoices); +$categoryChoices=agreement_service_options($categories);$categoryList=array_keys($categoryChoices); $institutions=$db->query("SELECT institution_name FROM agreement_phase3_institutions WHERE enabled=1 ORDER BY institution_name")->fetchAll(PDO::FETCH_COLUMN); $institutionList=array_values(array_map('strval',$institutions)); $categoryAdminRows=$canManageMasters?$db->query('SELECT category,enabled FROM agreement_categories ORDER BY category')->fetchAll():[]; $institutionAdminRows=$canManageMasters?$db->query('SELECT institution_name,enabled FROM agreement_phase3_institutions ORDER BY institution_name')->fetchAll():[]; $assignedUsers=$canManageRoles?$db->query('SELECT user_id,role_name,assigned_by,updated_at FROM agreement_phase3_roles ORDER BY user_id')->fetchAll():[]; $division=(string)($_GET['division']??'ihg');if(!in_array($division,['ihg','innovate'],true))$division='ihg'; +$q=substr(trim((string)($_GET['q']??'')),0,120); $activity=(string)($_GET['activity']??'active');if($activity==='unmapped')$activity='all';if(!in_array($activity,['active','inactive','all'],true))$activity='active'; $sort=(string)($_GET['sort']??'expiry');if(!in_array($sort,['start','expiry','months','days'],true))$sort='expiry'; $direction=(string)($_GET['dir']??'asc');if(!in_array($direction,['asc','desc'],true))$direction='asc'; -$url=static function(array $change=[])use($division,$activity,$sort,$direction):string{return '?'.http_build_query(array_merge(compact('division','activity','sort'),['dir'=>$direction],$change),'','&',PHP_QUERY_RFC3986);}; +$url=static function(array $change=[])use($division,$activity,$sort,$direction,$q):string{return '?'.http_build_query(array_merge(compact('division','activity','sort','q'),['dir'=>$direction],$change),'','&',PHP_QUERY_RFC3986);}; $nonce=(string)($_SESSION['agreements_tab_nonce']??''); if($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST['AUTH_ID'])){ try{ @@ -142,54 +148,89 @@ if((int)($_POST['company_id']??0)!==$cid)throw new RuntimeException('Incorrect company context'); getCompany($cid); // re-authorize CRM company before every mutation $op=(string)($_POST['operation']??''); - if(in_array($op,['create','edit','renew'],true)){ + if(in_array($op,['create','edit'],true)){ if(!$canEdit)throw new RuntimeException('Agreement editing requires Finance, Management or Administrator access'); - $target=(int)($_POST['agreement_id']??0);$old=$op==='create'?null:latestAgreement($db,$target,$cid);$allowedServices=$categoryList;if($op==='edit'&&$old!==null&&!in_array((string)($old['agreement_type']??''),$allowedServices,true))$allowedServices[]=(string)$old['agreement_type'];$v=recordValues($_POST,$allowedServices);$target=(int)($_POST['agreement_id']??0); + $target=(int)($_POST['agreement_id']??0); $old=$op==='create'?null:latestAgreement($db,$target,$cid); if($op!=='create'&&!$old)throw new RuntimeException('Agreement is not linked to this company'); - if($old && storedDivision($old)!==$v['business_division'] && $op==='renew')throw new InvalidArgumentException('Renewal must retain the original business division'); - $db->beginTransaction(); - if($op==='create'||$op==='renew'){ - $id=insertion($db,$cid,$name,$v,$user,$op==='renew'?$target:null); - if($op==='renew'){ - // Preserve the old agreement and its recorded status. Link the new agreement to the predecessor. - audit2($db,$target,$user,'renewed_by',null,['new_agreement_id'=>$id]); - } - $notice= $op==='create'?'Agreement created':'Renewal created as a separate agreement'; + $allowedServices=$categoryList; + if($op==='edit'&&$old!==null&&!in_array((string)($old['agreement_type']??''),$allowedServices,true))$allowedServices[]=(string)$old['agreement_type']; + $v=recordValues($_POST,$allowedServices,($old===null||empty($old['agreement_kind']))?null:(string)$old['agreement_kind'],$op==='edit'&&$old!==null&&empty($old['agreement_kind'])); + $metadata=ab1058_fetch_field_metadata(static fn(string $method,array $params=[]):array=>api2($method,$params)); + if(empty($metadata['verification']['ok']))throw new RuntimeException('Live REST field metadata does not match the verified Smart Process 1058 mapping.'); + $kindPayloadMapping=ab1058_agreement_kind_payload_mapping($metadata['fields']??[]); + if($v['agreement_kind']!==null&&$kindPayloadMapping===null)throw new RuntimeException('Contract/Cash Type has no verified Smart Process 1058 field and enum mapping; no Bitrix write was sent.'); + // Deliberately unset in normal development and production. Isolated synthetic + // testing must explicitly opt into the restricted opened=N candidate value. + $openedCandidate=getenv('AGREEMENTS_BITRIX_SYNTHETIC_OPENED_VALUE'); + $payload=ab1058_rest_payload(['company_id'=>$cid,'title'=>$v['agreement_title'],'serial_number'=>$v['serial_number'],'status'=>$v['status_override'],'coverage'=>$v['coverage_description']??'','start'=>$v['starts_on'],'end'=>$v['ends_on'],'escalation'=>$v['source_escalation_value']??'','institution'=>$v['source_issuer']??'','notes'=>$v['notes'],'opened'=>$openedCandidate,'agreement_kind'=>$v['agreement_kind']],$kindPayloadMapping); + if($op==='create'){ + $created=api2('crm.item.add',['entityTypeId'=>AGREEMENT_BITRIX_ENTITY_TYPE_ID,'fields'=>$payload]+ab1058_original_uf_names_option())['result']??[]; + $sourceId=(string)($created['item']['id']??$created['item']['ID']??$created['id']??''); + if(!ctype_digit($sourceId)||(int)$sourceId<=0)throw new RuntimeException('Bitrix did not return a Contract ID.'); }else{ - $s=$db->prepare('UPDATE agreements SET agreement_title=?,agreement_type=?,business_division=?,starts_on=?,ends_on=?,source_issuer=?,source_escalation_value=?,coverage_description=? WHERE id=? AND bitrix_company_id=?'); - $s->execute([$v['agreement_title'],$v['agreement_type'],$v['business_division'],$v['starts_on'],$v['ends_on'],$v['source_issuer'],$v['source_escalation_value'],$v['coverage_description'],$target,$cid]); - $m=$db->prepare('INSERT INTO agreement_phase2_meta(agreement_id,status_override,created_by_user_id) VALUES(?,?,?) ON DUPLICATE KEY UPDATE status_override=VALUES(status_override)'); - $m->execute([$target,$v['status_override'],$user]); - audit2($db,$target,$user,'edit',$old,$v);$notice='Agreement updated'; + $sourceLink=$db->prepare("SELECT source_record_id FROM agreement_source_links WHERE agreement_id=? AND source_system='bitrix_contracts' LIMIT 2");$sourceLink->execute([$target]);$sourceIds=$sourceLink->fetchAll(PDO::FETCH_COLUMN); + if(count($sourceIds)!==1||!ctype_digit((string)$sourceIds[0]))throw new RuntimeException('This local agreement does not have one verified Bitrix Contract link.'); + $sourceId=(string)$sourceIds[0]; + $remoteBefore=api2('crm.item.get',['entityTypeId'=>AGREEMENT_BITRIX_ENTITY_TYPE_ID,'id'=>(int)$sourceId]+ab1058_original_uf_names_option())['result']['item']??null; + if(!is_array($remoteBefore)||(int)($remoteBefore['id']??0)!==(int)$sourceId||(int)ab1058_value($remoteBefore,'companyId')!==$cid)throw new RuntimeException('The linked Bitrix Contract is missing or belongs to a different customer.'); + api2('crm.item.update',['entityTypeId'=>AGREEMENT_BITRIX_ENTITY_TYPE_ID,'id'=>(int)$sourceId,'fields'=>$payload]+ab1058_original_uf_names_option()); } - $db->commit(); + $remoteAfter=api2('crm.item.get',['entityTypeId'=>AGREEMENT_BITRIX_ENTITY_TYPE_ID,'id'=>(int)$sourceId]+ab1058_original_uf_names_option())['result']['item']??null; + if(!is_array($remoteAfter)||(string)($remoteAfter['id']??'')!==$sourceId||(string)ab1058_value($remoteAfter,'companyId')!==(string)$cid) + throw new RuntimeException('Bitrix Contract #'.$sourceId.' could not be verified for this customer after save. Review Bitrix before retrying.'); + $sync=ab1058_apply_item($db,$remoteAfter,static fn(int $companyId):string=>$name, + ['business_division'=>$v['business_division'],'agreement_type'=>$v['agreement_type'],'agreement_kind'=>$v['agreement_kind']],$op==='create', + static fn(int $localId)=>audit2($db,$localId,$user,$op,$old,$v)); + if(!in_array($sync['state']??'', ['created','updated','unchanged'],true))throw new RuntimeException('Bitrix Contract #'.$sourceId.' was saved, but local reconciliation is '.$sync['state'].' ('.$sync['reason'].'). Review the Sync Exceptions report before retrying.'); + $notice=$op==='create'?'New Bitrix Contract #'.$sourceId.' created and reconciled as a separate agreement':'Bitrix Contract #'.$sourceId.' updated and reconciled'; }else{throw new InvalidArgumentException('Unsupported operation');} - }catch(Throwable $ex){if($db->inTransaction())$db->rollBack();error_log('Agreements Phase2 mutation: '.$ex->getMessage());$error=$ex instanceof InvalidArgumentException?$ex->getMessage():'Unable to save. Check application permissions, required SQL tables and PHP logs.';} + }catch(Throwable $ex){if($db->inTransaction())$db->rollBack();error_log('Agreements Bitrix mutation: '.$ex->getMessage());$message=$ex->getMessage();$error=$ex instanceof InvalidArgumentException?$message:(str_starts_with($message,'Bitrix Contract #')||str_starts_with($message,'Live REST field metadata')||str_starts_with($message,'This local agreement')?$message:'Unable to save. Check Bitrix permissions, synchronization status and PHP logs.');} } $statusMap=[]; foreach($db->query('SELECT raw_value,status_label FROM agreement_status_map') as $entry)$statusMap[(string)$entry['raw_value']] = $entry['status_label']; $mapped=$db->query('SELECT COUNT(*) FROM agreement_status_map')->fetchColumn(); $rows=[];$total=0; if($cid>0){ - $sql="SELECT a.id,a.agreement_title,a.agreement_type,a.business_division,a.starts_on,a.ends_on,a.source_issuer,a.source_escalation_value,a.coverage_description,a.source_status_raw,m.status_override,m.previous_agreement_id,DATEDIFF(a.ends_on,CURRENT_DATE) AS days_left,sl.source_record_id AS original_contract_id FROM agreements a LEFT JOIN agreement_phase2_meta m ON m.agreement_id=a.id LEFT JOIN agreement_source_links sl ON sl.agreement_id=a.id AND sl.source_system='bitrix_contracts' WHERE a.bitrix_company_id=:cid"; + $sql="SELECT a.id,a.agreement_title,a.agreement_type,a.agreement_kind,a.business_division,a.starts_on,a.ends_on,a.source_issuer,a.source_escalation_value,a.coverage_description,a.source_status_raw,m.status_override,m.previous_agreement_id,CASE WHEN a.agreement_kind='cash' THEN NULL ELSE TIMESTAMPDIFF(MONTH,CURRENT_DATE,a.ends_on) END AS months_left,CASE WHEN a.agreement_kind='cash' THEN NULL ELSE DATEDIFF(a.ends_on,CURRENT_DATE) END AS days_left,sl.source_record_id AS original_contract_id FROM agreements a LEFT JOIN agreement_phase2_meta m ON m.agreement_id=a.id LEFT JOIN agreement_source_links sl ON sl.agreement_id=a.id AND sl.source_system='bitrix_contracts' WHERE a.bitrix_company_id=:cid"; if($division==='innovate')$sql.=" AND a.business_division='innovate'"; else $sql.=" AND (a.business_division='ihg' OR (a.business_division IS NULL AND sl.source_record_id IS NOT NULL))"; $sql.=" ORDER BY a.ends_on ASC,a.id DESC"; $s=$db->prepare($sql);$s->execute([':cid'=>$cid]); foreach($s->fetchAll() as $r){ - $override=(string)($r['status_override']??'');$raw=trim((string)($r['source_status_raw']??'')); - $r['effective_status']=in_array($override,['active','inactive'],true)?$override:($statusMap[$raw]??'unmapped'); - $r['date_expired']=!empty($r['ends_on']) && $r['ends_on']'starts_on','expiry'=>'ends_on','months'=>'days_left','days'=>'days_left'][$sort]; - usort($rows,static function($a,$b)use($sortField,$direction){$x=$a[$sortField];$y=$b[$sortField];if($x===null)return $y===null?0:1;if($y===null)return -1;$cmp=in_array($sortField,['days_left'],true)?((int)$x<=>(int)$y):strcmp((string)$x,(string)$y);return ($direction==='desc'?-1:1)*$cmp ?: ((int)$b['id']<=>(int)$a['id']);}); + $sortField=['start'=>'starts_on','expiry'=>'ends_on','months'=>'months_left','days'=>'days_left'][$sort]; + usort($rows,static function($a,$b)use($sortField,$direction){$x=$a[$sortField];$y=$b[$sortField];if($x===null)return $y===null?0:1;if($y===null)return -1;$cmp=in_array($sortField,['months_left','days_left'],true)?((int)$x<=>(int)$y):strcmp((string)$x,(string)$y);return ($direction==='desc'?-1:1)*$cmp ?: ((int)$b['id']<=>(int)$a['id']);}); +} +$canViewLinkedDocuments=false;$documentLinksByAgreement=[]; +if($cid>0){ + try{ + $linkagePath=getenv('AGREEMENT_LINKAGE_LIBRARY')?:'/home/innovationhub/private/agreements_web/agreement_document_linkage.php'; + if(!is_file($linkagePath))$linkagePath=dirname(__DIR__).'/private/agreement_document_linkage.php'; + require_once $linkagePath; + $canViewLinkedDocuments=ad_user_can_view_documents(static fn(string $method,array $params=[]):array=>api2($method,$params),$user); + if($canViewLinkedDocuments){ + $agreementIds=array_map(static fn(array $row):int=>(int)($row['original_contract_id']??0),$rows); + $documentLinksByAgreement=ad_group_document_links($db,$agreementIds,$cid,$division); + } + }catch(Throwable $documentPermissionError){ + $canViewLinkedDocuments=false;$documentLinksByAgreement=[]; + error_log('Agreements linked Documents permission: '.$documentPermissionError->getMessage()); + } } $editRow=null; if($canEdit&&$cid>0&&isset($_GET['edit'])&&ctype_digit((string)$_GET['edit']))$editRow=latestAgreement($db,(int)$_GET['edit'],$cid); +$prefillRow=null; +if($canEdit&&$cid>0&&isset($_GET['new_from'])&&ctype_digit((string)$_GET['new_from']))$prefillRow=latestAgreement($db,(int)$_GET['new_from'],$cid); +$formRow=$editRow??$prefillRow; +if($canEdit&&$formRow){$sourceId=$db->prepare("SELECT source_record_id FROM agreement_source_links WHERE agreement_id=? AND source_system='bitrix_contracts' LIMIT 1");$sourceId->execute([(int)$formRow['id']]);$recordId=(string)($sourceId->fetchColumn()?:'');if($recordId!==''){$data=$db->prepare('SELECT serial_number,notes FROM agreement_bitrix_source_data WHERE source_record_id=? LIMIT 1');$data->execute([$recordId]);$sourceData=$data->fetch(PDO::FETCH_ASSOC)?:[];$formRow=array_merge($formRow,$sourceData);}} $history=[];$historyRenewals=[]; if($cid>0&&isset($_GET['history'])&&ctype_digit((string)$_GET['history'])){ $hrow=latestAgreement($db,(int)$_GET['history'],$cid); @@ -202,7 +243,7 @@ } } ?>SLA & PSA Agreements

SLA & PSA Agreements

Open this tab from a Bitrix24 customer record.
Customer: · Bitrix company #
@@ -210,41 +251,56 @@
Business division
Agreement status — original Bitrix Yes/No, independent of expiry
+ +

Create/Edit is currently locked. It requires live REST field metadata, the additive reconciliation migration, verified synthetic permissions, and the explicit development write gates. No local-only agreement changes are allowed.

-
> +
>
- - - - - - - - -
+ + + + + + + + + + + +

Cancel editing

History: #

Close history
-

Original Bitrix imports have no recorded application edits until changed here. Creation, edits and renewals are logged for agreements managed in this app.

-

Renewed from agreement # · View previous agreement history

-
Later renewals
+

Original Bitrix imports have no recorded application edits until changed here. Creation, edits, and legacy agreement changes are logged for agreements managed in this app.

+

Previous agreement # · View previous agreement history

+
Subsequent agreements (legacy history)

No application changes have been recorded for this agreement yet.

— ·
Before
After

agreements shown

-
'Start','expiry'=>'Expiry','months'=>'Months left','days'=>'Total days left'] as $field=>$label):?> -
AgreementService EscalationStatusFinancing institutionCoverage / descriptionActions
Renewal of #
Expired by date
EditHistory -
+
'Start','expiry'=>'Expiry','months'=>'Months Left','days'=>'Days Left'] as $field=>$label):?> +
AgreementServiceType EscalationStatusFinancing institutionCoverage / descriptionActions
Previous agreement #
Expired by date
EditHistory +

No agreements match this selection. Check All agreements to see every record, including any with an unknown status.

+ +

Documents linked to agreements

+ +
( to ) +
+ +

No documents are linked to the agreements currently shown. Link or unlink files from the customer Documents tab.

+
+