<commit_before><?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once 'ilios_web_controller.php';

/**
 * @package Ilios
 *
 * Curriculum Inventory management controller.
 *
 * @see Ilios_CurriculumInventory_Exporter
 */
class Curriculum_Inventory_Manager extends Ilios_Web_Controller
{
    /**
     * The inventory exporter.
     * @var Ilios_CurriculumInventory_Exporter
     */
    protected $_exporter;

    /**
     * Constructor.
     */
    public function __construct ()
    {
        parent::__construct();
        // conditionally load all necessary DAOs
        if (! property_exists($this, 'clerkshipType')) {
            $this->load->model('Course_Clerkship_Type', 'clerkshipType', true);
        }
        if (! property_exists($this, 'inventory')) {
            $this->load->model('Curriculum_Inventory', 'inventory', true);
        }
        if (! property_exists($this, 'invReport')) {
            $this->load->model('Curriculum_Inventory_Report', 'invReport', true);
        }
        if (! property_exists($this, 'invAcademicLevel')) {
            $this->load->model('Curriculum_Inventory_Academic_Level', 'invAcademicLevel', true);
        }
        if (! property_exists($this, 'invInstitution')) {
            $this->load->model('Curriculum_Inventory_Institution', 'invInstitution', true);
        }
        if (! property_exists($this, 'invSequence')) {
            $this->load->model('Curriculum_Inventory_Sequence', 'invSequence', true);
        }
        if (! property_exists($this, 'invSequenceBlock')) {
            $this->load->model('Curriculum_Inventory_Sequence_Block', 'invSequenceBlock', true);
        }

        if (! property_exists($this, 'invExport')) {
            $this->load->model('Curriculum_Inventory_Export', 'invExport', true);
        }

        if (! property_exists($this, 'program')) {
            $this->load->model('Program', 'program', true);
        }

        $this->_exporter = new Ilios_CurriculumInventory_Exporter($this);
    }

    /**
     * Default action.
     *
     * This action prints the curriculum inventory manager for a requested report.
     * If no report is requested, then an bare page will be printed with just the controls to create and search reports.
     *
     * It accepts the following query string parameters:
     *    'report_id' ... (optional) the report id.
     */
    public function index ()
    {
        $lang = $this->getLangToUse();

        $data = array();
        $data['lang'] = $lang;
        $data['institution_name'] = $this->config->item('ilios_institution_name');
        $data['user_id'] = $this->session->userdata('uid');

        // authorization check
        if (! $this->session->userdata('has_admin_access')) {
            $this->_viewAccessForbiddenPage($lang, $data);
            return;
        }

        $schoolId = $this->session->userdata('school_id');
        $schoolRow = $this->school->getRowForPrimaryKeyId($schoolId);

        if (! isset($schoolRow)) {
            $msg = $this->languagemap->getI18NString('general.error.school_not_found', $lang);
            show_error($msg);
            return;
        }

        $payload = array(); // data container
        $academicLevels = array();

        $programs = $this->program->getAllPublishedProgramsWithSchoolId($schoolId);
        $payload['programs'] = $programs;

        $reports = $this->invReport->getList($schoolId); // existing reports
        $data['reports'] = $reports;

        $reportId = $this->input->get('report_id');

        if ($reportId) {
            $report = $this->invReport->getRowForPrimaryKeyId($reportId);
            if (! $report) {
                $msg = $this->languagemap->getI18NString('curriculum_inventory.report.load.general_error', $lang);
                show_error($msg);
                return;
            }
            $program = $this->program->getRowForPrimaryKeyId($report->program_id);
            $report->is_finalized = $this->invExport->exists($reportId);
            $report->program = $program;
            $academicLevels = array_values($this->invAcademicLevel->getLevels($report->report_id));
            $linkedCourses = $this->inventory->getLinkedCourses($report->report_id);
            $linkableCourses = $this->inventory->getLinkableCourses($report->year, $schoolId, $report->report_id);
            $courses = array_merge($linkedCourses, $linkableCourses);
            $sequenceBlocks = $this->invSequenceBlock->getBlocks($report->report_id);
            $sequenceBlocks = $this->invSequenceBlock->buildSequenceBlockHierarchy($sequenceBlocks);

            $payload['report'] = $report;
            $payload['academic_levels'] = $academicLevels;
            $payload['courses'] = $courses;
            $payload['sequence_blocks'] = $sequenceBlocks;
        }
        // JSONifiy the entire report data array and push it to the view
        $data['payload'] = Ilios_Json::encodeForJavascriptEmbedding($payload, Ilios_Json::JSON_ENC_SINGLE_QUOTES);
        // push the academic levels separately to simplify the "add sequence block" dialog's form population.
        $data['academic_levels'] = $academicLevels;

        $this->load->view('curriculum_inventory/index', $data);
    }

    /**
     * This action creates a new curriculum inventory report for a given academic year and program.
     *
     * It expects the following POST parameters:
     *    'report_year' ... the academic year
     *    'report_name' ... the report name
     *    'report_description' ... the report description
     *    'program_id' ... the program id
     *
     * This method prints out a result object as JSON-formatted text.
     *
     * On success, the object contains a property "report_id" which contains the id of the newly created report.
     * On failure, the object contains a property "error", which contains an error message.
     */
    public function create ()
    {
        $lang = $this->getLangToUse();
        $rhett = array();

        $data = array();
        $data['lang'] = $lang;
        $data['institution_name'] = $this->config->item('ilios_institution_name');
        $data['user_id'] = $this->session->userdata('uid');

        // authorization check
        if (! $this->session->userdata('has_admin_access')) {
            $this->_printAuthorizationFailedXhrResponse($lang);
            return;
        }

        $year = (int) $this->input->post('report_year');
        $reportName = $this->input->post('report_name');
        $reportDescription = $this->input->post('report_description');
        $programId = (int) $this->input->post('program_id');

        //
        // create new inventory report for the given academic year
        //

        // check if a curriculum inventory report already exists
        $invReport = $this->invReport->getByAcademicYearAndProgram($year, $programId);
        if (isset($invReport)) {
            $this->_printErrorXhrResponse('curriculum_inventory.create.error.already_exists', $lang);
            return;
        }

        $startYear = $year;
        $endYear = $startYear + 1;
        // create start/end date for the report
        // @todo make hardwired start/end day/month configurable
        $startDate = new DateTime();
        $startDate->setDate($startYear, 7, 1);
        $endDate = new DateTime();
        $endDate->setDate($endYear, 6, 30);

        // create a new curriculum inventory report and associated entities (academic levels, sequence etc.)
        // @todo running db transactions in the controller - BAD! refactor this out.
        $this->db->trans_start();
        $reportId = $this->invReport->create($year, $programId, $reportName, $reportDescription, $startDate, $endDate);
        $this->invAcademicLevel->createDefaultLevels($reportId);
        $this->invSequence->create($reportId);
        $this->db->trans_complete();
        if (false === $this->db->trans_status()) {
            $this->_printErrorXhrResponse('curriculum_inventory.create.error.general', $lang);
            return;
        }

        $rhett['report_id'] = $reportId;

        header("Content-Type: text/plain");
        echo json_encode($rhett);
    }

    /**
     * This action updates an existing report from user input.
     *<commit_msg>elaborated on one todo item, removed another unnecessary one.<commit_after><?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once 'ilios_web_controller.php';

/**
 * @package Ilios
 *
 * Curriculum Inventory management controller.
 *
 * @see Ilios_CurriculumInventory_Exporter
 */
class Curriculum_Inventory_Manager extends Ilios_Web_Controller
{
    /**
     * The inventory exporter.
     * @var Ilios_CurriculumInventory_Exporter
     */
    protected $_exporter;

    /**
     * Constructor.
     */
    public function __construct ()
    {
        parent::__construct();
        // conditionally load all necessary DAOs
        if (! property_exists($this, 'clerkshipType')) {
            $this->load->model('Course_Clerkship_Type', 'clerkshipType', true);
        }
        if (! property_exists($this, 'inventory')) {
            $this->load->model('Curriculum_Inventory', 'inventory', true);
        }
        if (! property_exists($this, 'invReport')) {
            $this->load->model('Curriculum_Inventory_Report', 'invReport', true);
        }
        if (! property_exists($this, 'invAcademicLevel')) {
            $this->load->model('Curriculum_Inventory_Academic_Level', 'invAcademicLevel', true);
        }
        if (! property_exists($this, 'invInstitution')) {
            $this->load->model('Curriculum_Inventory_Institution', 'invInstitution', true);
        }
        if (! property_exists($this, 'invSequence')) {
            $this->load->model('Curriculum_Inventory_Sequence', 'invSequence', true);
        }
        if (! property_exists($this, 'invSequenceBlock')) {
            $this->load->model('Curriculum_Inventory_Sequence_Block', 'invSequenceBlock', true);
        }

        if (! property_exists($this, 'invExport')) {
            $this->load->model('Curriculum_Inventory_Export', 'invExport', true);
        }

        if (! property_exists($this, 'program')) {
            $this->load->model('Program', 'program', true);
        }

        $this->_exporter = new Ilios_CurriculumInventory_Exporter($this);
    }

    /**
     * Default action.
     *
     * This action prints the curriculum inventory manager for a requested report.
     * If no report is requested, then an bare page will be printed with just the controls to create and search reports.
     *
     * It accepts the following query string parameters:
     *    'report_id' ... (optional) the report id.
     */
    public function index ()
    {
        $lang = $this->getLangToUse();

        $data = array();
        $data['lang'] = $lang;
        $data['institution_name'] = $this->config->item('ilios_institution_name');
        $data['user_id'] = $this->session->userdata('uid');

        // authorization check
        if (! $this->session->userdata('has_admin_access')) {
            $this->_viewAccessForbiddenPage($lang, $data);
            return;
        }

        $schoolId = $this->session->userdata('school_id');
        $schoolRow = $this->school->getRowForPrimaryKeyId($schoolId);

        if (! isset($schoolRow)) {
            $msg = $this->languagemap->getI18NString('general.error.school_not_found', $lang);
            show_error($msg);
            return;
        }

        $payload = array(); // data container
        $academicLevels = array();

        $programs = $this->program->getAllPublishedProgramsWithSchoolId($schoolId);
        $payload['programs'] = $programs;

        $reports = $this->invReport->getList($schoolId); // existing reports
        $data['reports'] = $reports;

        $reportId = $this->input->get('report_id');

        if ($reportId) {
            $report = $this->invReport->getRowForPrimaryKeyId($reportId);
            if (! $report) {
                $msg = $this->languagemap->getI18NString('curriculum_inventory.report.load.general_error', $lang);
                show_error($msg);
                return;
            }
            $program = $this->program->getRowForPrimaryKeyId($report->program_id);
            $report->is_finalized = $this->invExport->exists($reportId);
            $report->program = $program;
            $academicLevels = array_values($this->invAcademicLevel->getLevels($report->report_id));
            $linkedCourses = $this->inventory->getLinkedCourses($report->report_id);
            $linkableCourses = $this->inventory->getLinkableCourses($report->year, $schoolId, $report->report_id);
            $courses = array_merge($linkedCourses, $linkableCourses);
            $sequenceBlocks = $this->invSequenceBlock->getBlocks($report->report_id);
            $sequenceBlocks = $this->invSequenceBlock->buildSequenceBlockHierarchy($sequenceBlocks);

            $payload['report'] = $report;
            $payload['academic_levels'] = $academicLevels;
            $payload['courses'] = $courses;
            $payload['sequence_blocks'] = $sequenceBlocks;
        }
        // JSONifiy the entire report data array and push it to the view
        $data['payload'] = Ilios_Json::encodeForJavascriptEmbedding($payload, Ilios_Json::JSON_ENC_SINGLE_QUOTES);
        // push the academic levels separately to simplify the "add sequence block" dialog's form population.
        $data['academic_levels'] = $academicLevels;

        $this->load->view('curriculum_inventory/index', $data);
    }

    /**
     * This action creates a new curriculum inventory report for a given academic year and program.
     *
     * It expects the following POST parameters:
     *    'report_year' ... the academic year
     *    'report_name' ... the report name
     *    'report_description' ... the report description
     *    'program_id' ... the program id
     *
     * This method prints out a result object as JSON-formatted text.
     *
     * On success, the object contains a property "report_id" which contains the id of the newly created report.
     * On failure, the object contains a property "error", which contains an error message.
     */
    public function create ()
    {
        $lang = $this->getLangToUse();
        $rhett = array();

        $data = array();
        $data['lang'] = $lang;
        $data['institution_name'] = $this->config->item('ilios_institution_name');
        $data['user_id'] = $this->session->userdata('uid');

        // authorization check
        if (! $this->session->userdata('has_admin_access')) {
            $this->_printAuthorizationFailedXhrResponse($lang);
            return;
        }

        $year = (int) $this->input->post('report_year');
        $reportName = $this->input->post('report_name');
        $reportDescription = $this->input->post('report_description');
        $programId = (int) $this->input->post('program_id');

        //
        // create new inventory report for the given academic year
        //

        // check if a curriculum inventory report already exists
        $invReport = $this->invReport->getByAcademicYearAndProgram($year, $programId);
        if (isset($invReport)) {
            $this->_printErrorXhrResponse('curriculum_inventory.create.error.already_exists', $lang);
            return;
        }

        $startYear = $year;
        $endYear = $startYear + 1;
        // create start/end date for the report
        // @todo replace hardwired start/end day/month with values configured for academic years once issue #565 has been resolved.
        $startDate = new DateTime();
        $startDate->setDate($startYear, 7, 1);
        $endDate = new DateTime();
        $endDate->setDate($endYear, 6, 30);

        // create a new curriculum inventory report and associated entities (academic levels, sequence etc.)
        $this->db->trans_start();
        $reportId = $this->invReport->create($year, $programId, $reportName, $reportDescription, $startDate, $endDate);
        $this->invAcademicLevel->createDefaultLevels($reportId);
        $this->invSequence->create($reportId);
        $this->db->trans_complete();
        if (false === $this->db->trans_status()) {
            $this->_printErrorXhrResponse('curriculum_inventory.create.error.general', $lang);
            return;
        }

        $rhett['report_id'] = $reportId;

        header("Content-Type: text/plain");
        echo json_encode($rhett);
    }

    /**
     * This action updates an existing report from user input.
     *
{'fraction_non_alphanumeric': 0.1382927417410176, 'fraction_numerical': 0.001386544489992766, 'mean_word_length': 2.6563808684152526, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 205, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5010528', 'n_tokens_mistral': 4711, 'n_tokens_neox': 4620, 'n_words': 972}