public function findWorkflowCascading($firm_id, $status_id)
{
$firm = \Firm::model()->findByPk($firm_id);
$subspecialty_id = $firm->serviceSubspecialtyAssignment ? $firm->serviceSubspecialtyAssignment->subspecialty_id : null;
$criteria = new \CDbCriteria();
$criteria->addCondition('firm_id = ? OR firm_id IS NULL');
$criteria->order = 'firm_id DESC, episode_status_id DESC, subspecialty_id DESC';
$criteria->params = array($firm_id);
$workflows = self::model()->findAll($criteria);
if (!$workflows) {
throw new \CException('Cannot find any workflow rules');
}
$workflow = null;
foreach ($workflows as $possibleWorkflow) {
//episode and speciality must match what we have or be null, if that's not the case continue
if (!($possibleWorkflow->episode_status_id == $status_id || !$possibleWorkflow->episode_status_id) || !($possibleWorkflow->subspecialty_id == $subspecialty_id || !$possibleWorkflow->subspecialty_id)) {
continue;
}
if ($possibleWorkflow->episode_status_id == $status_id) {
//If the episode status matches return it
$workflow = $possibleWorkflow->workflow;
break;
} elseif ($possibleWorkflow->subspecialty_id === $subspecialty_id) {
//Otherwise the subspeciality should match
$workflow = $possibleWorkflow->workflow;
break;
} elseif (!$possibleWorkflow->episode_status_id && !$possibleWorkflow->subspecialty_id) {
//else we take the one where everything is null
$workflow = $possibleWorkflow->workflow;
break;
}
}
if (!$workflow) {
throw new \CException('Cannot find default workflow rule');
}
return $workflow;
}