diff --git a/app/plugins/CoreEnroller/src/Controller/AttributeCollectorsController.php b/app/plugins/CoreEnroller/src/Controller/AttributeCollectorsController.php index e9640bd71..7f9397fa9 100644 --- a/app/plugins/CoreEnroller/src/Controller/AttributeCollectorsController.php +++ b/app/plugins/CoreEnroller/src/Controller/AttributeCollectorsController.php @@ -60,6 +60,8 @@ public function dispatch(string $id) { attributes: array_diff_key($this->request->getData(), ['petition_id' => true, 'token' => true]) ); + $this->persistPetitionCouIdFromCollectedAttributes((int)$petition->id); + // On success, indicate the step is completed and generate a redirect // to the next step @@ -100,4 +102,51 @@ public function dispatch(string $id) { $this->render('/Standard/dispatch'); } + + /** + * If the Attribute Collector collected a COU for later context (eg approvals), + * persist Petition.cou_id during dispatch (not during finalization). + * + * @since COmanage Registry v5.2.0 + * @param int $petitionId + * @return void + */ + protected function persistPetitionCouIdFromCollectedAttributes(int $petitionId): void { + $petitionAttributesTable = $this->AttributeCollectors + ->EnrollmentAttributes + ->PetitionAttributes; + + // Fetch all petition attributes + enrollment attribute data + $attrs = $petitionAttributesTable + ->find() + ->where(['PetitionAttributes.petition_id' => $petitionId]) + ->contain(['EnrollmentAttributes']) + ->toArray(); + + // Find the first "cou_id" with a non-empty value + // NOTE: Attribute Collector configuration can include multiple COU attributes/values, but the + // Petition record has only a single `cou_id` column. By convention/assumption we therefore + // select the first non-empty collected `cou_id` and ignore any additional values. + $couAttr = null; + foreach ($attrs as $pa) { + if ( + !empty($pa->enrollment_attribute) + && ($pa->enrollment_attribute->attribute ?? null) === 'cou_id' + && ($pa->value ?? null) !== null + && ($pa->value ?? null) !== '' + ) { + $couAttr = $pa; + break; + } + } + + if(!$couAttr) { + return; + } + + $petitionsTable = $this->fetchTable('Petitions'); + $petition = $petitionsTable->get($petitionId); + $petition->cou_id = (int)$couAttr->value; + $petitionsTable->saveOrFail($petition); + } }