<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once "Modul_Controller.php";

class FollowUp extends Modul_Controller
{
    public function __construct()
    {
        parent::__construct();

        /* ----------------------------------------------------------------------------------
         * loader dari main CI
         * ----------------------------------------------------------------------------------*/
        //arrPrintWebs($this->session->login);
        $this->load->helper("he_stepping");
        $this->load->helper("he_access_right");
        $this->load->library("MobileDetect");
        $this->load->library("Curl");
        $this->load->helper("he_session_replacer");
        $this->load->model("Mdls/MdlCurrency");
        $this->load->helper('he_angka');


        $this->load->config("heWebs");
        $maintenanceTransaksi = $this->config->item("maintenanceTransaksi");
        $this->transaksiMaintenance = $maintenanceTransaksi != null && $maintenanceTransaksi == true ? true : false;
        $maintenanceOption = $this->config->item("maintenanceOptions");
        $this->transaksiMaintenanceMsg = isset($maintenanceOption[1]) ? $maintenanceOption[1] : array();
        $this->transaksiMaintenanceMsgStock = isset($maintenanceOption[2]) ? $maintenanceOption[2] : array();
        $this->transaksiMaintenanceStock = $this->config->item("maintenanceTransaksiStock");


        $this->load->model("Mdls/MdlMongoMother");
        $this->mongoTableList = array(
            "main" => "transaksi",
            "mainValues" => "transaksi_values",
            "detail" => "transaksi_data",
            "detailValues" => "transaksi_data_values",
            "sign" => "transaksi_sign",
            "extras" => "transaksi_extstep",
            "registry" => "transaksi_registry",
        );

        $this->load->model("MdlTransaksi");
        // cekBiru($this->configPath);
        // cekBiru($configPath);
        // cekKuning(url_segment(3));
    }

    /* -------------------------------------------------------------------------------------
     * create_form ada di index
     * lanjut_ke -> preview -> save
     * -------------------------------------------------------------------------------------*/
    public function index()
    {
        $configUi = $this->configUi;

        $this->jenisTrName = isset($configUi[$this->jenisTr]['steps'][1]['label']) ? $configUi[$this->jenisTr]['steps'][1]['label'] : "unnamed";
        $this->allSteps = isset($configUi[$this->jenisTr]['steps']) ? $configUi[$this->jenisTr]['steps'] : array();
        $heTransaksi_ui = (null != $configUi) ? $configUi : array();
        if (sizeof($heTransaksi_ui) > 0) {
            $this->template = isset($heTransaksi_ui[$this->jenisTr]) ? base_url() . "template/" . $heTransaksi_ui[$this->jenisTr]['template'] . ".html" : "";
        }
        else {
            die("konfigurasi transaksi belum ditentukan @" . __LINE__);
        }
        matiHere(__METHOD__);
        // arrPrint($configUi);
        //        arrPrint($this->session->login);
        //===pageView options
        if (!isset($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'])) {
            $viewModeConfig = isset($configUi[$this->jenisTr]['defaultViewMode']) ? $configUi[$this->jenisTr]['defaultViewMode'] : "list";
            $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] = isset($_GET['viewMode']) ? $_GET['viewMode'] : $viewModeConfig;
        }
        $viewModeSpec = array(
            "icon" => "",
            "url" => "",
        );
        $thisPage = base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3);
        switch ($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode']) {
            case "list":
                $viewModeSpec = array(
                    "icon" => "	glyphicon glyphicon-th-large",
                    "url" => $thisPage . "?viewMode=thumbnail",
                );
                break;
            case "thumbnail":
                $viewModeSpec = array(
                    "icon" => "glyphicon glyphicon-align-justify",
                    "url" => $thisPage . "?viewMode=list",
                );
                break;
        }
        $viewModeSwitch = "<a href='javascript:void(0)' onclick=\"location.href='" . $viewModeSpec['url'] . "';\"><span class='" . $viewModeSpec['icon'] . "'></span></a>";


        // if (!isset($this->session->login['id'])) {
        //     redirect(base_url() . "Login");
        // }
        //        arrprint($this->uri->segment_array());
        //        arrprint($this->session->login);

        $mb = New MobileDetect();
        $isMob = $mb->isMobile();


        $cCode = "_TR_" . $this->jenisTr;
        if (isset($_SESSION[$cCode]['mode']) && array_key_exists("edit", $_SESSION[$cCode]['mode'])) {
            $selectedID = $_SESSION[$cCode]['mode']['edit'];
            $title = "";
            $subTitle = "Edit " . $configUi[$this->jenisTr]["steps"][1]['label'];
            //            cekHitam("biruuu");
        }
        elseif (isset($_SESSION[$cCode]['mode']) && array_key_exists("cancel", $_SESSION[$cCode]['mode'])) {
            $selectedID = $_SESSION[$cCode]['mode']['cancel'];
            $title = "" . $configUi[$this->jenisTr]["steps"][1]['label'];
            $subTitle = "" . $configUi[$this->jenisTr]["steps"][1]['label'];
        }
        else {
            $title = $configUi[$this->jenisTr]["label"];
            $subTitle = $configUi[$this->jenisTr]["steps"][1]['label'];
        }

        //-----------------------------------------------------
        $arrJenisTrCek = array("587",
            "687",
            "1587",
            "1687"
        );
        if (in_array($this->jenisTr, $arrJenisTrCek)) {
            $transaksiName = isset($configUi[$this->jenisTr]['label']) ? $configUi[$this->jenisTr]['label'] : NULL;
            $subplace = isset($configUi[$this->jenisTr]['steps'][1]['subplace']) ? $configUi[$this->jenisTr]['steps'][1]['subplace'] : NULL;
            if ($subplace != NULL) {
                if (($subplace == "branch") && ($this->session->login['gudang_id'] < 0)) {
                    //                    cekPink("SESUAI");
                }
                elseif (($subplace == "branch_ng") && ($this->session->login['gudang_id'] > 0)) {
                    //                    cekPink("SESUAI NOT GOOD");
                }
                else {
                    $msg = "Anda tidak memiliki kewenangan untuk membuat request $transaksiName";
                    $alerts = array(
                        "type" => "warning",
                        "html" => "$msg",
                    );
                    echo swalAlert($alerts);
                    //                    echo toAlert($msg);
                    redirecResult(base_url() . get_class($this) . "/index/" . $this->uri->segment(3));
                }
            }
        }

        //-----------------------------------------------------

        /* ---------------------------------------------------------------------
         * nilai dikirim ke he_cart_helper
         * ---------------------------------------------------------------------*/
        $initMasterValues = array(
            "olehID" => my_id(),
            "olehName" => my_name(),
            "placeID" => my_cabang_id(),
            "placeName" => my_cabang_nama(),
            "cabangID" => my_cabang_id(),
            "cabangName" => my_cabang_nama(),
            "gudangID" => my_gudang_id(),
            "gudangName" => my_gudang_nama(),
            "tokoID" => my_toko_id(),
            "jenisTr" => $this->jenisTr,
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $configUi[$this->jenisTr]['steps'][1]['target'],
            "jenisTrName" => $configUi[$this->jenisTr]['label'],
            "stepNumber" => 1,
            "stepCode" => $configUi[$this->jenisTr]['steps'][1]['target'],
            "dtime" => dtimeNow(),
            "fulldate" => dtimeNow("Y-m-d"),
        );
        heInitGates_he_cart($this->jenisTr, $initMasterValues);

        $globalTemplate = "";
        $globalTemplate .= "<span>";
        $globalTemplateUrl = base_url() . "Selectors/_globalTemplate/globalTemplate/$cCode";
        if (isset($_SESSION[$cCode]['globalTemplate']) && $_SESSION[$cCode]['globalTemplate'] == 1) {
            $globalTemplate .= "
                <label class='radio-inline'>
                  <input type='radio' onchange=\"console.log('$globalTemplateUrl/0');top.$('#result').load('$globalTemplateUrl/0');\" name='globalTemplate'>Default
                </label>
                <label class='radio-inline'>
                  <input type='radio' onchange=\"console.log('$globalTemplateUrl/1');top.$('#result').load('$globalTemplateUrl/1');\" name='globalTemplate' checked>WideView
                </label>
                ";
        }
        else {
            $globalTemplate .= "
                <label class='radio-inline'>
                  <input type='radio' onchange=\"console.log('$globalTemplateUrl/0');top.$('#result').load('$globalTemplateUrl/0');\" name='globalTemplate' checked>Default
                </label>
                <label class='radio-inline'>
                  <input type='radio' onchange=\"console.log('$globalTemplateUrl/1');top.$('#result').load('$globalTemplateUrl/1');\" name='globalTemplate'>WideView
                </label>
                ";
        }
        $globalTemplate .= "</span>";


        $connectTo = isset($configUi[$this->jenisTr]['connectTo']) ? $configUi[$this->jenisTr]['connectTo'] : "";
        $stepHistoryFields = isset($configUi[$this->jenisTr]['shortStepHistoryFields']) ? $configUi[$this->jenisTr]['shortStepHistoryFields'] : array();


        $pairRegistries = isset($configUi[$this->jenisTr]['pairRegistries']) ? $configUi[$this->jenisTr]['pairRegistries'] : array();
        $historyFields = $configUi[$this->jenisTr]['shortHistoryFields'];
        $glanceHistoryFields = isset($configUi[$this->jenisTr]['glanceHistoryFields']) ? $configUi[$this->jenisTr]['glanceHistoryFields'] : array("nomer" => "receipt no");
        $itemAddConfig = isset($configUi[$this->jenisTr]['itemAddConfig']) ? $configUi[$this->jenisTr]['itemAddConfig'] : true;
        $glanceHistoryFields2 = array("nomer" => "receipt no"); //init;
        $selectorProcessor = base_url() . $configUi[$this->jenisTr]['selectorProcessor'] . "/$this->jenisTr";
        $uploadConfig = isset($configUi[$this->jenisTr]['uploadFields']) ? $configUi[$this->jenisTr]['uploadFields'] : array();
        //        arrPrint($uploadConfig);

        if ($isMob) {
            $historyFields = isset($configUi[$this->jenisTr]['compactHistoryFields']) ? $configUi[$this->jenisTr]['compactHistoryFields'] : array();
        }
        //
        //region lookup on-going transactions
        $arrayOnprogress = array();
        $progressFields = $historyFields;
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";
        $steps = $configUi[$this->jenisTr]['steps'];
        //endregion

        //region menambah supplier/customer (kalau berwenang)
        $pihakModel = isset($configUi[$this->jenisTr]['pihakModel']) ? $configUi[$this->jenisTr]['pihakModel'] : "";
        $pihakMainModel = isset($configUi[$this->jenisTr]['pihakModelMain']) ? $configUi[$this->jenisTr]['pihakModelMain'] : "";
        $dataAccess = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel] : array(
            "viewers" => array(),
            "creators" => array(),
            "creatorAdmins" => array(),
            "updaters" => array(),
            "updaterAdmins" => array(),
            "deleters" => array(),
            "deleterAdmins" => array(),
            "historyViewers" => array(),
        );
        $dataLabel = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel]['label'] : $pihakModel;
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $addPihakStr = "";
        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $pihakModel);
        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $dataLabel . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        }
                                        );";
                $addPihakStr = "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' title='add $dataLabel' data-toggle='tooltip' data-placement='right' class='btn btn-default' onclick=\"$addClick\">
                                            <span class='fa fa-user-plus'>                                            
                                             </span>
                                        </a>
                                </span>";
            }
        }
        //endregion

        // cekMerah($this->jenisTr);
        // arrPrint($configUi);
        //region menambah item/produk (kalau berwenang)
        $pihakModel = $configUi[$this->jenisTr]['selectorModel'];
        $dataAccess = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel] : array(
            "viewers" => array(),
            "creators" => array(),
            "creatorAdmins" => array(),
            "updaters" => array(),
            "updaterAdmins" => array(),
            "deleters" => array(),
            "deleterAdmins" => array(),
            "historyViewers" => array(),
        );
        $dataLabel = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel]['label'] : $pihakModel;
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $addItemStr = "";
        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $pihakModel);
        //        arrprint($dataAccess['creators']);
        $relPihak = "?cCode=$cCode&pId=yes";
        // cekHere($relPihak);
        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $dataLabel . "',
                                        message: $('<div></div>').load('" . $addLink . $relPihak . "'),
                                        draggable:true,
                                        closable:true,
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        }
                                        );";
                $addItemStr = "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' title='add $dataLabel' data-toggle='tooltip' data-placement='right' class='btn btn-default' onclick=\"$addClick\">
                                            <span class='fa fa-plus-circle'>                                            
                                             </span>
                                        </a>
                                </span>";
            }
        }
        //endregion


        //
        //region lookup on-going from connected requests
        $progress2Fields = array();
        $arrayOnprogress2 = array();
        $needToClear = false;
        //endregion

        // cekMerah($this->jenisTr);

        //region incomplete step antar cabang
        $arrayOnProgressView = array();
        $arrayOnProgressView = $this->viewIncompleteStepAntarCabang();
        if (sizeof($stepHistoryFields) > 0) {
            $stepHistoryFields['state'] = "status";
        }
        //endregion

        // cekLime($this->jenisTr);
        //
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $registryFields = $tr->getRegistryFields();
        $tr->addFilter("transaksi.toko_id='" . $this->session->login['toko_id'] . "'");
        //        $tr->addFilter("transaksi.gudang_id='" . $this->session->login['gudang_id'] . "'");
        $tr->addFilter("transaksi.jenis_master='" . $this->jenisTr . "'");
        //        $tr->addFilter("transaksi.next_step_code=''");
        $tmpHist = $tr->lookupRecentHistories(5)->result();

        $arrayHistory = array();
        if (sizeof($tmpHist) > 0) {
            $arrTransID = array();
            $arrTransTopID = array();
            $arrIdsHist = array();
            $arrTransHist = array();
            $tmpReg_result = array();
            foreach ($tmpHist as $row) {
                $arrTransID[] = $row->id;
                $arrTransTopID[] = $row->id_top;

                if ($row->ids_his != "") {
                    $hist = blobDecode($row->ids_his);
                    foreach ($hist as $hisSpec) {
                        $arrIdsHist[$row->id][$hisSpec['step']] = array(
                            "step" => $hisSpec['step'],
                            "trID" => $hisSpec['trID'],
                            "nomer" => $hisSpec['nomer'],
                        );
                        $arrTransHist[] = $hisSpec['trID'];
                    }
                }

                $filterField = array("main");
                if (sizeof($registryFields) > 0) {
                    foreach ($registryFields as $param) {
                        if (in_array($param, $filterField)) {
                            $tmpReg_result[$row->id][$param] = blobDecode($row->$param);
                        }
                    }
                }
            }

            //            $trReg = new MdlTransaksi();
            //            $trReg->setFilters(array());
            //            $trReg->addFilter("param='main'");
            //            $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
            //            $tmpReg = $trReg->lookupRegistries()->result();
            //            if (sizeof($tmpReg) > 0) {
            //                foreach ($tmpReg as $regRow) {
            //                    $param = $regRow->param;
            //                    $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
            //                }
            //            }

            if (sizeof($arrIdsHist) > 0) {
                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("id in ('" . implode("','", $arrTransHist) . "')");
                $tmpTransHist = $tr->lookupAll()->result();


                if (sizeof($tmpTransHist) > 0) {
                    foreach ($tmpTransHist as $histSpec) {
                        $tmpTransHist_result[$histSpec->id] = array(
                            "oleh_id" => $histSpec->oleh_id,
                            "oleh_nama" => $histSpec->oleh_nama,
                        );
                    }
                }

                foreach ($arrIdsHist as $trID => $histSpec) {
                    foreach ($histSpec as $step => $detailSpec) {
                        if (array_key_exists($detailSpec['trID'], $tmpTransHist_result)) {
                            $detailSpec['main'] = $tmpTransHist_result[$detailSpec['trID']];
                        }
                        $arrTransMainHist[$trID][$step] = $detailSpec;
                    }
                }
            }
            $numb = 0;
            foreach ($tmpHist as $row) {
                if (sizeof($pairRegistries) > 0) {
                    if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->id]))) {
                        foreach ($tmpReg_result[$row->id] as $param => $eReg) {
                            foreach ($eReg as $k => $v) {
                                if (!isset($row->$k)) {
                                    $row->$k = $v;
                                }
                            }
                        }
                    }
                }
                $tmp = array();
                $numb++;
                foreach ($historyFields as $fName => $fLabel) {
                    if (is_array($fLabel)) {
                        $hisStep = $fLabel['step'];
                        $hisKey = $fLabel['key'];

                        if (isset($row->ids_his)) {
                            $returnVal = showHistoriGlobalNumbers($row->ids_his, $hisStep, true);
                            if ($returnVal == "") {
                                $tmp[$fName] = "-";
                            }
                            else {
                                $tmp[$fName] = $returnVal;
                            }
                        }
                        else {
                            $tmp[$fName] = "-";
                        }
                    }
                    else {
                        $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : formatField($fName, 0);
                    }

                    if ($fName == "no") {
                        $tmp[$fName] = formatField($fName, $numb);
                    }
                }
                $arrayHistory[] = $tmp;
            }
        }
        //endregion


        //region lookup histories (swapJenis)
        $swapJenisTr = isset($configUi[$this->jenisTr]['requestCode']['masterCode']) ? $configUi[$this->jenisTr]['requestCode']['masterCode'] : array();
        $arrayHistoryR = array();
        if (sizeof($swapJenisTr)) {

            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            //            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
            //            $tr->addFilter("transaksi.gudang_id='" . $this->session->login['gudang_id'] . "'");
            $tr->addFilter("transaksi.jenis_master='" . $swapJenisTr . "'");
            $tmpHist = $tr->lookupRecentHistories(5)->result();

            if (sizeof($tmpHist) > 0) {
                $arrTransID = array();
                $arrTransTopID = array();
                $arrIdsHist = array();
                $arrTransHist = array();
                $tmpReg_result = array();
                foreach ($tmpHist as $row) {
                    $arrTransID[] = $row->id;
                    $arrTransTopID[] = $row->id_top;

                    if ($row->ids_his != "") {
                        $hist = blobDecode($row->ids_his);
                        foreach ($hist as $hisSpec) {
                            $arrIdsHist[$row->id][$hisSpec['step']] = array(
                                "step" => $hisSpec['step'],
                                "trID" => $hisSpec['trID'],
                                "nomer" => $hisSpec['nomer'],
                            );
                            $arrTransHist[] = $hisSpec['trID'];
                        }
                    }

                    $filterField = array("main");
                    if (sizeof($registryFields) > 0) {
                        foreach ($registryFields as $param) {
                            if (in_array($param, $filterField)) {
                                $tmpReg_result[$row->id][$param] = blobDecode($row->$param);
                            }
                        }
                    }
                }

                //                $trReg = new MdlTransaksi();
                //                $trReg->setFilters(array());
                //                $trReg->addFilter("param='main'");
                //                $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
                //                $tmpReg = $trReg->lookupRegistries()->result();
                //                if (sizeof($tmpReg) > 0) {
                //                    foreach ($tmpReg as $regRow) {
                //                        $param = $regRow->param;
                //                        $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                //                    }
                //                }

                foreach ($tmpHist as $row) {
                    if (sizeof($pairRegistries) > 0) {
                        if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$row->id]))) {
                            foreach ($tmpReg_result[$row->id] as $param => $eReg) {
                                foreach ($eReg as $k => $v) {
                                    if (!isset($row->$k)) {
                                        $row->$k = $v;
                                    }
                                }
                            }
                        }
                    }
                    $tmp = array();
                    foreach ($historyFields as $fName => $fLabel) {
                        $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : formatField($fName, 0);
                    }
                    $arrayHistoryR[] = $tmp;
                }
            }
        }

        //endregion
        //


        $barcodeSettings = isset($configUi[$this->jenisTr]['barcodeSettings']) ? $configUi[$this->jenisTr]['barcodeSettings'] : array();

        //==mobile scan (if possible)
        $mobScanStr = sizeof($barcodeSettings) ? "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' class='btn btn-default' onclick=\"getScan()\">
                                            <span class='fa fa-qrcode'>
                                             </span>
                                        </a>
                                </span>" : "";


        //region external tool
        if (isset($configUi[$this->jenisTr]['extTool'])) {
            $extToolConfig = $configUi[$this->jenisTr]['extTool'];
            $srcVar = $extToolConfig['sentParam'];
            $srcField = $extToolConfig['sentField'];
            $externSrc = $extToolConfig['externSrc'];
            $rawParam = array();
            $backUrl = base_url() . $extToolConfig['backUrl'];
            if (isset($_SESSION[$cCode][$srcVar]) && sizeof($_SESSION[$cCode][$srcVar]) > 0) {

                foreach ($_SESSION[$cCode][$srcVar] as $id => $rSpec) {
                    if (isset($rSpec[$srcField])) {
                        $rawParam[$id] = $rSpec[$srcField];
                    }
                }
            }
            //arrPrint($rawParam);die();
            if (sizeof($rawParam) > 0) {
                $param = base64_encode(serialize($rawParam));
                $backUrl = base64_encode(serialize($backUrl));
                $extTool = "<a class='btn btn-default' href='javascript:void(0)' onclick=\"window.open('" . $extToolConfig['url'] . "?param=$param&extern=" . $_SESSION[$cCode]['main'][$externSrc] . "&back=$backUrl','wTool');\" >" . $extToolConfig['label'] . "</a>";
            }
            else {
                $extTool = "<a class='btn btn-default' disabled>" . $extToolConfig['label'] . "</a>";
            }

        }
        else {
            //cekMerah("extTool doesnt exist");
            $extTool = "";
        }
        //endregion

        $allowTmpSave = isset($configUi[$this->jenisTr]['allowTmpSave']) ? $configUi[$this->jenisTr]['allowTmpSave'] : false;

        // $this->allSteps
        // cekKuning($this->jenisTr);
        // cekBiru($configUi[$this->jenisTr]);
        // $modulpath = base_url() . $this->modul . DIRECTORY_SEPARATOR;
        // cekMerah($this->modulPath);
        // cekHijau($this->configPath . "|" . MODUL_TEMPLATE_PATH . "|" . $configUi[$this->jenisTr]["template"]);
        $data = array(
            // "mode"                       => $this->uri->segment(2),

            "mode" => "createForm",
            "modeedit" => isset($_SESSION[$cCode]['mode']) && array_key_exists("edit", $_SESSION[$cCode]['mode']) || isset($_SESSION[$cCode]['mode']) && array_key_exists("cancel", $_SESSION[$cCode]['mode']) ? "_off" : "",
            "modeeditopt" => isset($_SESSION[$cCode]['mode']) && array_key_exists("edit", $_SESSION[$cCode]['mode']) || isset($_SESSION[$cCode]['mode']) && array_key_exists("cancel", $_SESSION[$cCode]['mode']) ? "data-toggle='tooltip' data-placement='top' data-original-title='tidak bisa ganti CUSTOMER pada mode EDIT/CANCEL'" : "",
            "isMobile" => $isMob,
            "errMsg" => $this->session->errMsg,
            "globalTemplate" => isset($globalTemplate) ? $globalTemplate : "",
            // "template"                   => isset($_SESSION[$cCode]['globalTemplate']) && $_SESSION[$cCode]['globalTemplate'] == 1 ? str_replace(".html", "_v2.html", $configUi[$this->jenisTr]["template"]) : $configUi[$this->jenisTr]["template"],
            "template" => MODUL_TEMPLATE_PATH . $configUi[$this->jenisTr]["template"],
            //            "title" => $configUi[$this->jenisTr]["label"],
            "title" => $title,
            //            "subTitle" => $configUi[$this->jenisTr]["steps"][1]['label'],
            "subTitle" => $subTitle,
            "jenisTr" => $this->jenisTr,
            "jenisTransaksi" => $this->jenisTr,
            "trName" => $configUi[$this->jenisTr]["label"],
            //            "selectorCaller" => base_url() . "_selectorItem/" . $configUi[$this->jenisTr]["selectorCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["selectorModel"],
            //            "selectorCaller" => base_url() . $configUi[$this->jenisTr]["selectorCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["selectorModel"],
            "selectorCaller" => isset($_SESSION[$cCode]['main']['pihakMdlName']) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["selectorCaller"] . "/$this->jenisTr/" . $_SESSION[$cCode]['main']['pihakMdlName'] : ($this->modulPath . $configUi[$this->jenisTr]["selectorCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["selectorModel"]),
            "selectorLabel" => $configUi[$this->jenisTr]["selectorLabel"],
            "selectorCaller2" => isset($configUi[$this->jenisTr]["selectorCaller2"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["selectorCaller2"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["selectorModel2"] : "",
            "selectorLabel2" => isset($configUi[$this->jenisTr]["selectorLabel2"]) ? $configUi[$this->jenisTr]["selectorLabel2"] : "",
            "selectorExternLabel" => isset($configUi[$this->jenisTr]["selectorLabel2"]) ? $configUi[$this->jenisTr]["selectorLabel2"] : "",
            // ---
            "pihakCaller" => base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModel"],
            "pihakCaller2" => isset($configUi[$this->jenisTr]["pihakCaller2"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakCaller2"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModel2"] : "",
            "pihakCaller3" => isset($configUi[$this->jenisTr]["pihakCaller3"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakCaller3"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModel3"] : "",
            "pihakExternCaller" => isset($configUi[$this->jenisTr]["pihakExternCaller"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakExternCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModelExtern"] : "",
            "pihakCallerDelete" => base_url() . $this->modul . DIRECTORY_SEPARATOR . "Selectors/_processPihak/remove/$this->jenisTr",
            "pihakMainCallerDelete" => base_url() . $this->modul . DIRECTORY_SEPARATOR . "Selectors/_processPihakMain/remove/$this->jenisTr",
            "pihakMainCallerRulesDelete" => base_url() . $this->modul . DIRECTORY_SEPARATOR . "Selectors/_processPihakMainRules/remove/$this->jenisTr",
            //tambahan pihak rules misal ppn optional didepan
            "pihakMainCallerRules" => isset($configUi[$this->jenisTr]["pihakMainCallerRules"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakMainCallerRules"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModelMainRules"] : "",
            "pihakMainLabelRules" => isset($configUi[$this->jenisTr]["pihakMainLabelRules"]) ? $configUi[$this->jenisTr]["pihakMainLabelRules"] : "",
            //tambahan pihak main
            "pihakMainCaller" => isset($configUi[$this->jenisTr]["pihakMainCaller"]) ? base_url() . $this->modul . DIRECTORY_SEPARATOR . $configUi[$this->jenisTr]["pihakMainCaller"] . "/$this->jenisTr/" . $configUi[$this->jenisTr]["pihakModelMain"] : "",
            "pihakMainLabel" => isset($configUi[$this->jenisTr]["pihakMainLabel"]) ? $configUi[$this->jenisTr]["pihakMainLabel"] : "",
            "pihakLabel" => isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] . "(" . $configUi[$this->jenisTr]["pihakLabel"] . ")" : $configUi[$this->jenisTr]["pihakLabel"],
            "pihakLabel2" => isset($_SESSION[$cCode]['main']['pihak2Name']) ? $_SESSION[$cCode]['main']['pihak2Name'] . "(" . $configUi[$this->jenisTr]["pihakLabel2"] . ")" : (isset($configUi[$this->jenisTr]["pihakLabel2"]) ? $configUi[$this->jenisTr]["pihakLabel2"] : ""),
            "pihakLabel3" => isset($_SESSION[$cCode]['main']['pihak3Name']) ? $_SESSION[$cCode]['main']['pihak3Name'] . "(" . $configUi[$this->jenisTr]["pihakLabel3"] . ")" : (isset($configUi[$this->jenisTr]["pihakLabel3"]) ? $configUi[$this->jenisTr]["pihakLabel3"] : ""),
            "pihakExternLabel" => isset($_SESSION[$cCode]['main']['pihakExternLabel']) ? $_SESSION[$cCode]['main']['pihakExternName'] . "(" . $configUi[$this->jenisTr]["pihakExternLabel"] . ")" : isset($configUi[$this->jenisTr]["pihakExternLabel"]) ? $configUi[$this->jenisTr]["pihakExternLabel"] : "",
            // history
            "arrayHistoryLabels" => $historyFields,
            "arrayHistory" => $arrayHistory + $arrayHistoryR,
            "arrayProgressLabels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progressFields : $glanceHistoryFields,
            "arrayProgress2Labels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progress2Fields : $glanceHistoryFields2,
            "arrayOnProgress" => $arrayOnprogress,
            "arrayOnProgress2" => $arrayOnprogress2,
            "reqFormTarget" => isset($reqFormTarget) ? $reqFormTarget : "",
            //            "strPaymentMethod" => $strPaymentMethod,
            "extTool" => $extTool,
            // "columnRecorderTarget"       => base_url() . $this->modul . DIRECTORY_SEPARATOR . "ValueGate/recordColumn/" . $this->jenisTr . "/",
            "columnRecorderTarget" => base_url() . $this->modul . DIRECTORY_SEPARATOR . "ValueGate/recordColumn/" . $this->jenisTr . "/",
            "defaultDescription" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "allowJoin" => isset($configUi[$this->jenisTr]["steps"][1]['allowJoin']) && $configUi[$this->jenisTr]["steps"][1]['allowJoin'] == true ? $configUi[$this->jenisTr]["steps"][1]['allowJoin'] : false,
            "allowTmpSave" => $allowTmpSave,
            "needToClear" => $needToClear,
            "addPihakStr" => $addPihakStr,
            "addItemStr" => $addItemStr,
            "mobScanStr" => $mobScanStr,
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4),
            "viewMode" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'],
            "viewModeSwitch" => $viewModeSwitch,
            "barcodeSettings" => $barcodeSettings,
            "selectorProcessor" => $selectorProcessor,
            // ----------------------
            "onprogressViewTitle" => "<span class='fa fa-eye'></span> show incomplete step " . $configUi[$this->jenisTr]["label"],
            "onprogressViewSubTitle" => "<span class='text-black'>(daftar transaksi yang masih stanby di cabang tujuan)</span>",
            "arrayOnProgressView" => $arrayOnProgressView,
            "stepHistoryFields" => $stepHistoryFields,
            "uploadConfig" => $uploadConfig,
            "allSteps" => $this->allSteps,
            "submit_button_target" => $this->modul . "/Transaksi/validate/",
        );

        // arrPrint($data);
        $this->load->view("transaksi", $data);

    }

    public function followupPrePreview()
    {
        $no = rtrim($this->uri->segment(5), "-");
        //        $targetStepNum = $this->uri->segment(4);
        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = blobEncode(current_url());
//        cekHere(":: $no ::");

        // region mengunci transaksi by $no dan userID
        if ($this->session->login['ghost'] == 0) {

            $this->load->model("Mdls/MdlLockerTransaksi");
            $lt = New MdlLockerTransaksi();
            $lt->addFilter("transaksi_id='$no'");
            $ltTmp = $lt->lookupAll()->result();
            if (sizeof($ltTmp) == 0) {
                $ltActive = array(
                    "state" => "active",
                    "produk_id" => "$no",
                    "transaksi_id" => "$no",
                    "cabang_id" => $this->session->login['cabang_id'],
                    "oleh_id" => 0,
                    "oleh_nama" => "",
                    "jenis" => "transaksi",
                    "jenis_locker" => "transaksi",
                    "jumlah" => "0",
                    "gudang_id" => "0",
                );
                $ltHold = array(
                    "state" => "hold",
                    "produk_id" => "$no",
                    "transaksi_id" => "$no",
                    "cabang_id" => $this->session->login['cabang_id'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "jenis" => "transaksi",
                    "jenis_locker" => "transaksi",
                    "jumlah" => "1",
                    "gudang_id" => "0",
                );

                // insert ke tabel locker transaksi
                $lt->addData($ltActive) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
                $lt->addData($ltHold) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
            }
            else {
                $byUpdateHold = array();
                $totalUpdateHold = 0;
                $insertHold = true;
                foreach ($ltTmp as $ltSpec) {
                    if (($ltSpec->state == "hold") && ($ltSpec->jumlah == "1")) {
                        $insertHold = false;
                        break;
                    }
                    elseif (($ltSpec->state == "hold")) {
                        $totalUpdateHold += isset($ltSpec->jumlah) ? $ltSpec->jumlah : 0;
                        $byUpdateHold[] = $ltSpec->oleh_id;
                    }
                }
                if ($insertHold == true) {
                    if (($totalUpdateHold == 0) && (in_array($this->session->login['id'], $byUpdateHold))) {
                        $ltHold = array(
                            "jumlah" => "1",
                        );
                        $ltWhere = array(
                            "state" => "hold",
                            "produk_id" => "$no",
                            "transaksi_id" => "$no",
                            "jenis" => "transaksi",
                            "jenis_locker" => "transaksi",
                            "oleh_id" => $this->session->login['id'],
                        );
                        $lt->updateData($ltWhere, $ltHold);
                    }
                    else {
                        //                    cekPink("total HOLDnya 0 dan saya BELUM pernah HOLD transaksi ini");
                        $ltHold = array(
                            "state" => "hold",
                            "produk_id" => "$no",
                            "transaksi_id" => "$no",
                            "cabang_id" => $this->session->login['cabang_id'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "jenis" => "transaksi",
                            "jenis_locker" => "transaksi",
                            "jumlah" => "1",
                            "gudang_id" => "0",
                        );
                        $lt->addData($ltHold) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
                    }

                    $ltActive = array(
                        "jumlah" => "0",
                    );
                    $ltWhere = array(
                        "state" => "active",
                        "produk_id" => "$no",
                        "transaksi_id" => "$no",
                        "jenis" => "transaksi",
                        "jenis_locker" => "transaksi",
                    );
                    $lt->updateData($ltWhere, $ltActive);
                }
                else {
                    //                cekPink("sudah ada yang HOLD");
                }
            }
        }
        // endregion


        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tmpTr = $tr->lookupJoined();
        cekBiru($this->db->last_query());
        //endregion


        $cancelPackingId = isset($tmpTr[0]->cancel_packing_source_id) ? $tmpTr[0]->cancel_packing_source_id : 0;
        $tmpTrCancelPacking = array();
        $id_top_source_cancel_packing = array();
        if ($cancelPackingId > 0) {
            $tr->setFilters(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $cancelPackingId)) . ")");
            $tmpTrCancelPacking = $tr->lookupJoined();
            $id_top_source_cancel_packing = $tmpTrCancelPacking[0]->id_top;
        }


        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            $sCtr = 0;
            foreach ($tmpSign as $row) {
                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }


        $rawItems = array();
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items2" => array(),
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            if (!isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = array();
            }
            //endregion

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber] : null;
            //            $masterID = isset($tmpTr[0]->referensi_id) && $tmpTr[0]->referensi_id > 0 ? $tmpTr[0]->referensi_id : $tmpTr[0]->transaksi_id;
            $measurementDetails = isset($this->configUi[$this->jenisTr]["receiptMesurementRows"]) ? $this->configUi[$this->jenisTr]["receiptMesurementRows"] : array();
            $validatePaymentLocker = isset($this->configUi[$this->jenisTr]["validatePaymentSource"][$stepNumber]) ? $this->configUi[$this->jenisTr]["validatePaymentSource"][$stepNumber] : array();
            $itemsChild = isset($this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fields']) ? $this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fields'] : array();//dipake detil pembelian aset
            $itemsChildGate = isset($this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['gate']) ? $this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['gate'] : array();//dipake detil pembelian aset/penambahan aset dari supplies sebagai switcer baca item atau main


            $referensiIDProject = $tmpTr[0]->referensi_id;
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


            //region periksa locker value;
            $tempLocker = array();
            $tempBtnUndo = array();
            if (sizeof($validatePaymentLocker) > 0) {
                $mdlName = "Mdls/" . $validatePaymentLocker;
                $this->load->model($mdlName);
                $l = new $validatePaymentLocker();
                $l->addFilter("transaksi_id='$no'");
                $l->addFilter("state='active'");
                $l->addFilter("nilai > 0");
                $tempLocker = $l->lookupAll()->result();
                //cekUngu($this->db->last_query() . " >> $validatePaymentLocker");
                //arrPrint($tempLocker);
                if (sizeof($tempLocker) > 0) {
                    $tempBtnUndo = array(
                        "allowedUndone" => false,//tidak boleh di undo/reject
                        "allowedFollow" => false,//boleh di followup
                    );
                }
                else {
                    //                    arrPrint($this->config->item('payment_source')[$this->jenisTr]);
                    //                    cekKuning(":: $currentStepNum ::");
                    $jnTarget = isset($this->config->item('payment_source')[$this->jenisTr][$currentStepNum][0]['jenisTarget']) ? $this->config->item('payment_source')[$this->jenisTr][$currentStepNum][0]['jenisTarget'] : "";
                    //                    cekHitam(":: ** $jnTarget ** ::");
                    $tempBtnUndo = array(
                        "allowedUndone" => true,// boleh di undo/reject
                        "allowedFollow" => true,//tidak boleh di followup
                        "label" => isset($this->configUi[$jnTarget]['label']) ? $this->configUi[$jnTarget]['label'] : "",
                    );
                }
            }


            //            arrPrint($tempLocker);
            //endregion


            //==periksa apakah ada ganjalan
            $trA = new MdlTransaksi();
            $extSteps = $trA->lookupExtSteps($masterID);
            if (sizeof($extSteps) > 0) {
                //                cekmerah("ada ganjalan step sebanyak " . sizeof($extSteps));
            }
            else {
                //                cekhijau("TAK ada ganjalan step");
            }
            $paySrcs = $trA->lookupPaymentSrcs($masterID, $this->jenisTr . "_");
            if (sizeof($paySrcs) > 0) {
                //                cekmerah("ada ganjalan paymentSrc sebanyak " . sizeof($paySrcs));
            }
            else {
                //                cekhijau("TAK ada ganjalan paymentSrc");
            }


            $allowEdit = isset($this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit']) ? $this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit'] : false;
            $allowCancel = isset($this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowCancel']) ? $this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowCancel'] : false;
            $editableFields = isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber] : array();


            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilterJoin("sub_step_number='" . $currentStepNum . "'");
            $tr->addFilterJoin("next_substep_code='" . $this->configUi[$this->jenisTr]['steps'][$stepNumber]['target'] . "'");
            $tr->addFilterJoin("next_substep_num='$stepNumber'");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTr = $tr->lookupJoined();
            cekHere("111");
            showLast_query("biru");
            //endregion


            //region valid subitem
            $tr->setFilters(array());
            $tr->setJoinedFilter(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");// $no adalah nomer SO project
//            $tr->addFilter("id in (" . implode(",", explode("-", $referensiIDProject)) . ")");// $referensiIDProject adalah nomer SO project
            // $tr->addFilterJoin("sub_step_number='" . $currentStepNum . "'");
            // $tr->addFilterJoin("next_substep_code='" . $this->configUi[$this->jenisTr]['steps'][$stepNumber]['target'] . "'");
            // $tr->addFilterJoin("next_substep_num='$stepNumber'");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTrSub = $tr->lookupJoinedSubItems();
//            showLast_query("hitam");
//            arrPrintPink($tmpTrSub);
//             matiHEre(sizeof($tmpTrSub));
            //endregion

            //region subitem3 bagian po service/ biaya-biaya
            $tr = new MdlTransaksi();
            $tr->setFilters(array());
            $tr->setJoinedFilter(array());
//            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilter("id in (" . implode(",", explode("-", $referensiIDProject)) . ")");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTrSub_item = $tr->lookupJoinedSubItems2();
            // arrPrint($tmpTrSub_item);
//             cekMerah($this->db->last_query());
//             matiHEre();
            //endregion

            // matiHEre("hiyaa");
            $id_top = isset($tmpTr[0]->id_top) ? $tmpTr[0]->id_top : "";
            if ($id_top != "") {
                $idTr = isset($tmpTr[0]->id) ? $tmpTr[0]->id : "";
                $trPack = new MdlTransaksi();
                $trPack->setFilters(array());
                $trPack->addFilter("id_top in (" . implode(",", explode("-", $id_top)) . ")");
                $trPack->addFilterJoin("valid_qty>0");
                $tmpTrPacked = $trPack->lookupJoined();
            }


            $tmpTrPrePacked = array();
            if (sizeof($id_top_source_cancel_packing) > 0) {
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("id_top in (" . implode(",", explode("-", $id_top_source_cancel_packing)) . ")");
                $trPrePack->addFilterJoin("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined();
            }
            else {
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("cancel_packing_source_id in (" . implode(",", explode("-", $no)) . ")");
                $trPrePack->addFilterJoin("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined();
            }

            $arrPreTmp__ = array();
            foreach ($tmpTrPrePacked as $y => $dd) {
                if (!isset($arrPreTmp__[$dd->jenis][$dd->produk_id])) {
                    $arrPreTmp__[$dd->jenis][$dd->produk_id] = 0;
                }
                $arrPreTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
            }

            $arrTmp__ = array();

            if (sizeof($tmpTrPacked) > 0) {
                foreach ($tmpTrPacked as $y => $dd) {
                    if (!isset($arrTmp__[$dd->jenis][$dd->produk_id])) {
                        $arrTmp__[$dd->jenis][$dd->produk_id] = 0;
                    }
                    $arrTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
                }
            }

            //region valid items
            $extractedItems = array();//==untuk urusan update transaksi referer
            $validItems = array();
            $validItemSends = array();
            $validItemReqCancels = array();
            $validItemCancels = array();
            $validItemPreCancels = array();
            $validItemSents = array();

            if (sizeof($tmpTr) > 0) {
                cekmerah("ada yang mau diekstrak (main)");
                foreach ($tmpTr as $row) {
                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    if (!isset($validItemCancels[$row->produk_id])) {
                        $validItemCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemReqCancels[$row->produk_id])) {
                        $validItemReqCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPackeds[$row->produk_id])) {
                        $validItemPackeds[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPreCancels[$row->produk_id])) {
                        $validItemPreCancels[$row->produk_id] = 0;
                    }

                    $validItems[$row->produk_id] += isset($row->valid_qty) ? $row->valid_qty : 0;
                    $validItemSends[$row->produk_id] += isset($arrTmp__['582spd'][$row->produk_id]) ? $arrTmp__['582spd'][$row->produk_id] : 0;
                    $validItemCancels[$row->produk_id] += isset($row->cancel_qty) ? $row->cancel_qty : 0;
                    $validItemReqCancels[$row->produk_id] += isset($row->req_cancel_qty) ? $row->req_cancel_qty : 0;
                    $validItemPreCancels[$row->produk_id] += isset($arrPreTmp__['1982'][$row->produk_id]) ? $arrPreTmp__['1982'][$row->produk_id] : 0;
                    $validItemPackeds[$row->produk_id] += isset($arrTmp__['582pkd'][$row->produk_id]) ? $arrTmp__['582pkd'][$row->produk_id] : 0;

                    if (!isset($extractedItems[$row->produk_id])) {
                        $extractedItems[$row->produk_id] = array();
                    }
                    $extractedItems[$row->produk_id][$row->id_detail] = array(
                        "id" => $row->id_detail,
                        "produk_id" => $row->produk_id,
                        "qty" => $row->produk_ord_jml,
                        "valid_qty" => $row->valid_qty,
                        "transaksi_id" => $row->transaksi_id,
                        "packed_qty" => isset($arrTmp__['582pkd'][$row->produk_id]) ? $arrTmp__['582pkd'][$row->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__['582spd'][$row->produk_id]) ? $arrTmp__['582spd'][$row->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$row->produk_id]) ? $arrPreTmp__['1982'][$row->produk_id] : 0,
                        "cancel_qty" => $row->cancel_qty,
                        "outstanding" => $row->produk_ord_jml - ($row->produk_ord_jml - $row->valid_qty),
                    );
                }
            }
            else {
                cekmerah("TIDAK ada yang mau diekstrak");
            }
            //endregion

            //region valid sub items
            $extractedSubItems = array();//==untuk urusan update transaksi referer
            $validSubItems = array();
            $validSubItemSends = array();
            $validSubItemReqCancels = array();
            $validSubItemCancels = array();
            $validSunItemPreCancels = array();
            if (sizeof($tmpTrSub) > 0) {
                cekmerah("ada yang mau diekstrak (sub)");
                foreach ($tmpTrSub as $rows) {
                    if (!isset($validSubItems[$rows->produk_id])) {
                        $validSubItems[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemSends[$rows->produk_id])) {
                        $validSubItemSends[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemCancels[$rows->produk_id])) {
                        $validSubItemCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemReqCancels[$rows->produk_id])) {
                        $validSubItemReqCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPackeds[$rows->produk_id])) {
                        $validSubItemPackeds[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPreCancels[$rows->produk_id])) {
                        $validSubItemPreCancels[$rows->produk_id] = 0;
                    }

                    $validSubItems[$rows->produk_id] += isset($rows->valid_qty) ? $rows->valid_qty : 0;
                    $validSubItemSends[$rows->produk_id] += isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0;
                    $validSubItemCancels[$rows->produk_id] += isset($rows->cancel_qty) ? $rows->cancel_qty : 0;
                    $validSubItemReqCancels[$rows->produk_id] += isset($rows->req_cancel_qty) ? $rows->req_cancel_qty : 0;
                    $validSubItemPreCancels[$rows->produk_id] += isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0;
                    $validSubItemPackeds[$rows->produk_id] += isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0;

                    if (!isset($extractedSubItems[$rows->produk_id])) {
                        $extractedSubItems[$rows->produk_id] = array();
                    }
                    $extractedSubItems[$rows->produk_id][$rows->id_sub_detail] = array(
                        "id" => $rows->id_sub_detail,
                        "produk_id" => $rows->produk_id,
                        "qty" => $rows->produk_ord_jml,
                        "valid_qty" => $rows->valid_qty,
                        "transaksi_id" => $rows->transaksi_id,
                        "packed_qty" => isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0,
                        "cancel_qty" => $rows->cancel_qty,
                        "outstanding" => $rows->produk_ord_jml - ($rows->produk_ord_jml - $rows->valid_qty),
                        "dikirim_qty" => $rows->produk_ord_diterima,
                    );
                }
            }
            //endregion

            //region valid sub items2 biaya dari PO service
            $extractedSubItems2 = array();//==untuk urusan update transaksi referer
            $validSubItems2 = array();
            $validSubItemSends2 = array();
            $validSubItemReqCancels2 = array();
            $validSubItemCancels2 = array();
            $validSubItemPreCancels2 = array();
            $validSubItemPackeds2 = array();
            if (sizeof($tmpTrSub_item) > 0) {
                foreach ($tmpTrSub_item as $rowSub) {
                    if (!isset($validSubItems2[$rowSub->produk_id])) {
                        $validSubItems2[$rowSub->produk_id] = 0;
                    }
                    if (!isset($validSubItemSends2[$rowSub->produk_id])) {
                        $validSubItemSends2[$rowSub->produk_id] = 0;
                    }
                    if (!isset($validSubItemCancels2[$rowSub->produk_id])) {
                        $validSubItemCancels2[$rowSub->produk_id] = 0;
                    }
                    if (!isset($validSubItemReqCancels2[$rowSub->produk_id])) {
                        $validSubItemReqCancels2[$rowSub->produk_id] = 0;
                    }
                    if (!isset($validSubItemPackeds2[$rowSub->produk_id])) {
                        $validSubItemPackeds2[$rowSub->produk_id] = 0;
                    }
                    if (!isset($validSubItemPreCancels2[$rowSub->produk_id])) {
                        $validSubItemPreCancels2[$rowSub->produk_id] = 0;
                    }

                    $validSubItems2[$rowSub->produk_id] += isset($rowSub->valid_qty) ? $rowSub->valid_qty : 0;
                    $validSubItemSends2[$rowSub->produk_id] += isset($arrTmp__['582spd'][$rowSub->produk_id]) ? $arrTmp__['582spd'][$rowSub->produk_id] : 0;
                    $validSubItemCancels2[$rowSub->produk_id] += isset($rowSub->cancel_qty) ? $rowSub->cancel_qty : 0;
                    $validSubItemReqCancels2[$rowSub->produk_id] += isset($rowSub->req_cancel_qty) ? $rowSub->req_cancel_qty : 0;
                    $validSubItemPreCancels2[$rowSub->produk_id] += isset($arrPreTmp__['1982'][$rowSub->produk_id]) ? $arrPreTmp__['1982'][$rowSub->produk_id] : 0;
                    $validSubItemPackeds2[$rowSub->produk_id] += isset($arrTmp__['582pkd'][$rowSub->produk_id]) ? $arrTmp__['582pkd'][$rowSub->produk_id] : 0;

                    if (!isset($extractedSubItems2[$rowSub->produk_id])) {
                        $extractedSubItems2[$rowSub->produk_id] = array();
                    }
                    $extractedSubItems2[$rowSub->produk_id][$rowSub->id_sub_detail] = array(
                        "id" => $rowSub->id_sub_detail,
                        "produk_id" => $rowSub->produk_id,
                        "produk_nama" => $rowSub->produk_nama,
                        "produk_ord_harga" => $rowSub->produk_ord_hrg,
                        "qty" => $rowSub->produk_ord_jml,
                        "valid_qty" => $rowSub->valid_qty,
                        "transaksi_id" => $rowSub->transaksi_id,
                        "packed_qty" => isset($arrTmp__['582pkd'][$rowSub->produk_id]) ? $arrTmp__['582pkd'][$rowSub->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__['582spd'][$rowSub->produk_id]) ? $arrTmp__['582spd'][$rowSub->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$rowSub->produk_id]) ? $arrPreTmp__['1982'][$rowSub->produk_id] : 0,
                        "cancel_qty" => $rowSub->cancel_qty,
                        "outstanding" => $rowSub->produk_ord_jml - ($rowSub->produk_ord_jml - $rowSub->valid_qty),
                    );
                    $rsltItem3_sub[$rowSub->produk_id] = array(
                        "placeID" => $rowSub->cabang_id,
                        "gudangID" => 0,
                        "id" => $rowSub->id_sub_detail,
                        "produk_id" => $rowSub->produk_id,
                        "produk_nama" => $rowSub->produk_nama,
                        "produk_ord_harga" => $rowSub->produk_ord_hrg,
                        "produk_ord_jml" => $rowSub->produk_ord_jml,
                        "qty" => $rowSub->produk_ord_jml,
                        "valid_qty" => $rowSub->valid_qty,
                        "transaksi_id" => $rowSub->transaksi_id,
                        "produk_jenis" => $rowSub->produk_jenis,
                    );
                    if (isset($rowSub->produk_ord_stok) && ($rowSub->produk_ord_stok == 0)) {
                        if (!isset($mainProjectCost['project_cost'])) {
                            $mainProjectCost['project_cost'] = 0;
                        }
                        $mainProjectCost['project_cost'] += $rowSub->produk_ord_hrg;
                    }
                }
            }
            //endregion

            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            //            //cekMerah($this->db->last_query());
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //            arrPrint($detailValues);
            //endregion

            //region take from registries
            //==ambil value-gate
            $trr = new MdlTransaksi();
            $trr->setFilters(array());
            $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
            //            $tmpReg = $tr->lookupRegistriesByMasterID($trID)->result();
            $tmpReg = $trr->lookupDataRegistries()->result();
            //            $tmpReg = $tr->lookupRegistriesByMasterID($masterID)->result();
//             cekKuning($this->db->last_query());
//arrPrint($tmpReg);
//            matiHere(__LINE__);
            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $items3 = array();
            $items4 = array();
            $items5 = array();
            $items7 = array();
            $items3_sum = array();
            $items4_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();

            $masterGates = array();
            $childGates = array();
            $childGates2 = array();
            $childGates2_sum = array();
            $childGatesRsltItems = array();
            $childGatesRsltItems2 = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $childTableInParamsRsltItems = array();
            $childTableInParamsRsltItems2 = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $childTableInValueParamsRsltItems = array();
            $childTableInValueParamsRsltItems2 = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $mainInputs = array();
            $itemsKomposisi = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        switch ($key_reg) {
                            case "main"://
                                $main = $main + unserialize(base64_decode($val_reg));
                                break;
                            case "items"://
                                $items = $items + unserialize(base64_decode($val_reg));
                                break;
                            case "items2"://
                                $items2 = $items2 + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems"://
                                $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems2"://
                                $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "items2_sum"://
                                $items2_sum = $items2_sum + unserialize(base64_decode($val_reg));
                                break;
                            case "items3":
                                $items3 = $val_reg != "" ? $items3 + unserialize(base64_decode($val_reg)) : array();
                                break;
                            case "items4":
                                $items4 = $val_reg != "" ? $items4 + unserialize(base64_decode($val_reg)) : array();
                                break;
                            case "items5":
                                $items5 = $val_reg != "" ? $items5 + unserialize(base64_decode($val_reg)) : array();
                                break;
                            case "items7":
                                $items7 = $val_reg != "" ? $items7 + unserialize(base64_decode($val_reg)) : array();
                                break;
                            case "items3_sum"://
                                $items3_sum = $items3_sum + unserialize(base64_decode($val_reg));
                                break;
                            case "items4_sum"://
                                $items4_sum = $items4_sum + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master"://
                                $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail"://
                                $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems"://
                                $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems2"://
                                $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master_values"://
                                $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values"://
                                $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems"://
                                $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems2"://
                                $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_values"://
                                $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_fields"://
                                $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                                break;
                            case "main_elements"://
                                $mainElements = unserialize(base64_decode($val_reg));
                                break;
                            case "main_inputs"://
                                $mainInputs = unserialize(base64_decode($val_reg));
                                break;
                            case "items_komposisi"://
                                $itemsKomposisi = unserialize(base64_decode($val_reg));
                                break;
                        }
                    }
                }
            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion

//            cekHitam("Items From REGISTRY");
//            arrPrint($items);
//            arrPrint($items2_sum);
//            arrPrintwebs($items3_sum);
//            matiHEre(__LINE__);

            //region replacer Downpayment avail
            if (isset($mainInputs['dp'])) {
                if (isset($this->configUi[$this->jenisTr]["updateDownpayment"][$stepNumber])) {
                    //                    arrPrint($mainInputs);
                    $this->load->model("Coms/ComLockerValue");
                    $mi = new ComLockerValue();
                    $mi->addFilter("produk_id='" . $main['masterID'] . "'");
                    $mainInputAvail = $mi->fetchBalances("downpayment");
                    $lockerVal = $mainInputAvail[0]->nilai;
                    //                    $mainValTmp = reversePpn($mainInputs['dp'],"10");
                    $mainValTmp_dp = $main['dp_value'];
                    $mainValTmp_dp_ppn = $main['dp_ppn_value'];

                    if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                        cekOrange();
                        $validate = round($mainInputAvail[0]->nilai - $mainValTmp_dp, 2);
                        if ($lockerVal > 0) {
                            $valnew = $main['new_net1'] - $lockerVal > 0 ? 0 : $main['new_net1'];
                            $main['dp_value'] = $valnew;
                            $main['dp_ppn_value'] = $valnew * 10 / 100;
                        }
                        else {
                            $main['dp_value'] = 0;
                            $main['dp_ppn_value'] = 0;
                            //                        $main['valid_dp'] = 0;
                        }

                        if ($validate > 0) {
                            $mainInputs['dp'] = $mainInputAvail[0]->nilai;

                        }
                        else {
                            if ($validate < 0) {
                                if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                                    $main['downpayment'] = $mainInputs['dp'];
                                    $mainInputs['downpayment'] = $mainInputs['dp'];
                                    $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['dp_ppn_value'];

                                }
                                unset($mainInputs['dp']);
                                //                                cekhere("sini po");
                            }
                            //                        if(!isset($main['valid_dp'])){
                            //                            $main['valid_dp'] = $mainInputAvail[0]->nilai;
                            //                        }

                        }
                    }
                    else {
                        //                         $mainInputs['dp'] = 0;
                        $main['dp_value'] = 0;
                        $main['dp_ppn_value'] = 0;
                        unset ($mainInputs['dp']);
                    }

                    if (!isset($main['valid_dp'])) {
                        $main['valid_dp'] = $mainInputAvail[0]->nilai;
                    }
                }


            }
            else {
                if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                    $main['downpayment'] = $main['dp'];
                    $mainInputs['downpayment'] = $main['dp'];
                    //                    $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['nilai_tambah_ppn_out'];
                    $main['total_ui'] = $masterTableInValueParams['new_net1'] - $main['valid_dp'];
                    cekBiru($masterTableInValueParams['new_net1'] . " - " . $main['valid_dp']);
                }
                else {
                    if (isset($masterTableInValueParams['new_net1'])) {

                        $main['total_ui'] = $masterTableInValueParams['new_net1'];
                    }
                    else {
                        $main['total_ui'] = $masterTableInValueParams['nett1'];
                        $main['new_grand_ppn'] = $masterTableInValueParams['grand_ppn'];
                    }
                }
            }
            //endregion

            $masterReplacers = array(
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $masterTableInParams['jenis_top'],
                "harga" => 0,
                "masterID" => $masterID,
            );
            foreach ($masterReplacers as $key => $src) {
                $main[$key] = $src;
                $mainValues[$key] = $src;
                $masterGates[$key] = $src;
            }
            //             arrPrintWebs($items3);
//             matiHere(__LINE__);
            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();
            cekMerah("BEFORE");
            arrPrint($items);
            $itemChildData = array();
            if (sizeof($items) > 0) {
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";
                    if (array_key_exists($id, $validItems)) {
                        cekHijau("valid_ID:: $id");

                        if($id!=$xid){
                            $items[$id] = $items[$xid];
                            unset($items[$xid]);
                        }

                        $items[$id]['jml'] = $validItems[$id];
                        //                        $items[$id]['jml'] = $validItems[$id]-(int)$validItemPreCancels[$id];
                        $items[$id]['max_jml'] = $validItems[$id];
                        //                        $items[$id]['max_jml'] = $validItems[$id]-(int)$validItemPreCancels[$id];
                        $items[$id]['packed_jml'] = $validItemPackeds[$id];
                        $items[$id]['sent_jml'] = $validItemSends[$id];
                        $items[$id]['cancel_jml'] = $validItemCancels[$id];
                        $items[$id]['req_cancel_jml'] = $validItemPreCancels[$id];
                        if (sizeof($editableFields) > 0) {
                            foreach ($editableFields as $fName) {
                                $items[$id]["max_$fName"] = isset($iSpec[$fName]) ? $iSpec[$fName] : 0;
                            }
                        }

                        if (sizeof($measurementDetails)) {
                            if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
                                $selectedColl = $measurementDetails[$tipeSize];
                                foreach ($selectedColl as $colSelected => $tempHelper) {
                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        $items[$id][$newKey] = $heAngka($iSpec[$colSelected]);
                                    }
                                }
                            }
                        }


                        if ($subAmountConfig != null) {
                            $tmpEx = $cal->multiExplode($subAmountConfig);
                            if (sizeof($tmpEx) > 1) {
                                //                            echo lgShowAlert("menghitung subtotal pakai rumus $subAmountConfig di step ke # $stepNumber");
                                $newSrc = $subAmountConfig;
                                foreach ($tmpEx as $key2 => $val2) {
                                    if (isset($items[$id][$val2])) {
                                        $newSrc = str_replace($val2, $items[$id][$val2], $newSrc);
                                    }
                                    else {
                                        if (isset($tmp[$val2])) {
                                            $newSrc = str_replace($val2, $items[$val2], $newSrc);
                                        }
                                        else {
                                            $newSrc = str_replace($val2, "0", $newSrc);
                                        }
                                    }
                                }
                                $subtotal = $cal->calculate($newSrc);
                            }
                            else {
                                //                            echo lgShowAlert("memasang subtotal dari $subAmountConfig");
                                $subtotal = $items[$id][$subAmountConfig];
                            }
                        }
                        else {
                            //                        echo lgShowAlert("tidak mengapa-apakan subtotal");
                            $subtotal = 0;
                        }

                        $items[$id]['subtotal'] = $subtotal;
                        //region item child

                        if (sizeof($itemsChild) > 0 && ($itemsChildGate == 'detail')) {
                            //                        if (sizeof($itemsChild)  > 0 ) {
                            for ($x = 1; $x <= $validItems[$id]; $x++) {
                                foreach ($itemsChild as $col => $col_label) {
                                    $itemChildData[$id][$x][$col] = isset($items[$id][$col]) ? $items[$id][$col] : "";
                                    $itemChildData[$id][$x]["jml"] = 1;
                                    $itemChildData[$id][$x]["qty"] = 1;
                                    $itemChildData[$id][$x]["folders"] = $main['pihakMainID'];
                                }

                            }
                            //                            arrPrint($itemsChild);
                            //                        foreach ($itemsChild as )
                        }

                        //endregion
                        cekBiru("itemsKomposisi");
                        cekBiru($itemsKomposisi);
                        if (sizeof($itemsKomposisi) > 0) {
                            if (array_key_exists($id, $itemsKomposisi)) {
                                //                                cekBiru(":: ADA komposisinya yaitu $id ::");
                                foreach ($items2[$id] as $jenis_komposisi => $iiSpec) {
                                    foreach ($iiSpec as $ee => $eeSpec) {
                                        $komposisi = $itemsKomposisi[$id][$jenis_komposisi][$ee];
                                        // re-kalkulasi gerbang items2
                                        $items2[$id][$jenis_komposisi][$ee]['jml'] = $komposisi->jml * $validItems[$id];
                                        $items2[$id][$jenis_komposisi][$ee]['sub_nilai'] = $komposisi->nilai * $validItems[$id];
                                        cekhijau("pID: $id [], jml: " . $komposisi->jml . " validItems: " . $validItems[$id]);
                                    }
                                }
                            }
                        }


                    }
                    else {
                        cekHijau("NON valid_ID:: $xid $id");
                        unset($items[$xid]);
                        unset($items2[$xid]);
                        unset($childGates[$xid]);
                        unset($childTableInParams[$xid]);
                        unset($childTableInValueParams[$xid]);

                    }
                }
//                if (sizeof($itemsKomposisi) > 0) {
//                    $items2_sum = array();// supplies-nya...
//                    $items3_sum = array();// biaya-nya...
//                    foreach ($items2 as $pID => $pSpec) {
//                        foreach ($pSpec as $jenis => $jSpec) {
//                            foreach ($jSpec as $eSpec) {
//                                if ($jenis == "produk") {
//                                    if (!isset($items2_sum[$eSpec['id']])) {
//                                        $items2_sum[$eSpec['id']] = $eSpec;
//                                        $items2_sum[$eSpec['id']]['jml'] = 0;
//                                        $items2_sum[$eSpec['id']]['produk_ids'] = array();
//                                    }
//                                    $items2_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
//                                    $items2_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;
//
//                                    cekBiru("pID: " . $eSpec['id'] . " jml: " . $eSpec['jml']);
//                                }
//                                if ($jenis == "biaya") {
//                                    if (!isset($items3_sum[$eSpec['id']])) {
//                                        $items3_sum[$eSpec['id']] = $eSpec;
//                                        $items3_sum[$eSpec['id']]['jml'] = 0;
//                                        $items3_sum[$eSpec['id']]['sub_nilai'] = 0;
//                                        $items3_sum[$eSpec['id']]['produk_ids'] = array();
//                                    }
//                                    $items3_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
//                                    $items3_sum[$eSpec['id']]['sub_nilai'] += $eSpec['sub_nilai'];
//                                    $items3_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;
//                                }
//                            }
//                        }
//                    }
//                }
                //ini untuk subItems project
//                if (sizeof($items2_sum) > 0) {
//                    foreach ($items2_sum as $pid => $rSpec) {
//                        $id = $rSpec['id'];
//                        if (array_key_exists($id, $validSubItems)) {
//                            cekHitam("masuk " . $id);
//                            $items2_sum[$id]['jml'] = $validSubItems[$id];
//                            //                        $items[$id]['jml'] = $validItems[$id]-(int)$validItemPreCancels[$id];
//                            $items2_sum[$id]['max_jml'] = $validSubItems[$id];
//                            //                        $items[$id]['max_jml'] = $validItems[$id]-(int)$validItemPreCancels[$id];
//                            $items2_sum[$id]['packed_jml'] = $validSubItemPackeds[$id];
//                            $items2_sum[$id]['sent_jml'] = $validSubItemSends[$id];
//                            $items2_sum[$id]['cancel_jml'] = $validSubItemCancels[$id];
//                            $items2_sum[$id]['req_cancel_jml'] = $validSubItemPreCancels[$id];
//                            if (sizeof($editableFields) > 0) {
//                                foreach ($editableFields as $fName) {
//                                    $items2_sum[$id]["max_$fName"] = isset($rSpec[$fName]) ? $rSpec[$fName] : 0;
//                                }
//                            }
//
//                            if (sizeof($measurementDetails)) {
//                                if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
//                                    $selectedColl = $measurementDetails[$tipeSize];
//                                    foreach ($selectedColl as $colSelected => $tempHelper) {
//                                        foreach ($tempHelper as $newKey => $heAngka) {
//                                            $items2_sum[$id][$newKey] = $heAngka($rSpec[$colSelected]);
//                                        }
//                                    }
//                                }
//                            }
//
//
//                            if ($subAmountConfig != null) {
//                                $tmpEx = $cal->multiExplode($subAmountConfig);
//                                if (sizeof($tmpEx) > 1) {
//                                    //                            echo lgShowAlert("menghitung subtotal pakai rumus $subAmountConfig di step ke # $stepNumber");
//                                    $newSrc = $subAmountConfig;
//                                    foreach ($tmpEx as $key2 => $val2) {
//                                        if (isset($items[$id][$val2])) {
//                                            $newSrc = str_replace($val2, $items[$id][$val2], $newSrc);
//
//                                        } else {
//                                            if (isset($tmp[$val2])) {
//                                                $newSrc = str_replace($val2, $items[$val2], $newSrc);
//
//                                            } else {
//                                                $newSrc = str_replace($val2, "0", $newSrc);
//
//                                            }
//                                        }
//
//
//                                    }
//                                    $subtotal = $cal->calculate($newSrc);
//
//
//                                } else {
//                                    //                            echo lgShowAlert("memasang subtotal dari $subAmountConfig");
//                                    $subtotal = $items[$id][$subAmountConfig];
//
//                                }
//                            } else {
//                                //                        echo lgShowAlert("tidak mengapa-apakan subtotal");
//                                $subtotal = 0;
//
//                            }
//
//                            $items2_sum[$id]['subtotal'] = $subtotal;
//                        } else {
//                            cekHitam("TIDAK ADA ");
//                            unset($items2_sum[$id]);
//                        }
//
//                    }
//                }
            }
//            arrPrintWebs($items2_sum);
            // arrPrint($validSubItems2);
            // arrPrint($items3);
            cekHijau("AFTER");
             arrPrint($items);
//             matiHere(__LINE__);
            if (sizeof($itemsChild) > 0 && ($itemsChildGate == 'main')) {

                $fieldAlias = isset($this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fieldAlias']) ? $this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fieldAlias'] : $itemsChild;//dipake detil pembelian aset
                foreach ($fieldAlias as $col => $col_label) {
                    $itemChildData[$main['pihakMainRulesID']][1][$col] = isset($main[$col_label]) ? $main[$col_label] : "";
                }
                $itemChildData[$main['pihakMainRulesID']][1]["jml"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["qty"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["folders"] = $main['pihakID'];
                //                cekBiru("main");
            }
            if (isset($mainProjectCost) && sizeof($mainProjectCost) > 0) {
                $main = $main + $mainProjectCost;
            }
//arrPrint($main);
//arrPrint($items);
//            matiHere(__LINE__);
            //-----------------------------
            $handler = $this->modul . "/_projectItemEditor";
            $projectKomposisi = projectBom($main['pihakProjekID'], $handler);
            cekMerah($this->db->last_query());
//            $items2_sum = array();
//            if (sizeof($projectKomposisi) > 0) {
//                foreach ($projectKomposisi as $komposisiJenis => $komposisiSpec) {
//                    switch ($komposisiJenis) {
//                        case "produk":
//                            $items2_sum = $komposisiSpec;
//                            break;
//                        case "biaya":
//
//                            break;
//                    }
//                }
//            }
//arrPrintKuning($items2_sum);
//            mati_disini(__LINE__);
            //-----------------------------

            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "items3" => $items3,
                "items4" => $items4,
                "items5" => $items5,
                "items7" => $items7,
                "items3_sum" => $items3_sum,
                "items4_sum" => $items4_sum,
                "items_child" => $itemChildData,
                "rsltItems" => $rsltItems,
                "rsltItems2" => $rsltItems2,
                "rsltItems3_sub" => $rsltItem3_sub,
                "extractedItems" => $extractedItems,
                "extractedSubItems" => $extractedSubItems,
                "extractedSubItems2" => $extractedSubItems2,
                "tableIn_master" => $masterTableInParams,
                "tableIn_detail" => $childTableInParams,
                "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
                "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
                "tableIn_master_values" => $masterTableInValueParams,
                "tableIn_detail_values" => $childTableInValueParams,
                "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
                "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
                "main_add_values" => $masterAddValues,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "lockerPayment" => $tempBtnUndo,
                "items_komposisi" => $itemsKomposisi,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;
            }
            //endregion

            // matiHEre("hoop build item3 dan item3 sum broo");
            $this->load->helper("he_value_builder");

            //-------------------------------------------
            $receiptElementsInjector = isset($this->configUi[$this->jenisTr]["receiptElementsInjector"]) ? $this->configUi[$this->jenisTr]["receiptElementsInjector"] : array();
            if (sizeof($receiptElementsInjector) > 0) {
                foreach ($receiptElementsInjector as $eName => $eSpec) {

                    if ((!isset($main[$eName])) || (!isset($mainElements[$eName]))) {
                        //                        cekhitam("tidak kenal ppv, maka diinjeckkan...");
                        if (isset($eSpec['defaultValue'])) {//==cek apakah ada seting defaultValue
                            //                        cekmerah("default value for $eName is: " . $eSpec['defaultValue']);
                            $defValueSrc = $eSpec['defaultValue'];
                            switch ($eSpec['elementType']) {
                                case "dataModel":
                                    heFetchElement_modul($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $this->configUiJenis);
                                    break;
                                case "dataField":
                                    heRecordElement_modul($this->jenisTr, $eName, $defValueSrc, $this->configUiJenis);
                                    break;
                            }
                            $_SESSION[$cCode]['main_elements'][$eName]['autoSelect'] = true;
                        }
                        else {//==cek apakah pilihannya cuma satu
                            if (isset($eSpec['noPrefetch']) && $eSpec['noPrefetch'] == true) {

                            }
                            else {
                                //                            cekHere(__LINE__);
                                switch ($eSpec['elementType']) {
                                    case "dataModel":
                                        $amdlName = $eSpec['mdlName'];
                                        $this->load->model("Mdls/" . $amdlName);
                                        $labelSrc = $eSpec['labelSrc'];
                                        $keySrc = $eSpec['key'];
                                        $oo = new $amdlName();
                                        $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();
                                        //                                    cekHitam($amdlName);
                                        //                                    arrPrint($aFilter);
                                        if (sizeof($aFilter) > 0) {
                                            $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                                        }
                                        $tmpo = $oo->lookupAll()->result();
                                        if (sizeof($tmpo) == 1) {
                                            $usedKey = $eSpec['key'];
                                            $defValueSrc = $tmpo[0]->$usedKey;
                                            heFetchElement_modul($this->jenisTr, $eName, $eSpec['mdlName'], $defValueSrc, $this->configUiJenis);
                                        }
                                        break;
                                    case "dataField":
                                        break;
                                }
                            }
                        }

                        resetValues($this->jenisTr);
                        fillValues_he_value_builder($this->jenisTr, $this->uri->segment(7), $this->uri->segment(6), $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);

                    }
                }
            }

            //==init replacer
            //==recover nilai HARGA master
            $_SESSION[$cCode]['main']['harga'] = 0;
            $_SESSION[$cCode]['main']['currentID'] = $no;

            //==default load dari nota, maka dianggap langsung done
            $_SESSION[$cCode]['main']['status_4'] = 1;
            $_SESSION[$cCode]['main']['trash_4'] = 0;
            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                foreach ($_SESSION[$cCode]['items'] as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);

                }
            }

            if (!isset($_SESSION[$cCode]["main"]["ppnFactor"])) {
                $_SESSION[$cCode]["main"]["ppnFactor"] = $this->session->login['ppnFactor'];
            }
//            $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) && $_SESSION[$cCode]["main"]["ppnFactor"] == "11" ? $_SESSION[$cCode]["main"]["ppnFactor"] : matiHere("error on build values on PrePrev " . __LINE__ . " silahkan relogin");
            $ppnFactor = isset($_SESSION[$cCode]["main"]["ppnFactor"]) && $_SESSION[$cCode]["main"]["ppnFactor"] == "11" ? $_SESSION[$cCode]["main"]["ppnFactor"] : $this->session->login['ppnFactor'];

            //            $this->load->helper("he_value_builder");
            resetValues($this->jenisTr);
            fillValues_he_value_builder($this->jenisTr, $this->uri->segment(7), $this->uri->segment(6), $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis, $ppnFactor);
            fillValues_he_value_builder($this->jenisTr, $this->uri->segment(7), $this->uri->segment(6), $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis, $ppnFactor);

            //mati_disini("setelah fillValue, akan masuk ke followuppreview");
            $actionTarget = "top.BootstrapDialog.closeAll();
                             top.BootstrapDialog.show({
                                 title:'Followup preview',
                                 message: " . 'top.$' . "('<div></div>').load('" . MODUL_PATH . "FollowUp/followupPreview/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "?rawBuilderURL=$rawBuilderURL'),
                                 size:top.BootstrapDialog.SIZE_WIDE,
                                 type:top.BootstrapDialog.TYPE_DEFAULT,
                                 draggable:true,
                                 closable:false
                             });";

            echo "<script>top.close_holdon();$actionTarget</script>";

        }
        else {
            die(lgShowAlert("No such transaction. You may want to refresh the browser to re-fetch actual content."));
        }


    }

    public function followupPreview()
    {
        $starttime = microtime(true);
        $no = rtrim($this->uri->segment(5), "-");
        $targetStepNum = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $afterTargetStepNum = ($targetStepNum + 1);

        $rawPrevURL = blobEncode(current_url());
        $rawBuilderURL = $_GET['rawBuilderURL'];

        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilterJoin("sub_step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined();

        //region SIGNATURE
        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            //            cekkuning("ada signs");
            $sCtr = 0;
            foreach ($tmpSign as $row) {

                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }
        else {
            //            cekkuning("TAK ada signs");
        }
        //endregion


        $rejectAllAllowed = true;
        $partialCanceled = false;
        $rawItems = array();
        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $pelaku = $tmpTr[0]->oleh_id;
            $project_id = $tmpTr[0]->project_id;
            //            $cCode = "_TR_" . $this->jenisTr;
            $cCode = $this->cCode;

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "items2" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            if (!isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = array();
            }
            //endregion
            $detailSizeKey = isset($_SESSION[$cCode]['main_elements']['detilSize']['key']) ? $_SESSION[$cCode]['main_elements']['detilSize']['key'] : array();
            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum] : array();
            $itemLabels2 = isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][$targetStepNum] : array();
            $itemLabels3 = isset($this->configLayout[$this->jenisTr]['receiptDetailFields3'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields3'][$targetStepNum] : array();
//            $itemLabels3 = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields2'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields2'][$targetStepNum] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$targetStepNum] : array();
            $itemNumLabels2 = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$targetStepNum] : array();
            $itemNumLabels3 = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields3'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields3'][$targetStepNum] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$targetStepNum] : null;
            $noteEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartNoteEnabled'] == true ? true : false;
            $noteEditabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEditabled'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNoteEditabled'][$targetStepNum] : false;
            $noteAdditionalEditabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteAdditionalEditabled'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNoteAdditionalEditabled'][$targetStepNum] : false;
            $noteFollowupEditabled = isset($this->configUi[$this->jenisTr]['followupMainNote'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['followupMainNote'][$targetStepNum] : array();
            $noteType = isset($this->configUi[$this->jenisTr]['shoppingCartNoteType']) ? $this->configUi[$this->jenisTr]['shoppingCartNoteType'] : "text";
            $addRowsConfigs = isset($this->configUi[$this->jenisTr]['additionalRows']) ? $this->configUi[$this->jenisTr]['additionalRows'] : array();
            $imageEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartImageEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartImageEnabled'] == true ? true : false;
            $imageType = isset($this->configUi[$this->jenisTr]['shoppingCartImageType']) ? $this->configUi[$this->jenisTr]['shoppingCartImageType'] : "text";
            $showPoStatus = isset($this->configUi[$this->jenisTr]['showPoStatus']) ? $this->configUi[$this->jenisTr]['showPoStatus'] : array();
            $receiptDetail2_sub = isset($this->configUi[$this->jenisTr]["shopingCartDetailFields2_sub"][$currentStepNum]) ? $this->configUi[$this->jenisTr]["shopingCartDetailFields2_sub"][$currentStepNum] : array();
            // arrprint($itemLabels3);
            //             matiHere();
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);

            $regIds = $tmpTr[0]->indexing_registry == NULL ? array() : blobDecode($tmpTr[0]->indexing_registry);

            //
            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            //            //cekMerah($this->db->last_query());
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //            arrPrint($detailValues);
            //endregion

            //region take from registries
            $tr->setFilters(array());
            $tr->addFilter("trash='0'");
            //            if (sizeof($regIds) > 0) {
            //                $tmpReg = $tr->lookupDataBaseRegistries($regIds)->result();
            //            }
            //            else {
            //                $tmpReg = $tr->lookupDataRegistriesByMasterID($trID)->result();
            //            }
            $tmpReg = $tr->lookupDataRegistriesByMasterID($trID)->result();
            //cekLime($this->db->last_query());


            $endtime = microtime(true); // Bottom of page
            $val = $endtime - $starttime;

            $main = array();
            $items = array();
            $masterGates = array();
            $childGates = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $itemsKomposisi = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        switch ($key_reg) {
                            case "main"://
                                $main = unserialize(base64_decode($val_reg));
                                break;
                            case "items"://
                                $items = unserialize(base64_decode($val_reg));
                                break;
                            case "items2"://
                                $items2 = unserialize(base64_decode($val_reg));
                                break;
                            case "items2_sum"://
                                $items2_sum = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master"://
                                $masterTableInParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail"://
                                $childTableInParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master_values"://
                                $masterTableInValueParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values"://
                                $childTableInValueParams = unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_values"://
                                $masterAddValues = unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_fields"://
                                $masterAddFields = unserialize(base64_decode($val_reg));
                                break;
                            case "main_elements"://
                                $mainElements = unserialize(base64_decode($val_reg));
                                break;
                            case "items_komposisi"://
                                $itemsKomposisi = unserialize(base64_decode($val_reg));
                                break;
                        }
                    }
                }
            }
            else {
                die("Cannot read the registry entries from $masterID :: $trID !");
            }
            //endregion


            // region transaksi data masterID
            $tr = new MdlTransaksi();
            $detailTmp = $tr->lookupDetailTransaksiNoJenis($masterID)->result();
            $totalOrdJmlMaster = 0;
            foreach ($detailTmp as $detailSpec) {
                $totalOrdJmlMaster += $detailSpec->produk_ord_jml;
            }
            // endregion transaksi data masterID


            $arrTest = array();
            $totalValidQty = 0;
            $totalOrdJml = 0;
            $itemsKompositID = array();
            $itemsKompositName = array();
            foreach ($tmpTr as $row) {
                $id = $row->produk_id;
                $itemsKompositID[$id] = $id;
                $itemsKompositName[$id] = $row->produk_nama;

                $tmp = array();
                if (sizeof($itemLabels) > 0) {
                    foreach ($itemLabels as $key => $val) {
                        if (isset($_SESSION[$cCode]['tableIn_detail_values'][$row->produk_id][$key])) {
                            $fieldValue = $_SESSION[$cCode]['tableIn_detail_values'][$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                $fieldValue = $row->$key;
                            }
                            else {
                                $fieldValue = "";
                            }
                        }
                        $tmp[$key] = $fieldValue;
                    }
                }

                if (sizeof($showPoStatus) > 0) {
                    $ext_blob = isset($row->ext_blob) ? $row->ext_blob : array();
                    if (sizeof($ext_blob) > 0) {
                        //                        cekOrange(arrPrint(blobDecode($row->ext_blob)));
                    }
                }
                else {
                    //                    cekOrange("function: " . __FUNCTION__ . " LINE: " . __LINE__ . " " . $this->jenisTr);
                    //                    cekOrange("prd_id: " . $id);
                }

                //region calculate subtotal
                //                arrPrint($childGates[$id]);
                //===perhitungan subtotal
                $this->load->library("FieldCalculator");
                $cal = new FieldCalculator();


                if ($subAmountConfig != null) {

                    $arrChildGates[$id] = isset($childGates[$id]) ? $childGates[$id] : array();
                    $subtotal = makeValue($subAmountConfig, $arrChildGates[$id], $arrChildGates[$id], 0);
                }
                else {
                    $subtotal = 0;
                    //                    //cekHijau("subtotal NOL");
                }
                $tmp["subtotal"] = $subtotal;
                //endregion

                switch ($detailSizeKey) {
                    default:
                    case "ckd":

                        $replaceValue = array(
                            "volume_new" => isset($tmp['volume_gross']) ? $tmp['volume_gross'] : 0,
                            "sub_volume_new" => isset($tmp['sub_volume_gross']) ? $tmp['sub_volume_gross'] : 0,
                            "berat_new" => isset($tmp['berat_gross']) ? $tmp['berat_gross'] : "0",
                            "sub_berat_new" => isset($tmp['sub_berat_gross']) ? $tmp['sub_berat_gross'] : "0",
                        );
                        $tmp = array_replace($tmp, $replaceValue);

                        break;
                    case "cbu":
                        break;
                }

                $tmp = array();

                $rawItems[$row->produk_id] = $tmp;


                // region cek partial qty
                $totalValidQty += $row->valid_qty;
                $totalOrdJml += $row->produk_ord_jml;
                // endregion cek partial qty

            }

            if ($totalValidQty == $totalOrdJml) {
                $partialCanceled = true;
            }
            if ($totalOrdJmlMaster != $totalOrdJml) {
                cekMerah("LINE:: " . __LINE__ . " || totalOrdJmlMaster:: $totalOrdJmlMaster || totalOrdJml:: $totalOrdJml");
                $rejectAllAllowed = false;
            }
        }
        else {

            $errMsg = "the entry you are trying to access does not exist.<br>";
            $errMsg .= "you may try to refresh the browser by pressing F5 button on your keyboard.<br>";
            $errMsg .= "if this error re-occurs, please contact system developer.<br>";


            echo "<script>top.BootstrapDialog.closeAll();</script>";
            die(lgShowAlert($errMsg));
        }
        //endregion


        $items = array();
        $items2 = array();

        $jenisTr = $this->jenisTr;
        $_SESSION[$cCode]['main']['currentID'] = $no;


        //region deteksi tombol2 followup
        $currentStepIndex = array_search($currentStepNum, $signNumbers, true);

        //region blocking edit/reject/delete/approve/fullfillment jika ada locker transaksi (HOLD by userID lain)
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->addFilter("transaksi_id='$trID'");
        $lt->addFilter("state='hold'");
        $lt->addFilter("jumlah='1'");
        //        $lt->addFilter("oleh_id='" . $this->session->login['id'] . "'");
        $ltTmp = $lt->lookupAll()->result();
        // showLast_query("pink");
        $allowedActionByHold = "";
        if (sizeof($ltTmp) > 0) {
            if ($ltTmp[0]->oleh_id == $this->session->login['id']) {
                $allowedAction = true;
                // cekUngu("transaksi HOLD by yang login, bisa dilanjutkan");
            }
            else {
                $allowedAction = false;
                $allowedActionByHold = $ltTmp[0]->oleh_nama;
                cekUngu("transaksi HOLD by orang lain, TIDAK BISA dilanjutkan");
            }
        }
        else {
            $allowedAction = true;
            cekUngu("transaksi TIDAK di-HOLD, BISA dilanjutkan");
        }
        //endregion

        //        $doFollowupLink = MODUL_PATH . __CLASS__ . "/doFollowup/" . $this->jenisTr . "/$no/$targetStepNum/$currentStepNum";
        //        $doRevertAllLink = MODUL_PATH . __CLASS__ . "/doRevertAll/" . $this->jenisTr . "/$no/$currentStepNum";
        //        $doRevertLink = MODUL_PATH . __CLASS__ . "/doRevert/" . $this->jenisTr . "/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

        //region ========================approve, reject, undo====================================
        $origTCode = heGetOriginTCode($this->jenisTr);
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $userGroup_editElementAllowed = $this->config->item("userGroup_editElementAllowed") != NULL ? $this->config->item("userGroup_editElementAllowed") : array();
        $thisStepGID = isset($this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup'] : "";
        $nextStepGID = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup'] : "";
        $hideFollowUp = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp'] : false;
        $editElementAllowed = array_intersect($userGroup_editElementAllowed, $mems);
        $allowFollowup = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup'] : true;

        $preProcRevConfig = null != $this->config->item("hePreProcessors");
        $preCompRevConfig = null != $this->config->item("heComponents");

        $deleteSpec = array(
            "label" => "cannot delete",
            "targetUrl" => "",
            "warning" => "",
        );
        $undoSpec = array(
            "label" => "cannot undo",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpec = array(
            "label" => "cannot reject 1 step",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpecAll = array(
            "label" => "cannot reject all steps (".__LINE__.")",
            "targetUrl" => "",
            "warning" => "",
        );
        $approvalSpec = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $editSpec = array(
            "label" => "cannot edit",
            "targetUrl" => "",
            "warning" => "",
        );

        $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);

        //
        cekmerah("evPre: $evPre, evPos: $evPost, evCom: $evCom, currentStep: $currentStepNum, targetStep: $targetStepNum");
        cekKuning("origTCode: $origTCode, currentStepNum: $currentStepNum");
        cekKuning(placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "reject"));

        //==delete, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum == 1) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "delete", $this->configUiJenis)) {//$targetStepNum
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                        );
                    }
                    else {
                    }
                }
                else {
                    //                    cekungu("bukan credit");
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekUngu("delete pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                        );
                    }
                    else {
                        cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                    }
                }
            }
            else {
                //                if (!isset($_SESSION[$cCode]['main']['paymentMethod'])) {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                if ($evPre == null && $evPost == null && $evCom == null) {
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $deleteSpec = array(
                        "label" => "safely delete",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                    );
                }
                //                }
            }
        }
        else {
            cekmerah("NOT possible to delete, $pelaku != " . $this->session->login['id']);
        }

        //==undo, hanya yang mengotorisasi transaksi
        if (($origTCode == null) && ($currentStepNum > 1) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "undo", $this->configUiJenis)) {
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekHere("$evPre :: $evPost :: $evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                        );
                    }
                    else {
                        //                cekmerah("NOT allowed to REJECT");
                    }
                    //undonya
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                cekhijau("allowed to undo");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $undoSpec = array(
                            "label" => "undo last step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                        );
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                //                cekmerah("evPre: $evPre, evPos: $evPost, evCom: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                cekhijau("allowed to undo");
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $undoSpec = array(
                        "label" => "undo last step",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                    );
                }
                else {
                    //                cekmerah("NOT allowed to undo");
                }
                //                }
            }
        }
        else {
            //            cekmerah("NOT possible to undo");
        }

        cekMerah("SINI");
        //==reject, hanya yang memiliki hak akses selanjutnya
        if (($origTCode == null) && ($currentStepNum > 0) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "reject", $this->configUiJenis)) {//$targetStepNum
            //            cekHijau("ready to reject");
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                //                cekKuning("kena if locker payment");
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                        );

                        if ($rejectAllAllowed == true) {

                            $rejectionSpecAll = array(
                                "label" => "reject all steps",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                            );
                        }
                    }

                }
                else {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekUngu("pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                        );

                        if ($rejectAllAllowed == true) {
                            $rejectionSpecAll = array(
                                "label" => "reject all steps",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                            );
                        }
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);

                cekHitam("currentStepNum:: $currentStepNum" . " LINE " . __LINE__);
                cekHitam("evPreProcc: $evPre, evPostProcc: $evPost, evCom: $evCom" . " LINE " . __LINE__);
//                $evCom = 0;
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                    cekhijau("allowed to REJECT || LINE: " . __LINE__);
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $rejectionSpec = array(
                        "label" => "reject 1 step",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                    );
                    if ($rejectAllAllowed == true) {
                        $rejectionSpecAll = array(
                            "label" => "reject all steps",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                            "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                        );
                    }
                }
                else {
                    cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                }

//============ reject all untuk running project di pindah ke pembatalan transaksi ============
//                cekKuning("project_id:: $project_id");
                if ($currentStepNum == 3) { //project sudah running
//                    $allowedRejectProject = array(8, 11);
//                        if( in_array($project_id, $allowedRejectProject) ){
//                        cekHijau("project_id:: $project_id BOLEH DI REJECT");
//                        if ($rejectAllAllowed == true) {
//                            $rejectionSpecAll = array(
//                                "label" => "reject all steps",
//                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
//                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
//                            );
//                        }
//                    }
                }
                else {
//                    cekHitam($currentStepNum);
                    if ($currentStepNum <= 2) {
//                        matiHEre(__LINE__);
//                        if( in_array($project_id, $allowedRejectProject) ){
                        if ($rejectAllAllowed == true) {
                            $rejectionSpecAll = array(
                                "label" => "reject all steps",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                            );
                        }
//                        }
                    }
                }

            }
        }
        else {
            //            cekmerah("NOT possible to reject");
        }

        //edit, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum > 0) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "edit", $this->configUiJenis)) {
            $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            cekPink("$evPre :: $evPost :: $evCom :: -- $evMaster");
            if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                cekhijau("allowed to EDIT");
                $editSpec = array(
                    "label" => "edit",
                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doPreEdit/$jenisTr/$no/$currentStepNum",
                    "warning" => "pressing EDIT will modify entire transaction data. continue?",
                );
            }
            else {
                cekmerah("NOT allowed to EDIT");
            }
        }
        else {
            if ($pelaku == $this->session->login['id']) {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                cekHitam("evPre::$evPre :: evePost::$evPost :: evCom::$evCom :: evMaster::$evMaster :: currentStepNum::$currentStepNum");

                if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                    cekhijau("allowed to EDIT");
                    $editSpec = array(
                        "label" => "edit",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doPreEdit/$jenisTr/$no/$currentStepNum",
                        "warning" => "pressing EDIT will modify entire transaction data. continue?",
                    );
                }
                else {
                    //lolosin untuk edit sub item
                    if (isset($this->configUiJenis["editSubItem"])) {
                        if ($this->configUiJenis["editSubItem"]["$currentStepNum"]) {
                            $editSpec = array(
                                "label" => "edit",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doPreEdit/$jenisTr/$no/$currentStepNum",
                                "warning" => "pressing EDIT will modify entire transaction data. continue?",
                            );
                        }
                        cekHijau("allow to edit");
                    }
                    cekmerah("NOT allowed to EDIT** LINE: " . __LINE__);
                }
            }
        }
        // matiHEre();

        //==approve
        if ($targetStepNum > $currentStepNum) {
            if ($allowFollowup == true) {
                if (isset($_SESSION[$cCode]['lockerPayment']['allowedFollow']) && $_SESSION[$cCode]['lockerPayment']['allowedFollow'] == true) {
                    if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                        if (isset($this->accessList[$this->jenisTr])) {
                            if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {

                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                        }
                        else {
                            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                                //                cekBiru(":: $currentStepNum :: $targetStepNum ::");
                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                $msgWarning2 = array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                //                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $approvalSpec = array(
                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                            );
                        }
                        else {
                            cekUngu("tidak ada approve");
                        }
                    }
                }
                else {
                    if (isset($this->accessList[$this->jenisTr])) {
                        if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(

                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            $msgWarning2 = array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {

                                $approvalSpec = array(
                                    //                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                        else {

                        }
                    }
                }
            }
            if ((isset($lockerPreDownpayment)) && ($lockerPreDownpayment == true)) {
                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                $msgWarning2 = array();
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $paymentSrcCek['label'],
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
            if (isset($lockShipment) && ($lockShipment == true)) {
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $lockShipmentLabel,
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
        }
        else {
            //            cekmerah("NOT possible to approve");
        }
        //endregion


        if (sizeof($signNumbers) > 0) {
            if ($currentStepIndex > 0) {
                $beforeCurrentIndex = ($currentStepIndex - 1);
                $beforeCurrentStep = $signNumbers[$beforeCurrentIndex];
            }
            else {

                $beforeCurrentStep = 0;
            }

            $masterRevertStep = $beforeCurrentStep;
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "", $this->configUiJenis)) {
                $mComponents = isset($this->configCore[$this->jenisTr]['components'][$currentStepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$currentStepNum]['master'] : array();

                if (sizeof($mComponents) > 0) {
                    $comNames = array();
                    foreach ($mComponents as $cSpec) {
                        $comNames[] = $cSpec['comName'];
                    }
                    if (in_array("Jurnal", $comNames)) {
                        //==tidak bisa di-revert
                    }
                    else {
                        $allowRevert = true;
                        $revertLabel = "undo";
                        $childRevertStep = -($currentStepNum);
                        $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    }
                }
                else {
                    $allowRevert = true;
                    //                    $revertLabel = $masterRevertStep . "undo " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                    $revertLabel = "undo";
                    $childRevertStep = -($currentStepNum);
                    $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";
                }

            }

        }
        //endregion


        //region check if i may approve or unapprove current transaction
        if (isset($this->configUi[$jenisTr]['steps'][$targetStepNum])) {
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                $allowFollowup = true;
                $buttonLabel = $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'];
                $acceptTarget = MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum";
                if (isset($masterRevertStep)) {
                    $mPreProcs = heCountPreProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mPostProcs = heCountPostProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mComs = heCountComponents_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);

                    //==set default to ENABLED
                    $childRevertStep = -($currentStepNum);
                    $rejectionLabel = "reject (def)";
                    $rejectionTarget = MODUL_PATH . __CLASS__ . "/dontFollowup/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    if (sizeof($mPreProcs['reversable']) > 0 || sizeof($mPostProcs['reversable']) > 0) {//maka cek dulu, boleh  cancel apa kagak
                        //==set default to DISABLED
                        $rejectionLabel = "can not reject";
                        $rejectionTarget = "";

                    }
                    else {//==langsung bisa dicancel
                        if (heJournalExists($this->jenisTr, $currentStepNum)) {
                            $rejectionLabel = "can not reject";
                            $rejectionTarget = "";
                        }
                        else {
                            //boleh
                        }

                    }

                }
            }
        }
        //endregion

        //endregion

        //region prevalidator
        $items = $rawItems;
        if (isset($this->configCore[$this->jenisTr]['preValidator'][$targetStepNum])) {
            $procList = $this->configCore[$this->jenisTr]['preValidator'][$targetStepNum];

            if (sizeof($procList) > 0) {
                foreach ($procList as $procName) {
                    $mdlProcName = "PreValidator" . $procName;
                    $this->load->model($mdlProcName);
                    if (isset($childGates) && sizeof($childGates) > 0) {
                        $prc = new $mdlProcName();
                        $requiredParams = $prc->getRequiredParams();
                        if (sizeof($requiredParams) > 0) {
                            $sentParams = array();
                            foreach ($childGates as $odSpec) {
                                $tmp = array();
                                foreach ($requiredParams as $key) {
                                    $tmp[$key] = $odSpec[$key];
                                }

                                $sentParams[] = $tmp;
                            }

                            $prc->pair($masterID, $sentParams);
                            $gotParams = $prc->exec();
                            if (isset($gotParams['items2']) && sizeof($gotParams['items2']) > 0) {
                                $items2 = $gotParams['items2'];
                                foreach ($gotParams['items2'] as $id => $iSpec) {
                                    //										$id=$iSpec['id'];
                                    if (isset($_SESSION[$cCode]['items'][$id])) {

                                        $items2[$id]['produk_ord_jml'] = $iSpec['produk_ord_jml'];
                                        $items2[$id]['produk_nama'] = $rawItems[$id]['produk_nama'];
                                        $items2[$id]['satuan'] = $rawItems[$id]['satuan'];


                                        $items[$id]['produk_ord_jml'] -= $iSpec['produk_ord_jml'];
                                        $_SESSION[$cCode]['items'][$id]['jml'] -= $iSpec['produk_ord_jml'];
                                        if ($items[$id]['produk_ord_jml'] < 1) {
                                            unset($items[$id]);
                                        }
                                        if ($_SESSION[$cCode]['items'][$id]['jml'] < 1) {
                                            unset($_SESSION[$cCode]['items'][$id]);
                                        }
                                    }
                                }
                            }

                        }
                        else {
                            die("preval $procName does not have requiredParams!");
                        }

                    }
                    else {
                        die("out_detail contains nothing!. skipping preprocessor");
                    }
                }
            }


            //<editor-fold desc="re-build values">


            //</editor-fold>

        }
        else {
            //                echo("no preval defined. skipping preval..<br>");
        }

        //endregion

        //region preview bottom elements

        $saveWarning = "";
        $buttonLabel = isset($this->configUi[$jenisTr]["steps"][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]["steps"][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]["steps"][$targetStepNum]['actionLabel'];
        //        cekBiru($buttonLabel . " LINE: " . __LINE__);
        if (isset($this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum])) {
            $saveWarning .= "clicking <strong>$buttonLabel</strong> button will make transaction state to: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . "</strong>";
            $saveWarning .= "<br>It would need to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum]['userGroup'] . "</strong>";
        }
        else {
            $saveWarning .= "clicking <strong>$buttonLabel</strong> button will instantly make transaction state to <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . "</strong>";
        }

        //endregion

        //region warn if irreverseble
        $mComponents = isset($this->configCore[$this->jenisTr]['components'][$targetStepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$targetStepNum]['master'] : array();
        if (sizeof($mComponents) > 0) {
            $comNames = array();
            $reks = array();
            foreach ($mComponents as $cSpec) {
                $comNames[] = $cSpec['comName'];
                if ($cSpec['comName'] == "Jurnal") {
                    if (isset($cSpec['loop']) && sizeof($cSpec['loop']) > 0) {
                        foreach ($cSpec['loop'] as $rek => $v) {
                            if (substr($rek, 0, 1) == "{") {
                                $rek = trim($rek, "{");
                                $rek = trim($rek, "}");
                                if (isset($_SESSION[$cCode]['main'][$rek])) {
                                    $rek = str_replace($rek, $_SESSION[$cCode]['main'][$rek], $rek);
                                }
                                else {
                                    $rek = NULL;
                                }
                            }
                            else {
                                //                        cekkuning("TIDAK mengandung kurawal");
                            }
                            $reks[$rek] = $rek;
                        }
                    }
                }
            }
            if (in_array("Jurnal", $comNames)) {
                //==tidak bisa di-revert
                $saveWarning .= "<br><span class='text-danger'>starting from this point, you can not undo the change made on this entry.</span>";
                if (sizeof($reks) > 0) {
                    $saveWarning .= "<br><h6><span class='text-blue'>these accounts will be affected at journal: <strong>" . implode(", ", $reks) . ".</strong></span></h6>";
                }
            }
        }
        //endregion


        $this->load->library("Validator");
        $vd = new Validator();
        $vd->setCCode($this->cCode);
        $vd->setConfigUiJenis($this->configUiJenis);
        $msgWarning = $vd->validate2();


        //
        //region replace main labels with properties from future/next step
        $mainProp = $tmpTr[0];
        $mainPropReplacers = array(//===replace khusus kebutuhan preview next step
            "jenis_label" => $tmpTr[0]->next_step_label,
            //            "nomer" => "(to be generated)",
            "result_nomer" => "(to be generated)",
            "dtime" => date("Y-m-d H:i:s"),
        );
        foreach ($mainPropReplacers as $key => $val) {
            $mainProp->$key = $val;
        }
        //endregion

        //
        //region prepare params for viewer

        $editableAddVals = array();
        if (isset($this->configCore[$this->jenisTr]['externalValues']) && sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configCore[$this->jenisTr]['externalValues'] as $exName => $exSpec) {
                if ($exSpec['useAt'] == $targetStepNum) {
                    $editableAddVals[] = $exName;
                }
            }
        }
        else {

        }


        $editableElements = array();
        $elementConfigs = isset($this->configUi[$this->jenisTr]['receiptElements']) ? $this->configUi[$this->jenisTr]['receiptElements'] : array();
        $relElementConfigs = isset($this->configUi[$this->jenisTr]['relativeElements']) ? $this->configUi[$this->jenisTr]['relativeElements'] : array();
        $relOptionConfigs = isset($this->configUi[$this->jenisTr]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();
        $xShipmentConfig = isset($this->configUi[$this->jenisTr]['xShipmentConfig']) ? $this->configUi[$this->jenisTr]['xShipmentConfig'] : array();
        $itemsChildLabel = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['fields']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['fields'] : array();
        $itemsChildEditable = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['editable']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['editable'] : array();
        $itemsChildGate = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['gate']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$targetStepNum]['gate'] : "none";
        $addRowsConfigs = isset($this->configUi[$this->jenisTr]['additionalRows']) ? $this->configUi[$this->jenisTr]['additionalRows'] : array();
        $kompositValidateConfigs = isset($this->configUi[$this->jenisTr]['kompositValidate']) ? $this->configUi[$this->jenisTr]['kompositValidate'] : array();

        if (sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $aKey => $aSpec) {
                    if (array_key_exists($aKey, $mainElements) && in_array($targetStepNum, $aSpec['editPoints'])) {
                        $editableElements[] = $aKey;
                    }
                    if (isset($relElementConfigs[$aKey])) {
                        foreach ($relElementConfigs[$aKey] as $mainRel => $relData) {
                            foreach ($relData as $relKey => $relDetails) {
                                //                                if (in_array("o_seller_spv", $mems)) {
                                if (sizeof($editElementAllowed) > 0) {
                                    if (array_key_exists($relKey, $mainElements) && in_array($targetStepNum, $relDetails['editPoints'])) {
                                        $editableElements[] = $relKey;

                                        if (array_key_exists($relKey, $relElementConfigs)) {
                                            //                                        cekBiru("rel element $relKey mentrigger kelompoknya sendiri");
                                            foreach ($relElementConfigs[$relKey] as $ownRel => $ownData) {
                                                foreach ($ownData as $ownKey => $ownDetails) {
                                                    if (array_key_exists($ownKey, $mainElements) && in_array($targetStepNum, $ownDetails['editPoints'])) {
                                                        $editableElements[] = $ownKey;
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }
                                //                                }
                            }
                        }
                    }
                }
            }
        }


        //region downpayment
        $dpValueDetails = array();
        $dpFieldName = array();
        $dpData = array();
        if (isset($masterTableInValueParams['dp_value']) && $masterTableInValueParams['dp_value'] > 0) {
            //        if (isset($masterTableInValueParams['dp_dipakai_ui']) && $masterTableInValueParams['dp_dipakai_ui'] > 0) {

            $tr = new MdlTransaksi();
            $tr->addFilter("transaksi.cabang_id='" . $tmpTr[0]->cabang_id . "'");
            $tr->addFilter("transaksi.jenis='700'");
            $tr->addFilterJoin("transaksi_data.produk_id='" . $tmpTr[0]->id_master . "'");
            $tmpTrs = $tr->lookupJoined();
            //arrprint($tmpTrs);


            $dpValueDetails = array(
                "dpp_dp" => $masterTableInValueParams['dp_value'],
                "ppn_dp" => $masterTableInValueParams['dp_ppn_value'],
                "dp" => $masterTableInValueParams['dp'],
                //                "due_amount" => $masterTableInValueParams['tagihan'],
                "penerima" => sizeof($tmpTrs) ? $tmpTrs[0]->oleh_nama : "-",
            );
            $dpFieldName = array(
                "dpp_dp" => "DPP Dp",
                "ppn_dp" => "VAT Dp",
                "dp" => "Downpayment",
                //                "due_amount" => "Due amount",
                "penerima" => "Penerima",
            );
            $dpData = array(
                "value" => $dpValueDetails,
                "field" => $dpFieldName,
            );
        }
        else {
            //            cekHitam("-TIDAK ADA DP-");
        }


        //endregion


        //region elements editor

        $elStr = array();
        $elements = array();
        $aFilter = array();

        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                switch ($eSpec['elementType']) {
                    case "dataModel":
                        $addStr = "";
                        $editStr = "";
                        $amdlName = $eSpec['mdlName'];
                        $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                        $elStr[$eName] = "";
                        $this->load->model("Mdls/" . $amdlName);
                        $labelSrc = $eSpec['labelSrc'];
                        $keySrc = $eSpec['key'];
                        $oo = new $amdlName();
                        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);
                        if (sizeof($aFilter) > 0) {
                            foreach ($aFilter as $filter) {
                                $exFilter = explode("=", $filter);
                                if (sizeof($exFilter) > 1) {
                                    if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                        $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                        $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                    }
                                }
                            }
                        }
                        $addClick = "";
                        $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array(
                            "viewers" => array(),
                            "creators" => array(),
                            "creatorAdmins" => array(),
                            "updaters" => array(),
                            "updaterAdmins" => array(),
                            "deleters" => array(),
                            "deleterAdmins" => array(),
                            "historyViewers" => array(),
                        );
                        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        }
                                        );";
                                $addStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$addClick\"><span class='fa fa-plus'></span></a>";
                            }
                        }

                        $tmpo = $oo->lookupAll()->result();
                        $elPair[$amdlName] = array();
                        $selectorTarget = MODUL_PATH . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";

                        $elStr[$eName] .= "<div class='box-body'>";
                        $elStr[$eName] .= "<select class='form-control' onchange=\"top.$('#result').load('$selectorTarget');\">";
                        $elStr[$eName] .= "<option value=''>-select-</option>";
                        if (sizeof($tmpo) > 0) {
                            foreach ($tmpo as $row) {

                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";

                            }
                        }
                        $elStr[$eName] .= "</select>";
                        $elStr[$eName] .= "</div class='box-header'>";

                        $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                        $defValue = "";
                        if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                            if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                $defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                    $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                    $defValue .= "<tr>";
                                    $defValue .= "<td align='left'>$label";
                                    $defValue .= "</td>";
                                    $defValue .= "<td align='left'>" . $fieldLabel;
                                    $defValue .= "</td>";
                                    $defValue .= "</tr>";
                                }
                                $defValue .= "</table>";
                            }
                        }


                        if ($defKey > 0) {
                            if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                    $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        }
                                        );";

                                    $editStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$editClick\"><span class='fa fa-pencil'></span></a>";
                                }
                            }
                        }

                        $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                        $elStr[$eName] .= "</div id='el$amdlName'>";
                        $elStr[$eName] .= "<div class='box-footer'>";

                        $elStr[$eName] .= "<span class='pull-right'>$editStr $addStr</span>";
                        $elStr[$eName] .= "</div class='box-footer'>";

                        $elements[$eName] = array(
                            "mdlName" => $eSpec['mdlName'],
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );


                        break;
                    case "dataField":
                        $elStr[$eName] = "";
                        $defaultValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                        $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";
                        //                        $elStr[$eName] .="<div class='box'>";

                        $elStr[$eName] .= "<div class='box-body'>";
                        switch ($eSpec['inputType']) {
                            case "text":
                                $elStr[$eName] .= "<input type=text class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                            case "date":
                                $elStr[$eName] .= "<input type=date class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                        }
                        $elStr[$eName] .= "</div class='box-body'>";

                        $elements[] = array(
                            "mdlName" => null,
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );
                        break;
                }
            }
        }

        //endregion


        $xShipmentBtn = array();
        if ($xShipmentConfig) {
            $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
            //            arrPrint($mems);
            foreach ($xShipmentConfig as $num => $val) {
                if ($num == $currentStepNum) {

                    $allowed = false;
                    foreach ($val['allowedGroups'] as $group) {
                        if (in_array($group, $mems)) {
                            $allowed = true;
                            break;
                        }
                    }
                    //                    cekHere("=== allowed::  " . $allowed);
                    if (($val['enabled'] == true) && ($allowed == true)) {

                        $labelx = $val['label'];
                        $targetJenisMaster = $val['targetJenisMaster'];
                        $warningx = $val['warning'];
                        $xShipmentBtn_str = array(
                            "label" => $labelx,
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/preCancelPacking/$jenisTr/$no/$targetJenisMaster/$currentStepNum",
                            "warning" => $warningx,
                        );
                        $xShipmentBtn = $xShipmentBtn_str;
                    }
                }
            }
        }

        $stepLabels = array();
        foreach ($this->configUi[$this->jenisTr]['steps'] as $num => $sSpec) {
            $stepLabels[$num] = $sSpec['label'];
        }

        $tmpTableIn_master = isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array();
        $tmpTableIn_masterValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();
        $main = array_merge(array_filter($main), array_filter($tmpTableIn_master), array_filter($tmpTableIn_masterValues));
        $mainAddValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();
        if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
            $mainAddValues = array_merge(array_filter($mainAddValues), array_filter($_SESSION[$cCode]['main_add_values']));
        }


        //==iterasi untuk memasukkan element relatif
        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            //            cekbiru("hendak memeriksa relative impacts");
            foreach ($_SESSION[$cCode]['main_elements'] as $eName => $eSpec) {
                //                cekbiru("memeriksa $eName:");
                if (array_key_exists($eName, $relElementConfigs)) {
                    //                    cekhijau("$eName memiliki relative impacts");
                    $currentValue = "";
                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $eSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $eSpec['value'];
                            break;
                    }
                    if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                        //                        cekhijau("memenuhi syarat");
                        //===daftarkan ke elementConfig
                        if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                            //                            cekmerah("memeriksa $eName, $currentValue");
                            //                            $rcCtr = 0;
                            foreach ($relElementConfigs[$eName][$currentValue] as $rcID => $rcSpec) {
                                //                                $elKey = $eName . "_" . $currentValue . "_" . $rcID;
                                $elKey = $rcID;
                                $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rcID];
                                //                                $rcCtr++;
                            }
                        }
                    }
                    else {
                        //                        cekmerah("TIDAK memenuhi syarat");
                    }
                }
            }
        }


        //==ini dua benda ini dibikin ulang di sini karena nantinya harus selalu refresh tanpa memanggil PrePreview lagi
        $trA = new MdlTransaksi();
        $extSteps = $trA->lookupExtSteps($masterID);
        $paySrcs = $trA->lookupPaymentSrcs($masterID, $this->jenisTr . "_");


        $_SESSION[$cCode]['extSteps'] = $extSteps;
        $_SESSION[$cCode]['paySrcs'] = $paySrcs;

        //create followup buttons for relative inputs
        //region buttons for relative inputs
        $extBtns = array();
        $extNewBtns = array();
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        if (isset($_SESSION[$cCode]['extSteps']) && sizeof($_SESSION[$cCode]['extSteps']) > 0) {
            foreach ($_SESSION[$cCode]['extSteps'] as $xSpec) {
                if (in_array($xSpec['groupID'], $mems)) {
                    $actionTarget = "
                                    top.BootstrapDialog.show(
                                   {
                                       title:'review " . $xSpec['label'] . "',
                                       message: " . '$' . "('<div></div>').load('" . MODUL_PATH . __CLASS__ . "/previewValue/" . $this->jenisTr . "/$masterID/" . $xSpec['id'] . "/" . $this->uri->segment(5) . "?rawPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        draggable:false,
                                        closable:true,
                                        }
                                        );";
                    $extBtns[$xSpec['key']] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> review " . $xSpec['label'] . "</a>";
                }
                else {
                    $extBtns[$xSpec['key']] = "<a class='btn btn-default text-muted'><i>unreviewable " . $xSpec['label'] . "</i></a>";
                }
            }
        }
        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            foreach ($_SESSION[$cCode]['main_elements'] as $eName => $eSpec) {
                if (array_key_exists($eName, $relOptionConfigs)) {
                    //                    cekhijau("$eName terdaftar pada relInputs");
                    if (isset($relOptionConfigs[$eName][$currentValue]) && sizeof($relOptionConfigs[$eName][$currentValue]) > 0) {
                        foreach ($relOptionConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                            if (isset($oValSpec['addPoints']) && in_array($targetStepNum, $oValSpec['addPoints'])) {
                                if (in_array($oValSpec['auth']['groupID'], $mems)) {
                                    $actionTarget = "
                                    top.BootstrapDialog.show(
                                   {
                                       title:'add " . $oValSpec['label'] . "',
                                       message: " . '$' . "('<div></div>').load('" . MODUL_PATH . __CLASS__ . "/addValue/" . $this->jenisTr . "/$masterID/" . "0" . "/" . $this->uri->segment(5) . "?rawPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        draggable:false,
                                        closable:true,
                                        }
                                        );";
                                    $extNewBtns[$oValueName] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> add " . $oValSpec['label'] . "</a>";
                                }
                                else {
                                    //                                    cekmerah("you are not allowed");
                                }
                            }
                            else {
                                //                                cekhijau("$oValueName TIDAK memenuhi syarat");
                            }
                        }
                    }
                }
            }
        }
        //endregion

        //create followup buttons for paymentSrc-related
        //region buttons for paymentSrc-related
        $payBtns = array();
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        if (isset($_SESSION[$cCode]['paySrcs']) && sizeof($_SESSION[$cCode]['paySrcs']) > 0) {
            foreach ($_SESSION[$cCode]['paySrcs'] as $xSpec) {
                if ($xSpec['sisa'] > 0) {

                    //                arrprint($xSpec);
                    $xSpec['groupID'] = $this->configUi[$xSpec['targetJenis']]['steps'][1]['userGroup'];
                    if (in_array($xSpec['groupID'], $mems)) {
                        $actionTarget = "
                                    top.BootstrapDialog.show(
                                   {
                                       title:'do " . $xSpec['label'] . "',
                                       message: " . '$' . "('<div></div>').load('" . MODUL_PATH . __CLASS__ . "Create/selectPaymentSrc/" . $xSpec['targetJenis'] . "/" . $xSpec['extID'] . "/$masterID?rawPrev=$rawPrevURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        draggable:false,
                                        closable:true,
                                        }
                                        );";
                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='fa fa-triangle-right'></span> do " . $xSpec['label'] . "</a>";
                    }
                    else {
                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-default text-muted'><i>" . $xSpec['label'] . "</i></a>";
                    }
                }
            }
        }
        //endregion

        //region additional row
        //        cekHitam($cCode . " $targetStepNum " . $currentStepNum);
        $selectedService = isset($_SESSION[$cCode]['main']['shippingService']) ? $_SESSION[$cCode]['main']['shippingService'] : "";

        //        arrPrint($selectedService);
        $allowEditRowa = isset($this->configUi[$this->jenisTr]["additionalRows"]["shippingService"][$selectedService]["shipping_service"]['editPoints']) ? $this->configUi[$this->jenisTr]["additionalRows"]["shippingService"][$selectedService]["shipping_service"]['editPoints'] : array();
        $addRows = array();
        $addRowLabels = array();
        if (in_array($targetStepNum, $allowEditRowa)) {
            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $eName => $eSpec) {
                    //reset dulu kalau yg tidak ada
                    if (array_key_exists($eName, $relElementConfigs)) {
                        //                    cekkuning("$eName ada dalam elementConfig, reset dulu adik2nya<br>");
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $currentValue = $eSpec['key'];
                                break;
                            case "dataField":
                                $currentValue = $eSpec['value'];
                                break;
                        }
                        if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                            //                        echo("-- $currentValue ada dalam elementConfig $eName<br>");
                            //===daftarkan ke elementConfig
                            if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                                //                            echo("---- memeriksa $eName, $currentValue<br>");
                                //                            $rcCtr=0;
                                foreach ($relElementConfigs[$eName][$currentValue] as $rKey => $rcSpec) {
                                    //                                $elKey = $eName . "_" . $currentValue . "_" . $rKey;
                                    $elKey = $rKey;
                                    $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rKey];
                                    //                                echo "elKey: $elKey";
                                    //                                $rcCtr++;


                                }
                            }
                            else {
                                //                            echo("---- TIDAK PERLU memeriksa $eName, $currentValue<br>");
                            }

                        }
                        else {
                            //                        echo("-- $currentValue TIDAK ada dalam elementConfig $eName<br>");
                        }
                    }
                    else {
                        //                    echo("$eName TIDAK ada dalam elementConfig<br>");
                    }

                    if (array_key_exists($eName, $addRowsConfigs)) {
                        switch ($elementConfigs[$eName]['elementType']) {
                            case "dataModel":
                                $currentValue = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : "";
                                break;
                            case "dataField":
                                $currentValue = $_SESSION[$cCode]['main_elements'][$eName]['value'];
                                break;
                        }
                        //                    cekhijau("currentValue: $currentValue");
                        if (isset($addRowsConfigs[$eName][$currentValue])) {
                            //                        cekmerah("aturan untuk $currentValue ada");
                            if (sizeof($addRowsConfigs[$eName][$currentValue]) > 0) {

                                foreach ($addRowsConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                    //                                cekhijau($oValueName);
                                    //                                arrprint($oValSpec);
                                    if (isset($oValSpec['editPoints']) && in_array($targetStepNum, $oValSpec['editPoints'])) {

                                        $relInputTarget = "'" . MODUL_PATH . __CLASS__ . "/_shoppingCart/recordAddRow/" . $this->jenisTr . "/$oValueName/?val='+this.value+'&ravPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'";


                                        //==init value and params
                                        //region default value
                                        if (isset($oValSpec['defaultValue'])) {
                                            $origDefValue = makeValue($oValSpec['defaultValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                        }
                                        //endregion

                                        //                                    cekmerah("$oValueName = ".$origDefValue);


                                        //region max-value
                                        $maxValue = $origDefValue;
                                        if (isset($oValSpec['maxValue'])) {
                                            $maxValue = makeValue($oValSpec['maxValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);

                                        }
                                        else {
                                            $maxValue = "";
                                        }

                                        //endregion


                                        //region min-value
                                        $minValue = $origDefValue;
                                        if (isset($oValSpec['minValue'])) {
                                            $minValue = makeValue($oValSpec['minValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                        }
                                        else {
                                            $minValue = "";
                                        }
                                        //endregion

                                        $minValStr = $minValue != "" ? "min='$minValue'" : "";
                                        $maxValStr = $maxValue != "" ? "max='$maxValue'" : "";

                                        //region inisiasi keystroke
                                        $keyupAct = "";
                                        if (isset($oValSpec['keyupAction']) && strlen($oValSpec['keyupAction']) > 0) {
                                            $keyupAct = $oValSpec['keyupAction'];
                                        }

                                        $keyupStr = "";
                                        if ($maxValue != "") {
                                            $keyupStr .= "if(parseInt(this.value)>$maxValue){this.value='$origDefValue';this.select();} ";
                                        }
                                        $keyupStr .= $keyupAct;


                                        $disabled = "";
                                        if (isset($oValSpec['disabled'])) {
                                            $disabled = $oValSpec['disabled'];
                                        }


                                        $blurStr = "";
                                        if ($minValue != "") {
                                            $blurStr = "if(this.value!=this.defaultValue){if(parseInt(this.value)>=$minValue){hiliteDiv(this);top.$('#result').load($relInputTarget);}else{this.value='$minValue';this.focus();}}";
                                        }
                                        else {
                                            $blurStr = "if(this.value!=this.defaultValue){hiliteDiv(this);top.$('#result').load($relInputTarget);}";

                                        }
                                        //endregion

                                        $defVal = isset($_SESSION[$cCode]['main'][$oValueName]) && $_SESSION[$cCode]['main'][$oValueName] > 0 ? ($_SESSION[$cCode]['main'][$oValueName] + 0) : $origDefValue;
                                        if (isset($addRowsConfigs[$eName][$currentValue][$oValueName]['role']) && $addRowsConfigs[$eName][$currentValue][$oValueName]['role'] == "minus") {
                                            $defVal = "(" . $defVal . ")";
                                        }
                                        //                                    $defVal = $origDefValue;
                                        $addRows[$oValueName] = "<input type=text autocomplete='off' id='$oValueName' class='form-control text-right' style='font-size:17px;' $disabled placeholder='$oValueName' value='$defVal' $minValStr $maxValStr 
onfocusssss='this.select()' onkeyup=\"$keyupStr\" onfocus=\"$keyupStr\"
onblur=\"$blurStr\"
onmouseout=\"$blurStr\"
>";
                                        $_SESSION[$cCode]['add_rows'][$oValueName] = $defVal;
                                        $addRowLabels[$oValueName] = $oValSpec['label'];

                                    }

                                }

                            }
                        }
                        else {
                            //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                            //                        cekmerah("aturan untuk $currentValue TIDAK ada");
                        }

                    }
                    else {
                        //					cekKuning("$eName TIDAK terdaftar pada relInputs");
                    }


                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $addStr = "";
                            $editStr = "";
                            $amdlName = $eSpec['mdlName'];
                            $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                            $elStr[$eName] = "";
                            $this->load->model("Mdls/" . $amdlName);
                            $labelSrc = $eSpec['labelSrc'];
                            $keySrc = $eSpec['key'];
                            $oo = new $amdlName();
                            $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);

                            if (sizeof($aFilter) > 0) {
                                foreach ($aFilter as $filter) {
                                    $exFilter = explode("=", $filter);
                                    if (sizeof($exFilter) > 1) {
                                        if (substr($exFilter[1], 0, 1) == ".") {
                                            //                                        $oo->addFilter($exFilter[0] . "='" . ltrim($exFilter[1], ".") . "'");
                                        }
                                        else {
                                            if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                                //                                            $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                                $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                            }
                                            else {
                                                //                                            $oo->addFilter($exFilter[0] . "='none'");
                                            }
                                        }
                                    }
                                }
                                $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                            }

                            $addClick = "";
                            $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array(
                                "viewers" => array(),
                                "creators" => array(),
                                "creatorAdmins" => array(),
                                "updaters" => array(),
                                "updaterAdmins" => array(),
                                "deleters" => array(),
                                "deleterAdmins" => array(),
                                "historyViewers" => array(),
                            );
                            $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                            if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                                if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                    $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";
                                    $addStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$addClick\"><span class='glyphicon glyphicon-plus'></span></a>";
                                }
                            }

                            //                        cekmerah("pre..");
                            $tmpo = $oo->lookupAll()->result();
                            //                        cekmerah($this->db->last_query());
                            $elPair[$amdlName] = array();
                            $selectorTarget = "'" . MODUL_PATH . __CLASS__ . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";

                            $elStr[$eName] .= "<div class='box-body'>";

                            switch ($eSpec['inputType']) {
                                case "combo":
                                    $elStr[$eName] .= "<select class='form-control' onchange=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">";
                                    $elStr[$eName] .= "<option value=''>-select-</option>";
                                    if (sizeof($tmpo) > 0) {
                                        foreach ($tmpo as $row) {

                                            $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                            if (sizeof($ex) > 1) {
                                                $labelValue = "";
                                                foreach ($ex as $col) {

                                                    $labelValue .= $row->$col . " / ";
                                                }
                                                $labelValue = rtrim($labelValue, " / ");
                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";

                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $labelValue . "</option>";
                                                //                                            $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $$labelValue . "</option>";

                                            }
                                            else {
                                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";
                                            }


                                        }
                                    }
                                    $elStr[$eName] .= "</select>";
                                    break;
                                case "radio":

                                    if (sizeof($tmpo) > 0) {
                                        foreach ($tmpo as $row) {
                                            $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                            if (sizeof($ex) > 1) {
                                                $labelValue = "";
                                                foreach ($ex as $col) {

                                                    $labelValue .= $row->$col . " / ";
                                                }
                                                $labelValue = rtrim($labelValue, " / ");
                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                                $elStr[$eName] .= "<label class='badge' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $labelValue . "</label>&nbsp;";
                                            }
                                            else {
                                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                                $elStr[$eName] .= "<label class='badge' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $row->$labelSrc . "</label>&nbsp;";
                                            }

                                        }
                                    }
                                    break;
                            }


                            $elStr[$eName] .= "</div class='box-header'>";

                            $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                            $defValue = "";
                            if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                                if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                    //								$defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                    $defValue .= "<div class='panel-body'>";
                                    $defValue .= "<table cellspacing='0' cellpadding='0' border='0'>";
                                    $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                    foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                        $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                        //                                    if(is_numeric($fieldLabel)){
                                        //                                        $fieldLabel=number_format($fieldLabel);
                                        //                                    }
                                        $defValue .= "<tr>";
                                        $defValue .= "<td align='left'>$label";
                                        $defValue .= "&nbsp;</td>";
                                        $defValue .= "<td align='left'>:&nbsp;" . $fieldLabel;
                                        $defValue .= "</td>";
                                        $defValue .= "</tr>";
                                    }
                                    $defValue .= "</table>";
                                    $defValue .= "</div class='panel-body'>";
                                }
                            }
                            else {//menentukan nilai default

                            }

                            if ($defKey > 0) {
                                if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                    $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                    if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                        $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";

                                        $editStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$editClick\"><span class='fa fa-pencil'></span></a>";
                                    }
                                }
                            }

                            $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                            $elStr[$eName] .= "</div id='el$amdlName'>";

                            $elements[$eName] = array(
                                "mdlName" => $eSpec['mdlName'],
                                "label" => $eSpec['label'],
                                "string" => $elStr[$eName],
                                "editStr" => $editStr,
                                "addStr" => $addStr,
                                "bgColor" => $defValue == "" ? "#fcfce0" : "#f5fff9",
                            );


                            break;
                        case "dataField":
                            $elStr[$eName] = "";
                            $initValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                            //                        $defaultValue = isset($_SESSION[$cCode]['main_elements'][$eName]['value']) ? $_SESSION[$cCode]['main_elements'][$eName]['value'] : "";
                            $defaultValue = isset($_SESSION[$cCode]['main'][$eName]) ? $_SESSION[$cCode]['main'][$eName] : 0;
                            $selectorTarget = "'" . MODUL_PATH . __CLASS__ . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";
                            //                        $elStr[$eName] .="<div class='box'>";

                            $maxValue = isset($eSpec['maxValue']) && isset($_SESSION[$cCode]['main'][$eSpec['maxValue']]) ? $_SESSION[$cCode]['main'][$eSpec['maxValue']] : "";

                            $elStr[$eName] .= "<div class='box-body'>";
                            switch ($eSpec['inputType']) {
                                case "text":
                                    $elStr[$eName] .= "<input type=text class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\" 
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                                case "number":
                                    $maxValStr = $maxValue != "" ? " max='" . $maxValue . "''" : "";
                                    $maxValValidator = $maxValue != "" ? " onkeyup=\"if(this.value>$maxValue){this.value='$maxValue';}\" " : "";
                                    $elStr[$eName] .= "<input type=number class='form-control' value='$defaultValue' onfocus='this.select()' $maxValStr $maxValValidator oonclick=\"this.value='$defaultValue';\" 
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                                case "date":
                                    $elStr[$eName] .= "<input type=date class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\" 
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                            }
                            $elStr[$eName] .= "</div class='box-body'>";

                            $elements[$eName] = array(
                                "mdlName" => null,
                                "label" => $eSpec['label'],
                                "string" => $elStr[$eName],
                                "editStr" => "",
                                "addStr" => "",
                                "bgColor" => $defaultValue == "" ? "#fcfce0" : "#fcfcff",
                            );
                            break;
                    }
                }
            }
        }


        //endregion.

        //region tambah additional rows tampil
        $addRowLabels = array();
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                if (array_key_exists($eName, $addRowsConfigs)) {

                    switch ($elementConfigs[$eName]['elementType']) {
                        case "dataModel":
                            $currentValue = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : "";
                            break;
                        case "dataField":
                            $currentValue = $_SESSION[$cCode]['main_elements'][$eName]['value'];
                            break;
                    }

                    if (isset($addRowsConfigs[$eName][$currentValue])) {
                        if (sizeof($addRowsConfigs[$eName][$currentValue]) > 0) {

                            foreach ($addRowsConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                //                                cekhijau($oValueName);
                                //                                arrprint($oValSpec);
                                if (isset($oValSpec['addPoints']) && in_array(1, $oValSpec['addPoints'])) {
                                    if (!isset($oValSpec['hideRow'])) {
                                        $addRowLabels[$oValueName] = $oValSpec['label'];
                                    }

                                }

                            }

                        }
                    }
                    else {
                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                        //                        cekmerah("aturan untuk $currentValue TIDAK ada");
                    }

                }
                else {
                    //					cekKuning("$eName TIDAK terdaftar pada relInputs");
                }

            }
        }
        //endregion

        //region add mainData
        //        cekHitam($targetStepNum." ".$this->jenisTr);
        $addMainSource = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum] : array();
        $addMainSourceField = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"] : array();
        $addMainSourceEdit = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"] : array();

        //        arrPrint($this->configUi[$this->jenisTr]["addMainSource"]);


        //endregion


        $detilSizeBar = array();
        $measureConf = isset($this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum] : false;
        //        cekHere($currentStepNum);
        //        arrPrint($measureConf);
        if ($measureConf) {
            if (isset($elements['detilSize'])) {
                $detilSizeBar = array(
                    "volume_gross" => isset($main['volume_gross']) ? number_format(conv_mmc_mc($main['volume_gross']), 2) : 0,
                    "berat_gross" => isset($main['berat_gross']) ? conv_g_kg($main['berat_gross']) : 0,
                );
            }
        }

//        arrPrintWebs($this->jenisTr);
//        arrPrintWebs($targetStepNum);
//        arrPrintWebs($itemLabels3);
//        arrPrintWebs($itemNumLabels3);

        $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "sub-amount");
        $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "sub-amount");
        $itemLabels3 = $itemLabels3 + $itemNumLabels3 + array("subtotal" => "sub-amount");

//        arrPrintWebs($itemLabels2);
//        arrPrintWebs($itemLabels3);

        if (isset($this->configUi[$this->jenisTr]['shoppingCartHideSubamount']) && $this->configUi[$this->jenisTr]['shoppingCartHideSubamount'][$targetStepNum] == true) {
            unset($itemLabels['subtotal']);
            unset($itemLabels2['subtotal']);
            unset($itemLabels3['subtotal']);
        }

        $pairedItemTarget = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName'] : "items2_sum";
        $pairedItemTarget3 = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName'] : "items3_sum";

        $itemsEditableConfig = isset($this->configUi[$this->jenisTr]['followupItemEditable']) ? $this->configUi[$this->jenisTr]['followupItemEditable'] : "_followupLiveEdit/updateItemField/";
        $itemsEditableConfig2 = isset($this->configUi[$this->jenisTr]['followupItemEditable']) ? $this->configUi[$this->jenisTr]['followupItemEditable'] : "_followupLiveEdit/updateSubItemField/";
        $itemsRemoveConfig = isset($this->configUi[$this->jenisTr]['followupItemRemove']) ? $this->configUi[$this->jenisTr]['followupItemRemove'] : "_followupLiveEdit/removeItem/";
        $itemsRemoveConfig2 = isset($this->configUi[$this->jenisTr]['followupItemRemove']) ? $this->configUi[$this->jenisTr]['followupItemRemove'] : "_followupLiveEdit/removeSubItem/";
        $mainEditableConfig = isset($this->configUi[$this->jenisTr]['followupMainEditable']) ? $this->configUi[$this->jenisTr]['followupMainEditable'] : "_followupLiveEdit/updateMainField/";

        $definitionButton = definitionButton();

        if ($partialCanceled == false) {
            $deleteSpec = array(
                "label" => "cannot delete",
                "targetUrl" => "",
                "warning" => "",
            );
            $undoSpec = array(
                "label" => "cannot undo",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpec = array(
                "label" => "cannot reject 1 step",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpecAll = array(
                "label" => "cannot reject all steps (".__LINE__.")",
                "targetUrl" => "",
                "warning" => "",
            );
            $editSpec = array(
                "label" => "cannot edit",
                "targetUrl" => "",
                "warning" => "",
            );

            $lastWarningLabel = isset($msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label']) ? $msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label'] . "<br>" : "";
            $newWarningLabel = "Transaksi ini telah diproses sebagian, UNDO/REJECT/DELETE/EDIT tidak bisa digunakan.";
            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                "label" => $lastWarningLabel . $newWarningLabel,
            );

            // $arrSwals = array(
            //     "type"              => "warning",
            //     "html"              => $newWarningLabel,
            //     "allowOutsideClick" => false,
            //     // "imageUrl"            => img_bitzer(),
            //     "background" => "aqua",
            //     "confirmButtonColor" => "#ff0055",
            // );
            //
            // echo swalAlert($arrSwals);
        }
        if ($allowedAction == false) {
            $deleteSpec = array(
                "label" => "cannot delete",
                "targetUrl" => "",
                "warning" => "",
            );
            $undoSpec = array(
                "label" => "cannot undo",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpec = array(
                "label" => "cannot reject 1 step",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpecAll = array(
                "label" => "cannot reject all steps ($allowedAction)",
                "targetUrl" => "",
                "warning" => "",
            );
            $editSpec = array(
                "label" => "cannot edit",
                "targetUrl" => "",
                "warning" => "",
            );
            $approvalSpec = array(
                "label" => "cannot approve",
                "targetUrl" => "",
                "warning" => "",
            );
            $xShipmentBtn = array();
            $extBtns = array();
            $extNewBtns = array();
            $payBtns = array();

            $lastWarningLabel = isset($msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label']) ? $msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label'] . "<br>" : "";
            $newWarningLabel = "Transaksi ini dikunci karena sedang ditindaklanjuti oleh <span class='text-uppercase text-bold'>$allowedActionByHold</span>.";
            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                "label" => $lastWarningLabel . $newWarningLabel,
            );
        }

        //-----------------------------------------------------
        $beforeStepWarning = NULL;
        $beforeStepNum = $currentStepNum - 1;
        if ($beforeStepNum > 0) {
            $beforeStepLabels = isset($this->configUi[$this->jenisTr]['steps'][$beforeStepNum]['label']) ? $this->configUi[$this->jenisTr]['steps'][$beforeStepNum]['label'] : "-";
            $beforeStepLabels = "Transaksi akan kembali ke $beforeStepLabels";
            $beforeStepWarning = "DELETE, UNDO, REJECT 1 STEP: Transaksi akan mundur 1 langkah. $beforeStepLabels.";
        }
        else {
            $beforeStepLabels = "Transaksi akan ditutup dan tidak bisa dilanjutkan.";
            $beforeStepWarning = "DELETE, UNDO, REJECT 1 STEP: Transaksi akan ditutup dan tidak bisa dilanjutkan.";
        }
        $beforeAllStepLabels = "Transaksi akan ditutup dan tidak bisa dilanjutkan.";

        //-----------------------------------------------------
        //        cekKuning($kompositValidateConfigs);
        if (sizeof($kompositValidateConfigs) > 0) {
            if (isset($kompositValidateConfigs['enabled']) && ($kompositValidateConfigs['enabled'] == true)) {
                $this->load->model("Mdls/" . $kompositValidateConfigs['mdlName']);
                $kmp = New $kompositValidateConfigs['mdlName']();
                $kmp->addFilter("produk_id in ('" . implode("','", $itemsKompositID) . "')");
                $kmpTmp = $kmp->lookupAll()->result();
                $kompositComponent = array();
                if (sizeof($kmpTmp) > 0) {
                    foreach ($kmpTmp as $kmpSpec) {
                        $kompositComponent[$kmpSpec->produk_id][] = $kmpSpec;
                    }
                }
                //                cekKuning($kompositComponent);
                $noComponent = array();
                foreach ($itemsKompositName as $pID => $pName) {
                    if (!array_key_exists($pID, $kompositComponent)) {
                        $noComponent[$pID] = $pName;
                    }
                }

                if (sizeof($noComponent) > 0) {
                    $link = base_url() . "Data/view/ProdukKomposit";
                    $produk_ket = implode(",", $noComponent);
                    $msg = "Produk $produk_ket belum memiliki komposisi. ";
                    $msg .= "Untuk mengatur komposisinya ";
                    $msg .= "<a href='$link' style='font-weight:bold;color:#ffffff;'>klik disini</a>";
                    $msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label'] = $msg;

                    $approvalSpec = array(
                        "label" => "cannot approve",
                        "targetUrl" => "",
                        "warning" => "",
                    );
                }
            }
        }


        // menonaktifkan tombol approve di followupPreview, tembakan menonaktifkan tombol-tombol
        $pakai_ini = 1;
        if ($pakai_ini == 1) {
            if (($this->jenisTr == "110")) {
                $rejectionSpecAll = array(
                    "label" => "cannot reject all steps",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
            //            if (($this->jenisTr == "967") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            if (($this->jenisTr == "582") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "582") && ($targetStepNum == 4)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "382") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "382") && ($targetStepNum == 4)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "466") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "461") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "982") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "2985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "3585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "967") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "961") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "587") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "587") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "687") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "687") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1587") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1587") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1687") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1687") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "334") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1334") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1337") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
        }

        //--- cek saldo kas/valas uang muka valas
        $saldoLockerConfig = isset($this->configUi[$this->jenisTr]['saldoLocker']) ? $this->configUi[$this->jenisTr]['saldoLocker'] : array();
        if ((sizeof($saldoLockerConfig) > 0) && ($saldoLockerConfig['enabled'] == true)) {
            if (isset($saldoLockerConfig['pairModel'])) {
                $result = array();
                $resultLockerLabel = array();
                foreach ($saldoLockerConfig['pairModel'] as $mtd => $pmSpec) {
                    $resultLockerLabel[$mtd] = $pmSpec['label'];
                    $mdl = $pmSpec['mdlName'];
                    $this->load->model("Mdls/$mdl");
                    $md = New $mdl();
                    if (isset($pmSpec['mdlFilter']) && (sizeof($pmSpec['mdlFilter']) > 0)) {
                        makeFilter($pmSpec['mdlFilter'], $_SESSION[$cCode]['main'], $md);
                    }
                    $mdTmp = $md->lookupAll()->result();
                    //                    showLast_query("biru");

                    if (sizeof($mdTmp) > 0) {
                        $result[$mtd] = array(
                            "name" => $_SESSION[$cCode]['main'][$pmSpec['sesKey']],
                            "nilai" => $mdTmp[0]->nilai,
                        );
                    }
                    else {
                        $result[$mtd] = array(
                            "name" => $_SESSION[$cCode]['main'][$pmSpec['sesKey']],
                            "nilai" => 0,
                        );
                    }

                }
                if (sizeof($result) > 0) {
                    $metode = $_SESSION[$cCode]['main']['pihak3ID'];
                    switch ($metode) {
                        case "cash":
                            if (isset($result[$metode])) {
                                $bayar_total = $_SESSION[$cCode]['main']['total_bayar'];
                                $saldo = isset($result[$metode]['nilai']) ? $result[$metode]['nilai'] : 0;
                                $kas_nama = isset($result[$metode]['name']) ? $result[$metode]['name'] : "";
                                //                                $saldo = 0;
                                if ($bayar_total > $saldo) {
                                    $result[$metode]['warning'] = "Saldo kas $kas_nama tidak cukup untuk melanjutkan transaksi ini. Silahkan mengisi saldo kas atau melakukan edit.";
                                    //                                    $result[$metode]['warning'] = $resultLockerLabel[$metode];
                                    $approvalSpec = array(
                                        "label" => "cannot approve",
                                        "targetUrl" => "",
                                        "warning" => "",
                                    );
                                }
                            }
                            break;
                        case "valas":
                            if (isset($result[$metode])) {
                                $bayar_total_valas = $_SESSION[$cCode]['main']['valas_nilai_bayar'];
                                $bayar_total = $_SESSION[$cCode]['main']['biaya_transfer'] + $_SESSION[$cCode]['main']['biaya_lain_lain_novalas'];
                                $saldo = isset($result[$metode]['nilai']) ? $result[$metode]['nilai'] : 0;
                                $valas_nama = isset($result[$metode]['name']) ? $result[$metode]['name'] : "";
                                $kas_nama = isset($result['cash']['name']) ? $result['cash']['name'] : "";
                                $kas_saldo = isset($result['cash']['nilai']) ? $result['cash']['nilai'] : "";
                                $metodeWarning = "";
                                if ($bayar_total_valas > $saldo) {
                                    //                                        $result[$mtd]['warning'] = $resultLockerLabel[$metode];
                                    $metodeWarning .= "Saldo valas $valas_nama tidak cukup untuk melanjutkan transaksi ini.<br>";
                                    $approvalSpec = array(
                                        "label" => "cannot approve",
                                        "targetUrl" => "",
                                        "warning" => "",
                                    );
                                }
                                if ($bayar_total_valas > $kas_saldo) {
                                    $metodeWarning .= "Saldo kas $kas_nama tidak cukup untuk melanjutkan transaksi ini.";
                                    $approvalSpec = array(
                                        "label" => "cannot approve",
                                        "targetUrl" => "",
                                        "warning" => "",
                                    );
                                }
                                $result[$metode]['warning'] = $metodeWarning;
                            }
                            break;
                    }
                }
            }
        }

        //region DETAILS BOM
        $this->load->model("Mdls/MdlProjectKomposisi");
        $this->load->model("Mdls/MdlProjectKomposisiWorkorder");
        $this->load->model("Mdls/MdlProjectKomposisiWorkorderSub");
        $this->load->model("Mdls/MdlProjectWorkOrder");
        $this->load->model("Mdls/MdlProdukProject");
        $this->load->model("Mdls/MdlTasklistProject");

        $pk = new MdlProjectKomposisi();
        $o = new MdlProdukProject();
        $kf = new MdlProjectKomposisiWorkorder();
        $pf = new MdlProjectWorkOrder();
        $kfs = new MdlProjectKomposisiWorkorderSub();
        $ts = new MdlTasklistProject();

        $trIDProjectTarget = $mainProp->id_master;
        $o->addFilter("lock=1");
//        $o->addFilter("nomor_kontrak=0");
        $o->addFilter("transaksi_id=$trIDProjectTarget");
        $tempProdukMaster = $o->lookUpAll()->result();

        $produkProjectPid = 0;
        if (!empty($tempProdukMaster)) {
            $produkProjectPid = $tempProdukMaster[0]->id;
        }

        $ts->setFilters(array());
        $ts->addFilter("produk_id='$produkProjectPid'");
        $ts->addFilter("trash='0'");
        $ts->addFilter("status='1'");
        $tempTasklist = $ts->lookUpAll()->result();

        $taskList = array();
        if(!empty($tempTasklist)){
            foreach($tempTasklist as $rows){
                $taskList[$rows->id] = $rows;
            }
        }

        $arrGudangWorkorder=array();
        $arrStockLockerWorkorder = array();
        if(!empty($taskList)){
            foreach($taskList as $ids => $rWo){
                $no_spk = $rWo->no_spk;
                $produk_id = $rWo->produk_id;
                $fase_id = $rWo->fase_id;
                $sub_fase_id = $rWo->sub_fase_id;
                $ambil_angka_depan_spk = explode("/", $no_spk)[0];
                $gudang_project = "$produk_id" . "$fase_id" . "$sub_fase_id" . "$ambil_angka_depan_spk";
                $arrGudangWorkorder[] = $gudang_project;
                $taskList[$ids]->gudang_id = $gudang_project;
            }

            $arrGudang_project_wo = implode(",", $arrGudangWorkorder);

            //material sudah distribusi
            $arrMaterialDist = array();
            $this->load->model("Mdls/MdlLockerStock");
            $ls = new MdlLockerStock();
            $ls->addFilter("gudang_id in ($arrGudang_project_wo)");
            $ls->addFilter("jumlah>0");
            $ls->addFilter("state='active'");
            $tempLs = $ls->lookUpAll()->result();
            $arrProdukDistQuery = $this->db->last_query();
            if (!empty($tempLs)) {
                $resetRow=0;
                foreach ($tempLs as $rows) {
                    $arrMaterialDist[$rows->gudang_id]['produk'][$resetRow] = (array)$rows;
                    $arrMaterialDist[$rows->gudang_id]['produk'][$resetRow]->biaya_nama = 'produk';
                    $resetRow++;
                }
            }
            cekMerah(__LINE__);
            cekHitam($arrProdukDistQuery);
            $this->load->model("Mdls/MdlLockerStockSupplies");
            $lss = new MdlLockerStockSupplies();
            $lss->addFilter("gudang_id in ($arrGudang_project_wo)");
            $lss->addFilter("jumlah>0");
            $lss->addFilter("state='active'");
            $tempLss = $lss->lookUpAll()->result();
            $arrSuppliesDistQuery = $this->db->last_query();
            if (!empty($tempLss)) {
                foreach ($tempLss as $rows) {
                    $arrMaterialDist[$rows->gudang_id]['supplies'][$rows->biaya_id][$rows->produk_id] = (array)$rows;
                    $arrMaterialDist[$rows->gudang_id]['supplies'][$rows->biaya_id][$rows->produk_id]->biaya_nama = 'supplies';
                }
            }
            cekMerah(__LINE__);
            cekHitam($arrSuppliesDistQuery);
            //material sudah distribusi hold
            $arrMaterialDistHold = array();
            $this->load->model("Mdls/MdlLockerStock");
            $lsh = new MdlLockerStock();
            $lsh->addFilter("gudang_id in ($arrGudang_project_wo)");
            $lsh->addFilter("jumlah>0");
            $lsh->addFilter("state='hold'");
            $tempLsh = $lsh->lookUpAll()->result();
            $arrProdukDistHoldQuery = $this->db->last_query();
            if (!empty($tempLsh)) {
                foreach ($tempLsh as $rows) {
                    $arrMaterialDistHold[$rows->gudang_id][$rows->produk_id] = (array)$rows;
                }
            }
            cekMerah(__LINE__);
            cekHitam($arrProdukDistHoldQuery);
            $this->load->model("Mdls/MdlLockerStockSupplies");
            $lshs = new MdlLockerStockSupplies();
            $lshs->addFilter("gudang_id in ($arrGudang_project_wo)");
            $lshs->addFilter("jumlah>0");
            $lshs->addFilter("state='distribute'");
            $tempLshs = $lshs->lookUpAll()->result();
            $arrSuppliesDistHoldQuery = $this->db->last_query();
            if (!empty($tempLshs)) {
                foreach ($tempLshs as $rows) {
                    $arrMaterialDistHold[$rows->gudang_id][$rows->biaya_id][$rows->produk_id] = (array)$rows;
                }
            }
            cekMerah(__LINE__);
            cekHitam($arrSuppliesDistHoldQuery);
//            echo json_encode($arrMaterialDist);
//            echo json_encode($arrMaterialDistHold);
//            arrPrint($arrMaterialDistHold);

        }

//        arrPrint($tempTasklist);
//        cekHijau($trIDProjectTarget);
//        cekHijau($produkProjectPid);

        //produk komposisi sumary
        $pk->setFilters(array());
        $pk->addFilter("produk_id='$produkProjectPid'");
        $pk->addFilter("jenis in ('produk','biaya','room')");
        $this->db->order_by("jenis", "desc");
        $tempProduk = $pk->lookUpAll()->result();
        $sumarryProjectLabel = $pk->getListedFields();

        $sumarryProject = array();
        if (sizeof($tempProduk) > 0) {
            foreach ($tempProduk as $i => $temproduk_0) {
                foreach ($sumarryProjectLabel as $key => $label) {
                    $sumarryProject[$temproduk_0->jenis][$i][$key] = $temproduk_0->$key;
                }
                if ($temproduk_0->jenis == "biaya") {
                    unset($sumarryProject["biaya"][$i]["jml"]);
                    unset($sumarryProject["biaya"][$i]["harga"]);
                }
                $sumarryProject[$temproduk_0->jenis][$i]["subtotal"] = $temproduk_0->harga * $temproduk_0->jml;
            }
        }

        $kf->setFilters(array());
        $kf->addFilter("produk_id='$produkProjectPid'");
        $kf->addFilter("trash='0'");
        $kf->addFilter("status='1'");
        $this->db->order_by("id", "ASC");
        $tempProdukFaseKomposisi = $kf->lookUpAll()->result();

        $pf->setFilters(array());
        $pf->addFilter("produk_id='$produkProjectPid'");
        $pf->addFilter("trash='0'");
        $pf->addFilter("status='1'");
        $this->db->order_by("id", "ASC");
        $tempProdukFase = $pf->lookUpAll()->result();

        $kfs->setFilters(array());
        $kfs->addFilter("produk_id='$produkProjectPid'");
        $kfs->addFilter("trash='0'");
        $kfs->addFilter("status='1'");
        $kfs->addFilter("jenis_transaksi='5582'");
//        $kfs->addFilter("jenis_transaksi='sub_wo'");
        $this->db->order_by("id", "ASC");
        $tempProdukFaseKomposisiSub = $kfs->lookUpAll()->result();

        //region komposisi work order
        $produkFase = array();
        $fields = $pf->getListedFields();
        if (sizeof($tempProdukFase) > 0) {
            foreach ($tempProdukFase as $data) {
                foreach ($fields as $field => $fieldAlias) {
                    $produkFase[$data->id][$field] = isset($data->$field) ? $data->$field : "";
                }
                if (isset($data->qty) && $data->qty > 0) {
                    for ($di = 1; $di <= $data->qty; $di++) {
                        $produkFase[$data->id]['details'][$di] = array(
                            "idx" => $data->produk_id . $data->id . $di,
                            "nama" => $data->nama . " (" . $di . ")",
                        );
                    }
                }
            }
        }
        //endregion

        //relasi jadi option atau input
        $arrRel = array();
        $priceList = array();
        $produkKomposisTarget = array();
        $produkKomposisJual = array();
        $produkKomposisiFaseSub = array();
        $FaseSubNama = array();
        if (sizeof($tempProdukFaseKomposisi) > 0) {
            foreach ($tempProdukFaseKomposisi as $ii => $iiData) {
                if ($iiData->jenis == "room") {
                    $iiData->produk_dasar_id = $iiData->room_id;
                }
                $priceList[$iiData->fase_id][$iiData->produk_dasar_id] = array(
                    "harga_ori" => $iiData->nilai,
                    "harga_bom" => $iiData->harga,
                );
                if (!isset($iiData->subtotal)) {
                    $iiData->subtotal = $iiData->jml * $iiData->harga;
                }
                if ($iiData->jenis == "produk" || $iiData->jenis == "jual" || $iiData->jenis == "room") {
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->produk_dasar_id]["subtotal"] = $iiData->jml * $iiData->harga;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->produk_dasar_id] = (array)$iiData;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->produk_dasar_id]["jual"] = isset($arrPrice[$iiData->produk_dasar_id]['jual']) ? $arrPrice[$iiData->produk_dasar_id]['jual'] : 0;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->produk_dasar_id]["ppv"] = isset($arrPrice[$iiData->produk_dasar_id]['hpp_nppv']) ? $arrPrice[$iiData->produk_dasar_id]['hpp_nppv'] : 0;
                }
                if ($iiData->jenis == "target") {
                    $produkKomposisTarget[$prodID][$iiData->fase_id] = (array)$iiData;
                }
                if ($iiData->jenis == "jual") {
                    $produkKomposisJual[$prodID][$iiData->fase_id] = (array)$iiData;
                }
                if ($iiData->jenis == "produk_room") {
                    unset($produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->produk_dasar_id]);
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->room_id][$iiData->produk_dasar_id] = (array)$iiData;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->room_id][$iiData->produk_dasar_id]['hpp'] = $iiData->hrg_hpp;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->room_id][$iiData->produk_dasar_id]['ppv'] = $iiData->hrg_ppv;
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->room_id][$iiData->produk_dasar_id]['jual'] = $iiData->hrg_jual;
                }
                if ($iiData->jenis == "biaya_room") {
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->room_id][$iiData->produk_dasar_id] = (array)$iiData;
                }
                if ($iiData->jenis == "biaya") {
                    $produkKomposisiFase[$iiData->fase_id][$iiData->jenis][$iiData->id] = (array)$iiData;
                }
            }
            //SUB WO
            foreach ($tempProdukFaseKomposisiSub as $ii => $iiDataSub) {
                $priceList[$iiDataSub->fase_id][$iiDataSub->produk_dasar_id] = array(
                    "harga_ori" => $iiDataSub->nilai,
                    "harga_bom" => $iiDataSub->harga,
                );
                if (!isset($iiDataSub->subtotal)) {
                    $iiDataSub->subtotal = $iiDataSub->jml * $iiDataSub->harga;
                }
                if ($iiDataSub->jenis == "produk") {
                    $produkKomposisiFaseSub[$iiDataSub->fase_id][$iiDataSub->sub_fase_id][$iiDataSub->jenis][$iiDataSub->produk_dasar_id]["subtotal"] = $iiDataSub->jml * $iiDataSub->harga;
                    $produkKomposisiFaseSub[$iiDataSub->fase_id][$iiDataSub->sub_fase_id][$iiDataSub->jenis][$iiDataSub->produk_dasar_id] = (array)$iiDataSub;
                    $produkKomposisiFaseSub[$iiDataSub->fase_id][$iiDataSub->sub_fase_id][$iiDataSub->jenis][$iiDataSub->produk_dasar_id]["jual"] = $iiDataSub->hrg_jual;
                    $produkKomposisiFaseSub[$iiDataSub->fase_id][$iiDataSub->sub_fase_id][$iiDataSub->jenis][$iiDataSub->produk_dasar_id]["ppv"] = $iiDataSub->hrg_ppv;
                }
                if ($iiDataSub->jenis == "target") {
                    $produkKomposisTargetSub[$prodID][$iiDataSub->fase_id][$iiDataSub->sub_fase_id] = (array)$iiDataSub;
                }
                if ($iiDataSub->jenis == "biaya") {
                    $produkKomposisiFaseSub[$iiDataSub->fase_id][$iiDataSub->sub_fase_id][$iiDataSub->jenis][$iiDataSub->id] = (array)$iiDataSub;
                }
                $FaseSubNama[$iiDataSub->fase_id][$iiDataSub->sub_fase_id] = $iiDataSub->sub_fase_nama;
            }
        }
        else {
            $produkKomposisiFase = array();
        }
        //relasi jadi option atau input

        $produk_komposisi_fase_sub = $produkKomposisiFaseSub;
        $sub_fase_nama = $FaseSubNama;
        $produk_fase = $produkFase;
        $produk_komposisi_fase = $produkKomposisiFase;
        $produkKomposisiFaseHeaderMini = array(
            "produk" => array(
                "produk_dasar_id" => "BB",
                "satuan" => "UOM",
                "ppv" => "HPPV",
                "nilai" => "HS",
                "harga" => "HA",
                "jml" => "JML",
                "subtotal" => "SUB",
            ),
            "biaya" => array(
                "produk_dasar_id" => "JASA",
                "cat_id" => "CAT",
                "keterangan" => "ket",
                "satuan_id" => "UOM",
                "harga" => "HRG",
                "jml" => "JML",
                "subtotal" => "SUB",
            ),
        );
        $produk_komposisi_fase_header_mini = $produkKomposisiFaseHeaderMini;
        $produkNama = $tempProdukMaster[0]->nama;
        $relSuppliesHeader = array(
            "cat_id" => "cat_nama",
            "satuan_id" => "satuan",
            "produk_dasar_id" => "produk_dasar_nama",
            "harga_ori" => "harga",
            "harga_bom" => "harga_bom",
            "employee_id" => "employee_nama",
            "akses_id" => "hak_akses_nama",
            // "harga_bom"=>"harga_bom",
        );
        $produkKomposisiFaseHeader = array(
            "produk" => array(
                "produk_dasar_id" => "Material",
                "satuan" => "UoM",
                "nilai" => "H.HPP",
                "ppv" => "H.PPV",
                "jual" => "H.JUAL STD",
                "harga" => "Hrg Anggaran",
                "jml" => "Jml",
                "subtotal" => "Subtotal",
            ),
            "biaya" => array(
                "produk_dasar_id" => "Jasa",
                "cat_id" => "Kategori biaya",
                "satuan_id" => "satuan",
                "keterangan" => "ket",
                // "harga_ori"       => "harga standar",
                "harga" => "Harga",
                "jml" => "Jml",
                "subtotal" => "Subtotal",
            ),
            // "target" => array(
            //     "produk_dasar_id" => "Produk fase(wip)",
            //     // "gudang2_id"         => "fase proses lanjut*",
            // ),
            // "timwork" => array(
            //     "employee_id" => "nama",
            //     "akses_id" => "hak akses",
            //     // "gudang2_id"         => "fase proses lanjut*",
            // ),
            "jual" => array(
                "nilai" => "BOM",
                "harga" => "JUAL",
                "jml" => "Jml",
                "subtotal" => "Subtotal",
            ),
            "room" => array(
                "room_nama" => "Nama Ruang",
                "room_ket" => "Keterangan",
            ),
            "produk_room" => array(
                "produk_dasar_id" => "Material",
                "satuan" => "UoM",
                "nilai" => "H.HPP",
                "ppv" => "H.PPV",
                "jual" => "H.JUAL STD",
                "harga" => "Hrg Anggaran",
                "avail" => "Jml Avail",
                "jml" => "Jml",
                "subtotal" => "Subtotal",
            ),
            "biaya_room" => array(
                "produk_dasar_id" => "Jasa",
                "satuan_id" => "satuan",
                "cat_id" => "Kategori biaya",
                // "harga_ori"       => "harga standar",
                "harga" => "Harga",
                "avail" => "Jml Avail",
                "jml" => "Jml",
                "subtotal" => "Subtotal",
            ),
        );
        $produk_komposisi_fase_header = $produkKomposisiFaseHeader;

        //KLO ADA UPDATE UBAH DI SINI AJA
        $rincianProject = "";
        $total_anggaran = 0;
        if (count($sumarryProject) > 0) {
            $rincianProject .= "<div class='panel panel-body no-padding table-responsive'>
                                <h5 class='text-bold text-muted'>Ringkasan Anggaran <r>($produkNama)</r></h5>";
            $rincianProject .= "<table class='table dataTable compact display table-bordered table-condensed'>";
            $rincianProject .= "<thead>";
            $rincianProject .= "<tr>";
            $rincianProject .= "<th>No</th>";
            $rincianProject .= "<th class='text-center'>Rencana Kerja</th>";
            $rincianProject .= "<th class='text-center'>Qty</th>";
            $rincianProject .= "<th class='text-center'>Hrg BOM/Unit</th>";
            $rincianProject .= "<th class='text-center'>Total Hrg BOM</th>";
            $rincianProject .= "<th class='text-center'>Hrg Jual/Unit</th>";
            $rincianProject .= "<th class='text-center'>Total Hrg Jual</th>";
            $rincianProject .= "<th class='text-center'>Total R/L</th>";
            $rincianProject .= "</tr>";
            $rincianProject .= "</thead>";
            $rincianProject .= "<tbody>";

            $no = 0;
            $subtotal = 0;
            $subtotalTotal = 0;
            $subtotalTotalJual = 0;
            foreach ($produk_fase as $k => $sumarryProdukFase_0) {
                $no++;
                $anggaran_total = 0;
                foreach ($produk_komposisi_fase_sub[$k] as $jenis_ => $arrAgr0) {
                    $nilai_anggaran = 0;
                    foreach ($arrAgr0 as $jenis => $arrAgr) {
                        switch ($jenis) {
                            case "produk":
                                foreach ($arrAgr as $ks => $prdAgr) {
                                    $nilai_anggaran += $prdAgr['subtotal'];
                                }
                                break;
                            case "biaya":
                                foreach ($arrAgr as $ks => $prdAgr) {
                                    $nilai_anggaran += $prdAgr['subtotal'];
                                }
                                break;
                        }
                    }
                    $anggaran_total += $nilai_anggaran;
                }
                $subtotal = $anggaran_total;
                $subtotalRata = $anggaran_total / $sumarryProdukFase_0['qty'];
                $subtotalJual = $produk_komposisi_fase[$k]['jual'][0]['harga'];
                $totalJual = $produk_komposisi_fase[$k]['jual'][0]['harga'] * $sumarryProdukFase_0['qty'];
                $rincianProject .= "<tr onclick=\"showHideRow($k);\">";
                $rincianProject .= "<td class='text-center text-bold'>$no</td>";
                $limitNama = strlen($sumarryProdukFase_0['nama']) > 35 ? substr($sumarryProdukFase_0['nama'], 0, 32) . "..." : $sumarryProdukFase_0['nama'];
                $rincianProject .= "<td class='text-left text-link text-bold' title='klik " . $sumarryProdukFase_0['nama'] . " untuk melihat detail'>" . $limitNama . "</td>";
                $rincianProject .= "<td class='text-left text-link text-bold'>" . $sumarryProdukFase_0['qty'] . "</td>";
                $rincianProject .= "<td>" . formatField("subtotal", $subtotalRata) . "</td>";
                $rincianProject .= "<td>" . formatField("subtotal", $subtotal) . "</td>";
                $rincianProject .= "<td>" . formatField("subtotal", $subtotalJual) . "</td>";
                $rincianProject .= "<td>" . formatField("subtotal", $totalJual) . "</td>";
                $rincianProject .= "<td>" . formatField("subtotal", $totalJual - $subtotal) . "</td>";
                $rincianProject .= "</tr>";
                $rincianProject .= "<tr id='hr_$k' class='hiddenx'>";
                $rincianProject .= "<td colspan='8' class='bg-olive text-black'>";
                $rincianProject .= "<div id='wrapper_$k' class='open' styles='height:0px;overflow: hidden;transition: height 200ms;'>";
                $rincianProject .= "<div id='height_$k'>";
                $fase_urut = $k;
                foreach ($produk_komposisi_fase_sub[$k] as $nSubFase => $subFaseData) {
                    $sub_nama = isset($sub_fase_nama[$k][$nSubFase]) ? $sub_fase_nama[$k][$nSubFase] : "####";
                    $rincianProject .= "<div class='box'>";
                    $rincianProject .= "<div class='box-header text-bold text-uppercase text-primary'>$sub_nama</div>";
                    $rincianProject .= "<div class='box-body no-padding'>";
                    $faseSubTotal = 0;
                    foreach ($produk_komposisi_fase_header_mini as $hFieldKey => $hLabelData) {
                        switch ($hFieldKey) {
                            case "produk":
                                $rincianProject .= "<table style='' class='table dataTable compact display striped table-bordered'>";
                                $rincianProject .= "<thead>";
                                $rincianProject .= "<tr class='bg-gray'>";
                                $rincianProject .= "<th>No</th>";
                                foreach ($hLabelData as $hField => $hLabel) {
                                    $rincianProject .= "<th>$hLabel</th>";
                                }
                                $rincianProject .= "</tr>";
                                $rincianProject .= "</thead>";
                                $rincianProject .= "<tbody>";
                                $i = 0;
                                $presub = 0;
                                if (isset($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["produk"]) && sizeof($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["produk"])) {
                                    foreach ($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["produk"] as $aa => $DataRelsupplies) {
                                        $tID = $DataRelsupplies["id"];
                                        $presub += $DataRelsupplies["jml"] * $DataRelsupplies["harga"];
                                        $rincianProject .= "<tr>";
                                        $i++;
                                        $rincianProject .= "<td>$i</td>";
                                        foreach ($hLabelData as $hField => $hLabel) {
                                            $transformKey = isset($relSuppliesHeader[$hField]) ? $relSuppliesHeader[$hField] : $hField;
                                            $val = isset($DataRelsupplies[$transformKey]) ? $DataRelsupplies[$transformKey] : "";
                                            $rincianProject .= "<td>" . formatField($hField, $val) . "</td>";

                                        }
                                        $rincianProject .= "</tr>";
                                    }
                                }
                                $rincianProject .= "</tbody>";
                                $rincianProject .= "<tfoot class='text-bold'>";
                                $rincianProject .= "<tr>";
                                $rincianProject .= "<td colspan='" . count($hLabelData) . "' class='text-right'>Total</td>";
                                $rincianProject .= "<td>" . formatField("subtotal", $presub) . "</td>";
                                $rincianProject .= "</tr>";
                                $rincianProject .= "</tfoot>";
                                $rincianProject .= "</table>";

                                $faseSubTotal += $presub;
                                break;
                            case "biaya":
                                $rincianProject .= "<table style='' class='table dataTable compact display table-bordered'>";
                                $rincianProject .= "<thead>";
                                $rincianProject .= "<tr class='bg-gray'>";
                                $rincianProject .= "<th>No</th>";
                                foreach ($hLabelData as $hField => $hLabel) {
                                    $rincianProject .= "<th>$hLabel</th>";
                                }
                                $rincianProject .= "</tr>";
                                $rincianProject .= "</thead>";
                                $rincianProject .= "<tbody>";
                                //bagaian data relasi komposisi
                                $i = 0;
                                $presub = 0;
                                if (isset($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["biaya"]) && sizeof($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["biaya"]) > 0) {
                                    foreach ($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["biaya"] as $DataRelsuppliesBiaya) {
                                        $presub += $DataRelsuppliesBiaya["jml"] * $DataRelsuppliesBiaya["harga"];
                                        $rincianProject .= "<tr>";
                                        $i++;
                                        $rincianProject .= "<td>$i</td>";
                                        foreach ($hLabelData as $hField => $hLabel) {
                                            $transformKey = isset($relSuppliesHeader[$hField]) ? $relSuppliesHeader[$hField] : $hField;
                                            $val = isset($DataRelsuppliesBiaya[$transformKey]) ? $DataRelsuppliesBiaya[$transformKey] : "";
                                            $rincianProject .= "<td>" . formatField($hField, $val) . "</td>";
                                        }
                                        $rincianProject .= "</tr>";
                                    }
                                }
                                $rincianProject .= "</tbody>";
                                $rincianProject .= "<tfoot class='text-bold'>";
                                $rincianProject .= "<tr>";
                                $rincianProject .= "<td colspan='" . count($hLabelData) . "' class='text-right'>Total</td>";
                                $rincianProject .= "<td>" . formatField("subtotal", $presub) . "</td>";
                                $rincianProject .= "</tr>";
                                $rincianProject .= "</tfoot>";
                                $rincianProject .= "</table>";

                                $faseSubTotal += $presub;
                                break;
                            case "jual":
                                if (isset($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["jual"]) && sizeof($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["jual"])) {
                                    foreach ($produk_komposisi_fase_sub[$fase_urut][$nSubFase]["jual"] as $aa => $DataRelsupplies) {
                                        foreach ($hLabelData as $hField => $hLabel) {
                                            $transformKey = isset($relSuppliesHeader[$hField]) ? $relSuppliesHeader[$hField] : $hField;
                                            $val = isset($DataRelsupplies[$transformKey]) ? $DataRelsupplies[$transformKey] : "";

                                        }
                                    }
                                }
                                break;
                        }
                    }
//                    $rincianProject .= "<table style='' class='table dataTable compact display table-bordered'>";
//                    $rincianProject .= "<thead class='text-bold'>";
//                    $rincianProject .= "<tr>";
//                    $rincianProject .= "<th colspan='' class='text-right fa-2x'>Total</th>";
//                    $rincianProject .= "<th class='fa-2x bg-info text-bold'>" . formatField("subtotal", $faseSubTotal) . "</th>";
//                    $rincianProject .= "</tr>";
//                    $rincianProject .= "</thead>";
//                    $rincianProject .= "</table>";
                    $rincianProject .= "</div>";
                    $rincianProject .= "</div>";
                }
                $rincianProject .= "<table style='' class='table dataTable compact display table-bordered'>";
                $rincianProject .= "<thead class='text-bold'>";
                $rincianProject .= "<tr>";
                $rincianProject .= "<th colspan='' class='text-right fa-2x'>Total</th>";
                $rincianProject .= "<th class='fa-2x bg-info text-bold'>" . formatField("subtotal", $subtotal) . "</th>";
                $rincianProject .= "</tr>";
                $rincianProject .= "</thead>";
                $rincianProject .= "</table>";
                $rincianProject .= "</div>";
                $rincianProject .= "</div>";
                $rincianProject .= "</td>";
                $rincianProject .= "</tr>";
                $subtotalTotal += $subtotal;
                $subtotalTotalJual += $totalJual;
            }

            $rincianProject .= "</tbody>";
            $rincianProject .= "<tfoot>";

//            $rincianProject .= "<tr>";
//            $rincianProject .= "<td colspan='6' class='text-right'>Total Anggaran</td>";
//            $rincianProject .= "<td colspan='2' class='text-left'>" . formatField("subtotal", $subtotalTotal) . "</td>";
//            $rincianProject .= "</tr>";
//            $rincianProject .= "<tr>";
//            $rincianProject .= "<td colspan='6' class='text-right'>Total Jual Project</td>";
//            $rincianProject .= "<td colspan='2' class='text-left'>" . formatField("subtotal", $subtotalTotalJual) . "</td>";
//            $rincianProject .= "</tr>";

            $_SESSION[$cCode]['main']['projectHarga'] = $subtotalTotalJual;

            $_SESSION[$cCode]['main']['no_kontrak'] = $_SESSION[$cCode]['items7'][0]["ref_kontrak"];
            $_SESSION[$cCode]['main']['tgl_kontrak'] = $_SESSION[$cCode]['items7'][0]["tgl_kontrak"];
            $_SESSION[$cCode]['main']['startDate'] = $_SESSION[$cCode]['items7'][0]["tgl_mulai_project"];
            $_SESSION[$cCode]['main']['endDate'] = $_SESSION[$cCode]['items7'][0]["tgl_akhir_project"];
            $_SESSION[$cCode]['main']['efakturSource'] = $_SESSION[$cCode]['main']["nomer"];
//
//
//            [no_kontrak] => 3514684685468416954
//            [efakturSource] => 588so.1.10.5
//            [tgl_kontrak] => 2024-09-17
//            [startDate] => 2024-09-18
//            [endDate] => 2024-09-26

//            $_SESSION[$cCode]['main']['ppn'] = ($_SESSION[$cCode]['items'][0]['ppnFactor']/100) * $subtotalTotalJual;
//            $_SESSION[$cCode]['items']['harga'] = $subtotalTotalJual;

            //MANUAL INJECT ITEMs
            $_SESSION[$cCode]['items'][$produkProjectPid]['harga'] = $subtotalTotalJual;
//            $_SESSION[$cCode]['items'][0]['sub_ppn'] = ($_SESSION[$cCode]['items'][0]['ppnFactor']/100) * $subtotalTotalJual;
//            $_SESSION[$cCode]['items'][0]['ppn'] = ($_SESSION[$cCode]['items'][0]['ppnFactor']/100) * $subtotalTotalJual;
//            $_SESSION[$cCode]['items'][0]['nilai_untung'] = ($subtotalTotalJual-$subtotalTotal);
//            $_SESSION[$cCode]['items'][0]['nilai_rugi'] = ($subtotalTotalJual-$subtotalTotal) > 0 ? 0 : ($subtotalTotal-$subtotalTotalJual);
//            $_SESSION[$cCode]['items'][0]['nilai_final_rugilaba'] = ($subtotalTotalJual-$subtotalTotal) > 0 ? ($subtotalTotalJual-$subtotalTotal) : ($subtotalTotal-$subtotalTotalJual);
//            $_SESSION[$cCode]['items'][0]['subtotal'] = $subtotalTotalJual;

            //MANUAL INJECT ITEMs
//            arrPrint($_SESSION[$cCode]['items']);

            $bg_color = $subtotalTotalJual - $subtotalTotal < 0 ? "bg-danger" : "bg-info";
            $kerugin = $subtotalTotalJual - $subtotalTotal < 0 ? " <br><small><r>rugi " . number_format($subtotalTotal - $subtotalTotalJual) . "</r></small>" : "";

            $rincianProject .= "<tr class='$bg_color text-bold fa-2x'>";
            $rincianProject .= "<td colspan='6' class='text-right'>Total R/L $kerugin</td>";
            $rincianProject .= "<td colspan='2' class='text-left'>" . formatField("subtotal", $subtotalTotalJual - $subtotalTotal) . "</td>";
            $rincianProject .= "</tr>";
            $rincianProject .= "</tfoot>";
            $rincianProject .= "</table>";
            $rincianProject .= "</div>";
            $rincianProject .= "<div>";
            $rincianProject .= "</div>";
            $rincianProject .= "</div>";
            $rincianProject .= "</div>";

            if ( !isset($_SESSION[$cCode]['items'][$produkProjectPid]['subtotal']) ) {
                $rincianProject .= "<script>
                    top.$('input[name=harga_$produkProjectPid]').blur();
                </script>";
            }

            //ORI
//            if ($_SESSION[$cCode]['items'][$produkProjectPid]['harga'] == 0) {
//                $rincianProject .= "<script>
//                    top.$('input[name=harga_$produkProjectPid]').blur();
//                </script>";
//            }
        }
        //KLO ADA UPDATE UBAH DI SINI AJA

        /*
         * TERMIN
         */
        $terminproject = array();
        $tr->setFilters(array());
        $tr->addFilter("project_id='$produkProjectPid'");
        $tr->addFilter("jenis='588so'");
        $tr->addFilter("target_jenis='7499'");
        $tmpTerminPymSrc = $tr->lookUpPayment()->result();

        cekMerah( $this->db->last_query() );
//        matiHere($produkProjectPid);

        if(!empty($tmpTerminPymSrc)){
            foreach($tmpTerminPymSrc as $row){
                $terminproject[] = $row;
            }
        }
        $terminCheckSetting = $_SESSION[$cCode]['items3'][0]['harga'];

        /*
         * PENERIMAAN PEMBAYARAN DARI TERMIN
         */
        $terimabayarproject = array();
        $tr->setFilters(array());
        $tr->addFilter("project_id='$produkProjectPid'");
        $tr->addFilter("jenis='7499'");
        $tr->addFilter("target_jenis='749'");
        $tmpTerimaBayarPymSrc = $tr->lookUpPayment()->result();

        cekMerah( $this->db->last_query() );
//        matiHere($produkProjectPid);

        if(!empty($tmpTerimaBayarPymSrc)){
            foreach($tmpTerimaBayarPymSrc as $row){
                $terimabayarproject[] = $row;
            }
        }

        /*
         * RETENSI / GARANSI (dari payment source)
         */
        $retensiproject = array();
        $tr->setFilters(array());
        $tr->addFilter("project_id='$produkProjectPid'");
        $tr->addFilter("jenis='588so'");
        $tr->addFilter("target_jenis='7488'");
        $tmpRetensiPymSrc = $tr->lookUpPayment()->result();

        if(!empty($tmpRetensiPymSrc)){
            foreach($tmpRetensiPymSrc as $row){
                $retensiproject[] = $row;
            }
        }

        $retensiCheckSetting = $_SESSION[$cCode]['items5'][0]['harga'];

        /*
         * UANG MUKA / DP
         */
        $uangmukaproject = array();
        $tr->setFilters(array());
        $tr->addFilter("project_id='$produkProjectPid'");
        $tr->addFilter("jenis='4467'");
        $tr->addFilter("target_jenis='04467'");
        $tmpUangMukaPymSrc = $tr->lookUpPayment()->result();

        if(!empty($tmpUangMukaPymSrc)){
            foreach($tmpUangMukaPymSrc as $row){
                $uangmukaproject[] = $row;
            }
        }

        $uangmukaCheckSetting = $_SESSION[$cCode]['items4'][0]['harga'];

        $rincianProject .= "
            <script>
                function showHideRow(ids){
                    if( $('#hr_'+ids) && $('#hr_'+ids).hasClass('hidden') ){
                        $('#hr_'+ids).removeClass('hidden');
                        $('#wrapper_'+ids).height( $('#height_'+ids).outerHeight(true) + 10 );
                    }
                    else{
                        $('#wrapper_'+ids).height(0);
                        setTimeout( function(){
                            $('#hr_'+ids).addClass('hidden');
                        }, 450)
                    }
                }
            </script>
            ";

        //endregion DETAILS BOM

        $view_mod = $this->uri->segment(7) == 3 && $this->uri->segment(6) == 4 ? "_mod" : ""; // step 3 - ke step 4

        $data = array(
            "mode" => $this->uri->segment(3) . $view_mod,
            "template" => $this->configUi[$jenisTr]["template"],
            "title" => $this->configUi[$jenisTr]["label"],
            "subTitle" => $this->configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "pihakLabel" => $this->configUi[$jenisTr]["pihakLabel"],
            "mainLabels" => $this->configLayout[$jenisTr]["receiptMainFields"],
            "main" => $mainProp,
            "mainValues" => $_SESSION[$cCode]['main'],
            "detailValues" => $_SESSION[$cCode]['tableIn_detail_values'],
            "itemLabels" => $itemLabels,
            "itemLabels2" => $itemLabels2,
            "itemLabels3" => $itemLabels3,
            "itemLabels3_sub" => $receiptDetail2_sub,
            "noteEnabled" => $noteEnabled,
            "noteEditabled" => $noteEditabled,
            "noteType" => $noteType,
            "imageEnabled" => $imageEnabled,
            "imageType" => $imageType,

            "items" => $_SESSION[$cCode]['items'],
            "items2" => isset($_SESSION[$cCode][$pairedItemTarget]) ? $_SESSION[$cCode][$pairedItemTarget] : array(),
            // "items3" => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : (isset($_SESSION[$cCode]["items3"]) ? $_SESSION[$cCode]["items3"]: array()),
            "items3" => isset($_SESSION[$cCode]["items3_sum"]) ? $_SESSION[$cCode]["items3_sum"] : array(),
            "items_child" => isset($_SESSION[$cCode]['items_child']) ? $_SESSION[$cCode]['items_child'] : array(),
            "itemsChildLabel" => $itemsChildLabel,
            "itemsChildLabelEditable" => $itemsChildEditable,
            "itemsChildGate" => $itemsChildGate,
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            "sumRows" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum] : $this->configLayout[$this->jenisTr]['receiptSumFields'][$targetStepNum],
            "sumRowsAdditional" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFieldsAdditional'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFieldsAdditional'][$targetStepNum] : array(),
            "sumAddRows" => $addRowLabels,
            "sumRows3" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields3'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields3'][$targetStepNum] : isset($this->configLayout[$this->jenisTr]['receiptSumFields3'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields3'][$targetStepNum] : array(),
            "extValueLabels" => isset($this->configCore[$this->jenisTr]['externalValues']) ? $this->configCore[$this->jenisTr]['externalValues'] : array(),
            "extEditableFields" => $editableAddVals,

            "mainAddValues" => $mainAddValues,
            "mainAddFields" => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),

            "mainElements" => $_SESSION[$cCode]['main_elements'],
//            "mainElements" => array(),
            "elements" => $elements,
            "editableElements" => $editableElements,
            "elementConfig" => $elementConfigs,
            "mainInputs" => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
            "elementEditTarget" => MODUL_PATH . "_followupLiveEdit/selectElement/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "actionTarget" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
            "paymentMethod" => isset($tmpTr[0]->pembayaran) ? $tmpTr[0]->pembayaran : "",
            "grandTotal" => isset($_SESSION[$cCode]['main']['grand_total']) ? $_SESSION[$cCode]['main']['grand_total'] : 0,
            "description" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "descriptionAdditional" => isset($_SESSION[$cCode]['main']['description_additional'][$targetStepNum]) ? $_SESSION[$cCode]['main']['description_additional'][$targetStepNum] : "",
            "descriptionAdditionalPreviews" => isset($_SESSION[$cCode]['main']['description_additional']) ? $_SESSION[$cCode]['main']['description_additional'] : array(),
            "descriptionAdditionalRule" => $noteAdditionalEditabled,
            "descriptionMainFollowup" => isset($_SESSION[$cCode]['main']['description_main_followup']) ? $_SESSION[$cCode]['main']['description_main_followup'] : "",
            "descriptionMainFollowupRule" => $noteFollowupEditabled,
            "allowEdit" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowEdit']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowEdit'] : false,
            "allowRemove" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowRemove']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowRemove'] : true,
            "allowCancel" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowCancel']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowCancel'] : false,
            "allowIncrement" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowIncrement']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowIncrement'] : false,
            "editableFields" => isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$targetStepNum] : array(),
            "editableFields2" => isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields2'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields2'][$targetStepNum] : array(),
            "stepLabels" => $stepLabels,
            "rawPrevURL" => $rawPrevURL,
            "rawBuilderURL" => $rawBuilderURL,
            "currentStep" => $targetStepNum,
            "extSteps" => isset($_SESSION[$cCode]['extSteps']) ? $_SESSION[$cCode]['extSteps'] : array(),
            "paySrcs" => isset($_SESSION[$cCode]['paySrcs']) ? $_SESSION[$cCode]['paySrcs'] : array(),
            "extBtns" => $extBtns,
            "extNewBtns" => $extNewBtns,
            "payBtns" => $payBtns,
            "xShipmentBtn" => $xShipmentBtn,
            //==================liveEdit========================
            "followupSegments" => array(
                $this->uri->segment(3),
                $this->uri->segment(4),
                $this->uri->segment(5),
            ),
            "removeItemTarget" => MODUL_PATH . "$itemsRemoveConfig" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "removeSubItemTarget" => MODUL_PATH . "$itemsRemoveConfig2" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateItemFieldTarget" => MODUL_PATH . "$itemsEditableConfig" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateSubItemFieldTarget" => MODUL_PATH . "$itemsEditableConfig2" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateItemChildTarget" => MODUL_PATH . "_followupLiveEdit/updateChildField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateSubItemChildTarget" => MODUL_PATH . "_followupLiveEdit/updateSubItemField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateMainFieldTarget" => MODUL_PATH . "$mainEditableConfig" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateMainSourceTarget" => MODUL_PATH . "_followupLiveEdit/updateSourceField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "clearContentTarget" => MODUL_PATH . get_class($this) . "/clearContent/" . $this->jenisTr . "/" . $this->uri->segment(5),
            "msgWarning" => isset($msgWarning) ? $msgWarning : array(),
            "msgWarning2" => isset($msgWarning2) ? $msgWarning2 : array(),
            "addRows" => $addRows,
            "addRowLabels" => $addRowLabels,
            "deleteSpec" => $deleteSpec,
            "undoSpec" => $undoSpec,
            "rejectionSpec" => $rejectionSpec,
            "rejectionSpecAll" => $rejectionSpecAll,
            "approvalSpec" => $approvalSpec,
            "editSpec" => $editSpec,
            "detailSizeKey" => $detailSizeKey,
            "detilSizeBar" => $detilSizeBar,
            "addMainSourceField" => $addMainSourceField,
            "addMainSourceEdit" => $addMainSourceEdit,
            "definitionButton" => $definitionButton,
            "dpData" => $dpData,
            //--------------------------
            "beforeStepLabels" => $beforeStepLabels,
            "beforeAllStepLabels" => $beforeAllStepLabels,
            "beforeStepWarning" => $beforeStepWarning,
            "itemsKompositID" => $itemsKompositID,
            //-----------------------
            "saldoLocker" => isset($result) ? $result : array(),
            "extractedSubItems2" => isset($_SESSION[$cCode]["extractedSubItems2"]) ? $_SESSION[$cCode]["extractedSubItems2"] : array(),
            "rincianProject" => $rincianProject,

            "extractedSumSubItems" => isset($_SESSION[$cCode]['extractedSumSubItems']) ? $_SESSION[$cCode]['extractedSumSubItems'] : array(),
            "checklistNotePaired" => MODUL_PATH . "_followupLiveEdit/updateChecklistField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/" . $this->uri->segment(8),
            "checklistnote_cek" => isset($_SESSION[$cCode]['main']['checklistnote_cek']) ? $_SESSION[$cCode]['main']['checklistnote_cek'] : 0,

            "tasklistHeader" => array(
                "dtime" => "tgl",
                "no_spk" => "No. SPK",
                "produk_nama" => "nama WO",
                "produk_paket_nama" => "nama Paket",
                "employee_nama" => "pelaksana",
//                "gudang_id" => "gudang",
                "nilai_sub_fase" => "nilai",
                "persen_sub" => "bobot",
                "progress_percent" => "progress",
                "progress_nama" => "status",
            ),
            "tasklist" => $taskList,

            "uangmukaprojectHeader" => array(
                "dtime" => "tgl",
                "no_spk" => "No. SPK",
                "produk_nama" => "nama WO",
                "produk_paket_nama" => "nama Paket",
                "employee_nama" => "pelaksana",
//                "gudang_id" => "gudang",
                "nilai_sub_fase" => "nilai",
                "persen_sub" => "bobot",
                "progress_percent" => "progress",
                "progress_nama" => "status",
            ),
            "uangmukaproject" => $uangmukaproject,
            "uangmukaCheckSetting" => $uangmukaCheckSetting,

            "retensiprojectHeader" => array(
                "dtime" => "tgl",
                "no_spk" => "No. SPK",
                "produk_nama" => "nama WO",
                "produk_paket_nama" => "nama Paket",
                "employee_nama" => "pelaksana",
//                "gudang_id" => "gudang",
                "nilai_sub_fase" => "nilai",
                "persen_sub" => "bobot",
                "progress_percent" => "progress",
                "progress_nama" => "status",
            ),
            "retensiproject" => $retensiproject,
            "retensiCheckSetting" => $retensiCheckSetting,

            "terminprojectHeader" => array(
                "dtime" => "tgl",
                "tagihan" => "harga project",
                "terbayar" => "telah di bayar (Rp)",
                "terbayar_persen" => "telah di bayar (%)",
                "sisa" => "sisa piutang (Rp)",
                "sisa_persen" => "sisa piutang (%)",
                "cek" => "status",
            ),
            "terminproject" => $terminproject,
            "terminCheckSetting" => $terminCheckSetting,

            "terimabayarprojectHeader" => array(
                "dtime" => "tgl",
                "tagihan" => "harga project",
                "nomer" => "nomer",
                "payment_source_keterangan" => "ket",
                "terbayar" => "telah di bayar (Rp)",
                "terbayar_persen" => "telah di bayar (%)",
                "sisa" => "sisa piutang (Rp)",
                "sisa_persen" => "sisa piutang (%)",
                "cek" => "status",
            ),
            "terimabayarproject" => $terimabayarproject,
//            "terimabayarproject" => array(),

            "arrMaterialDist" => $arrMaterialDist,
            "arrMaterialDistHold" => $arrMaterialDistHold,
        );

//        arrPrint($_SESSION);

        if (isset($_SESSION[$cCode]['main'])) {
            $data['pihakID'] = isset($_SESSION[$cCode]['main']['pihakID']) ? $_SESSION[$cCode]['main']['pihakID'] : 0;
            $data['pihakName'] = isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] : "";
        }
        //endregion

        $this->load->view("transaksi", $data);

    }

    public function followupMultiPrePreview()
    {
        $no = rtrim($this->uri->segment(5), "-");

        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $currentStepCode = $this->uri->segment(8);
        $rawBuilderURL = blobEncode(current_url());
        $itemSwaperToMain = $this->configUi[$this->jenisTr]["itemSwaperToMain"][$stepNumber];
        $itemSwaper = $this->configUi[$this->jenisTr]["itemSwaper"][$stepNumber];
//arrPrintPink($this->uri->segment_array());

        $this->load->model("MdlTransaksi");
        $trr = new MdlTransaksi();


        //region extract packing list to item
        $trr->addFilter("id_master='$no'");
        $trr->addFilter("jenis='$currentStepCode'");
        $trr->addFilter("link_id='0'");
        $trListTmp = $trr->lookupAll()->result();
        $items = array();
        $topID = array();
        $trIdSO = "";
        if (sizeof($trListTmp)) {
            foreach ($trListTmp as $tmp) {
                // arrPrint($tmp);
                $listTr[] = $tmp->id;
                // $prevDataReg =$trr->lookupDataRegistriesByMasterID($tmp->id)->result();
                // arrPrint(blobDecode($prevDataReg[0]->items2_sum));
                // arrprint($prevDataReg);
                $topID["ids_prev"] = blobDecode($tmp->ids_prev)[0];
                $trIdSO = blobDecode($tmp->ids_prev)[0];
                foreach ($itemSwaper as $targetKey => $srcKey) {
                    // ceklIme($srcKey);
                    // $items[$tmp->id_top][$targetKey]=
                    if (substr($srcKey, 0, 1) == ".") {
                        //        cekKuning("APA ADANYA");

                        $realCol = ltrim($srcKey, ".");
                        $realValue = $realCol;
                    }
                    else {
                        $realValue = $tmp->$srcKey;
                    }
                    $items[$tmp->id][$targetKey] = $realValue;
                }
                // if(sizeof($prevDataReg)>0){
                //     $tmpMain = blobDecode($prevDataReg[0]->items2_sum);
                //     foreach($tmpMain as $dataReg){
                //         if(!isset($items[$tmp->id]["harga"])){
                //             $items[$tmp->id]["harga"]=0;
                //         }
                //         $items[$tmp->id]["harga"] += $dataReg["harga"];
                //     }
                //
                // }
            }
        }

        //endregion

        //region build item to master dari 582 so
        $tmpRegItemsTop = $trr->lookupDataRegistriesByMasterID($topID["ids_prev"])->result();
        $regItemsTop = array();
        $regMainTop = array();
        $regMainElemenTop = array();
        foreach ($tmpRegItemsTop as $tmpRegItemsTop_0) {
            $regMainTop = blobDecode($tmpRegItemsTop_0->main);
            $regItemsTop = blobDecode($tmpRegItemsTop_0->items);
            $regMainElemenTop = blobDecode($tmpRegItemsTop_0->main_elements);
        }

        foreach ($regItemsTop as $regItemsTop_0) {
            // arrPrint($regItemsTop_0);
            foreach ($itemSwaperToMain as $keyTarget => $keySrc) {
                $regMainTop[$keyTarget] = $regItemsTop_0[$keySrc];
            }
        }
        //endregion
        $trr->setFilters(array());
        $trr->addFilter("id='$no'");
        $tmpMaster = $trr->lookupMainTransaksi()->result();
        $nomer_top["nomer_top"] = $tmpMaster[0]->nomer_top;


        //bagian sub item ber isi fg index by transksi PL
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $selectKolom = "";
        $trReg = new MdlTransaksi();
        $trReg->setFilters(array());
        $trReg->setJointSelectFields("items2_sum,rsltItems3_sub,transaksi_id");
        $trReg->addFilter("transaksi_id in ('" . implode("','", $listTr) . "')");
        $tmpRegTmp = $trReg->lookupDataRegistries()->result();
//        cekHitam($this->db->last_query());
        $selectedFields = array("items2_sum", "rsltItems3_sub");
        $items2 = array();
        $items3 = array();
        foreach ($tmpRegTmp as $tmpReg_0) {
            foreach ($selectedFields as $kol) {
                switch ($kol) {
                    case "items2_sum":
                        $items2["items2"][$tmpReg_0->transaksi_id] = blobDecode($tmpReg_0->items2_sum);
                        break;
                    case "rsltItems3_sub":
                        $items3["items3"][$tmpReg_0->transaksi_id] = blobDecode($tmpReg_0->rsltItems3_sub);
                        $tmpParam = blobDecode($tmpReg_0->rsltItems3_sub);
                        if (sizeof($tmpParam) > 0) {
                            foreach ($tmpParam as $ii => $params) {
                                arrPrint($params);
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["nama"] = $params["produk_nama"];
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["kode"] = isset($params["kode"]) ? $params["kode"] : "-";
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["jml"] = isset($params["qty"]) ? $params["qty"] : 0;
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["satuan"] = isset($params["satuan"]) ? $params["satuan"] : "-";
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["harga"] = isset($params["produk_ord_harga"]) ? $params["produk_ord_harga"] : "-";
                                $items3["items3"][$tmpReg_0->transaksi_id][$ii]["sub_harga"] = isset($params["produk_ord_harga"]) ? $params["produk_ord_harga"] : "-";
                            }
                        }

                        break;
                }
            }
        }
        //         arrPrint($items3);
        // matiHEre();
        //bagian sub detil item bersisi

        // arrPrint($listTr);

        //region builder ankan transaksi
        // $this->db->trans_start();
        // region mengunci transaksi by $no
        if ($this->session->login['ghost'] == 0) {
            // ceklIme($this->session->login['ghost']);
            $this->load->model("Mdls/MdlLockerTransaksi");
            $lt = New MdlLockerTransaksi();
            foreach ($listTr as $id_lock) {
                $lt->addFilter("transaksi_id='$id_lock'");
                $ltTmp = $lt->lookupAll()->result();
                // matiHEre(sizeof($ltTmp));
                if (sizeof($ltTmp) == 0) {
                    $ltActive = array(
                        "state" => "active",
                        "produk_id" => "$id_lock",
                        "transaksi_id" => "$id_lock",
                        "cabang_id" => $this->session->login['cabang_id'],
                        "oleh_id" => 0,
                        "oleh_nama" => "",
                        "jenis" => "transaksi",
                        "jenis_locker" => "transaksi",
                        "jumlah" => "0",
                        "gudang_id" => "0",
                    );
                    $ltHold = array(
                        "state" => "hold",
                        "produk_id" => "$id_lock",
                        "transaksi_id" => "$id_lock",
                        "cabang_id" => $this->session->login['cabang_id'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "jenis" => "transaksi",
                        "jenis_locker" => "transaksi",
                        "jumlah" => "1",
                        "gudang_id" => "0",
                    );

                    // insert ke tabel locker transaksi
                    $lt->addData($ltActive) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
                    ceklIme($this->db->last_query());
                    $lt->addData($ltHold) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
                    ceklIme($this->db->last_query());
                }
                else {
                    $byUpdateHold = array();
                    $totalUpdateHold = 0;
                    $insertHold = true;
                    foreach ($ltTmp as $ltSpec) {
                        if (($ltSpec->state == "hold") && ($ltSpec->jumlah == "1")) {
                            $insertHold = false;
                            break;
                        }
                        elseif (($ltSpec->state == "hold")) {
                            $totalUpdateHold += isset($ltSpec->jumlah) ? $ltSpec->jumlah : 0;
                            $byUpdateHold[] = $ltSpec->oleh_id;
                        }
                    }
                    if ($insertHold == true) {
                        if (($totalUpdateHold == 0) && (in_array($this->session->login['id'], $byUpdateHold))) {
                            $ltHold = array(
                                "jumlah" => "1",
                            );
                            $ltWhere = array(
                                "state" => "hold",
                                "produk_id" => "$no",
                                "transaksi_id" => "$no",
                                "jenis" => "transaksi",
                                "jenis_locker" => "transaksi",
                                "oleh_id" => $this->session->login['id'],
                            );
                            $lt->updateData($ltWhere, $ltHold);
                        }
                        else {
                            //                    cekPink("total HOLDnya 0 dan saya BELUM pernah HOLD transaksi ini");
                            $ltHold = array(
                                "state" => "hold",
                                "produk_id" => "$no",
                                "transaksi_id" => "$no",
                                "cabang_id" => $this->session->login['cabang_id'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "jenis" => "transaksi",
                                "jenis_locker" => "transaksi",
                                "jumlah" => "1",
                                "gudang_id" => "0",
                            );
                            $lt->addData($ltHold) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
                        }

                        $ltActive = array(
                            "jumlah" => "0",
                        );
                        $ltWhere = array(
                            "state" => "active",
                            "produk_id" => "$no",
                            "transaksi_id" => "$no",
                            "jenis" => "transaksi",
                            "jenis_locker" => "transaksi",
                        );
                        $lt->updateData($ltWhere, $ltActive);
                        cekHitam($this->db->last_query());
                    }
                    else {
                        //                cekPink("sudah ada yang HOLD");
                    }
                }
            }


        }
        // endregion

        $cCode = "_TR_" . $this->jenisTr;
        if (isset($_SESSION[$cCode])) {
            $_SESSION[$cCode] = null;
            unset($_SESSION[$cCode]);
        }

        //region session init
        if (!isset($_SESSION[$cCode])) {
            $_SESSION[$cCode] = array(
                "items" => array(),
                "main" => array(),
            );
        }
        if (!isset($_SESSION[$cCode]['main'])) {
            $_SESSION[$cCode]['main'] = array();
        }
        if (!isset($_SESSION[$cCode]['items'])) {
            $_SESSION[$cCode]['items'] = array();
        }
        //endregion
        $masterID = $no;
        //REGION BUILD REGISTRY
        $trr = new MdlTransaksi();
        $trr->setFilters(array());
        $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        $tmpReg = $trr->lookupDataRegistries()->result();

        $items2_sum = array();

        $items3_sum = array();
        $items4_sum = array();
        $rsltItems = array();
        $rsltItems2 = array();

        $masterGates = array();
        $childGates = array();
        $childGates2 = array();
        $childGates2_sum = array();
        $childGatesRsltItems = array();
        $childGatesRsltItems2 = array();
        $masterTableInParams = array();
        $childTableInParams = array();
        $childTableInParamsRsltItems = array();
        $childTableInParamsRsltItems2 = array();
        $masterTableInValueParams = array();
        $childTableInValueParams = array();
        $childTableInValueParamsRsltItems = array();
        $childTableInValueParamsRsltItems2 = array();
        $masterAddValues = array();
        $masterAddFields = array();
        $mainElements = array();
        $mainInputs = array();
        $itemsKomposisi = array();
        if (sizeof($tmpReg) > 0) {
            foreach ($tmpReg as $row) {
                foreach ($row as $key_reg => $val_reg) {

                    switch ($key_reg) {
                        case "rsltItems"://
                            $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                            break;
                        case "rsltItems2"://
                            $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                            break;
                        case "items4_sum"://
                            $items4_sum = $items4_sum + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_master"://
                            $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail"://
                            $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail_rsltItems"://
                            $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail_rsltItems2"://
                            $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_master_values"://
                            $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail_values"://
                            $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail_values_rsltItems"://
                            $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                            break;
                        case "tableIn_detail_values_rsltItems2"://
                            $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                            break;
                        case "main_add_values"://
                            $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                            break;
                        case "main_add_fields"://
                            $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                            break;
                        case "main_elements"://
                            $mainElements = unserialize(base64_decode($val_reg));
                            break;
                        case "main_inputs"://
                            $mainInputs = unserialize(base64_decode($val_reg));
                            break;
                        case "items_komposisi"://
                            $itemsKomposisi = unserialize(base64_decode($val_reg));
                            break;
                    }
                }
            }

        }
        else {
            die("Cannot read the registry entries from $masterID!");
        }
        //endregion

        //region replacer Downpayment avail
        if (isset($mainInputs['dp'])) {
            if (isset($this->configUi[$this->jenisTr]["updateDownpayment"][$stepNumber])) {
                //                    arrPrint($mainInputs);
                $this->load->model("Coms/ComLockerValue");
                $mi = new ComLockerValue();
                $mi->addFilter("produk_id='" . $main['masterID'] . "'");
                $mainInputAvail = $mi->fetchBalances("downpayment");
                $lockerVal = $mainInputAvail[0]->nilai;
                //                    $mainValTmp = reversePpn($mainInputs['dp'],"10");
                $mainValTmp_dp = $main['dp_value'];
                $mainValTmp_dp_ppn = $main['dp_ppn_value'];

                if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                    cekOrange();
                    $validate = round($mainInputAvail[0]->nilai - $mainValTmp_dp, 2);
                    if ($lockerVal > 0) {
                        $valnew = $main['new_net1'] - $lockerVal > 0 ? 0 : $main['new_net1'];
                        $main['dp_value'] = $valnew;
                        $main['dp_ppn_value'] = $valnew * 10 / 100;
                    }
                    else {
                        $main['dp_value'] = 0;
                        $main['dp_ppn_value'] = 0;
                        //                        $main['valid_dp'] = 0;
                    }

                    if ($validate > 0) {
                        $mainInputs['dp'] = $mainInputAvail[0]->nilai;

                    }
                    else {
                        if ($validate < 0) {
                            if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                                $main['downpayment'] = $mainInputs['dp'];
                                $mainInputs['downpayment'] = $mainInputs['dp'];
                                $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['dp_ppn_value'];

                            }
                            unset($mainInputs['dp']);
                            //                                cekhere("sini po");
                        }
                        //                        if(!isset($main['valid_dp'])){
                        //                            $main['valid_dp'] = $mainInputAvail[0]->nilai;
                        //                        }

                    }
                }
                else {
                    //                         $mainInputs['dp'] = 0;
                    $main['dp_value'] = 0;
                    $main['dp_ppn_value'] = 0;
                    unset ($mainInputs['dp']);
                }

                if (!isset($main['valid_dp'])) {
                    $main['valid_dp'] = $mainInputAvail[0]->nilai;
                }
            }


        }
        else {
            if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                $main['downpayment'] = $main['dp'];
                $mainInputs['downpayment'] = $main['dp'];
                //                    $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['nilai_tambah_ppn_out'];
                $main['total_ui'] = $masterTableInValueParams['new_net1'] - $main['valid_dp'];
                cekBiru($masterTableInValueParams['new_net1'] . " - " . $main['valid_dp']);
            }
            else {
                if (isset($masterTableInValueParams['new_net1'])) {

                    $main['total_ui'] = $masterTableInValueParams['new_net1'];
                }
                else {
                    $main['total_ui'] = $masterTableInValueParams['nett1'];
                    $main['new_grand_ppn'] = $masterTableInValueParams['grand_ppn'];
                }
            }
        }
        //endregion

        $masterReplacers = array(
            "jenisTrMaster" => $this->jenisTr,
            "jenisTrTop" => $masterTableInParams['jenis_top'],
            "harga" => 0,
            "masterID" => $no,
        );
        foreach ($masterReplacers as $key => $src) {
            $main[$key] = $src;
            $mainValues[$key] = $src;
            $masterGates[$key] = $src;
        }

        //------------------------
        $additionalPackinglist = isset($this->configUi[$this->jenisTr]["additionalPackinglist"][$stepNumber]) ? $this->configUi[$this->jenisTr]["additionalPackinglist"][$stepNumber] : array();
        if (isset($additionalPackinglist['enabled']) && ($additionalPackinglist['enabled'] == true)) {
            //region valid subitem
            $tr->setFilters(array());
            $tr->setJoinedFilter(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $trIdSO)) . ")");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTrSub = $tr->lookupJoinedSubItems();
            showLast_query("hitam");
//            arrPrintPink($tmpTrSub);
//            matiHEre(sizeof($tmpTrSub));

            //region valid sub items
            $extractedSubItems = array();//==untuk urusan update transaksi referer
            $extractedSumSubItems = array();//==untuk urusan update transaksi referer
            $validSubItems = array();
            $validSubItemSends = array();
            $validSubItemReqCancels = array();
            $validSubItemCancels = array();
            $validSunItemPreCancels = array();
            if (sizeof($tmpTrSub) > 0) {
                cekmerah("ada yang mau diekstrak");
                foreach ($tmpTrSub as $rows) {
                    if (!isset($validSubItems[$rows->produk_id])) {
                        $validSubItems[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemSends[$rows->produk_id])) {
                        $validSubItemSends[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemCancels[$rows->produk_id])) {
                        $validSubItemCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemReqCancels[$rows->produk_id])) {
                        $validSubItemReqCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPackeds[$rows->produk_id])) {
                        $validSubItemPackeds[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPreCancels[$rows->produk_id])) {
                        $validSubItemPreCancels[$rows->produk_id] = 0;
                    }

                    $validSubItems[$rows->produk_id] += isset($rows->valid_qty) ? $rows->valid_qty : 0;
                    $validSubItemSends[$rows->produk_id] += isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0;
                    $validSubItemCancels[$rows->produk_id] += isset($rows->cancel_qty) ? $rows->cancel_qty : 0;
                    $validSubItemReqCancels[$rows->produk_id] += isset($rows->req_cancel_qty) ? $rows->req_cancel_qty : 0;
                    $validSubItemPreCancels[$rows->produk_id] += isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0;
                    $validSubItemPackeds[$rows->produk_id] += isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0;

                    if (!isset($extractedSubItems[$rows->produk_id])) {
                        $extractedSubItems[$rows->produk_id] = array();
                    }
                    $extractedSubItems[$rows->produk_id][$rows->id_sub_detail] = array(
                        "id" => $rows->id_sub_detail,
                        "produk_id" => $rows->produk_id,
                        "produk_nama" => $rows->produk_nama,
                        "produk_kode" => $rows->produk_kode,
                        "qty" => $rows->produk_ord_jml,
                        "valid_qty" => $rows->valid_qty,
                        "transaksi_id" => $rows->transaksi_id,
                        "packed_qty" => isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0,
                        "cancel_qty" => $rows->cancel_qty,
                        "outstanding" => $rows->produk_ord_jml - ($rows->produk_ord_jml - $rows->valid_qty),
                        "dikirim_qty" => $rows->produk_ord_diterima,
                    );


                    if (!isset($extractedSumSubItems[$rows->produk_id])) {
                        $extractedSumSubItems[$rows->produk_id] = array();
                    }
                    $extractedSumSubItems[$rows->produk_id]['id'] = $rows->id_sub_detail;
                    $extractedSumSubItems[$rows->produk_id]['produk_id'] = $rows->produk_id;
                    $extractedSumSubItems[$rows->produk_id]['produk_nama'] = $rows->produk_nama;
                    $extractedSumSubItems[$rows->produk_id]['produk_kode'] = $rows->produk_kode;
                    $extractedSumSubItems[$rows->produk_id]['qty'] += $rows->produk_ord_jml;
                    $extractedSumSubItems[$rows->produk_id]['valid_qty'] += $rows->valid_qty;
                    $extractedSumSubItems[$rows->produk_id]['transaksi_id'] += $rows->transaksi_id;
                    $extractedSumSubItems[$rows->produk_id]['packed_qty'] += isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0;
                    $extractedSumSubItems[$rows->produk_id]['sent_qty'] += isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0;
                    $extractedSumSubItems[$rows->produk_id]['req_cancel_qty'] += isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0;
                    $extractedSumSubItems[$rows->produk_id]['cancel_qty'] += $rows->cancel_qty;
                    $extractedSumSubItems[$rows->produk_id]['outstanding'] += $rows->produk_ord_jml - ($rows->produk_ord_jml - $rows->valid_qty);
                    $extractedSumSubItems[$rows->produk_id]['dikirim_qty'] += $rows->produk_ord_diterima;


                }
            }
            //endregion

            //endregion

            //region subitem3 bagian po service/ biaya-biaya

//            $tr = new MdlTransaksi();
//            $tr->setFilters(array());
//            $tr->setJoinedFilter(array());
//            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
//            $tr->addFilterJoin("valid_qty>0");
//            $tmpTrSub_item = $tr->lookupJoinedSubItems2();
//            $extractedSubItems2 = array();//==untuk urusan update transaksi referer
//            $validSubItems2 = array();
//            $validSubItemSends2 = array();
//            $validSubItemReqCancels2 = array();
//            $validSubItemCancels2 = array();
//            $validSubItemPreCancels2 = array();
//            $validSubItemPackeds2 = array();
//            if (sizeof($tmpTrSub_item) > 0) {
//                foreach ($tmpTrSub_item as $rowSub) {
//                    if (!isset($validSubItems2[$rowSub->produk_id])) {
//                        $validSubItems2[$rowSub->produk_id] = 0;
//                    }
//                    if (!isset($validSubItemSends2[$rowSub->produk_id])) {
//                        $validSubItemSends2[$rowSub->produk_id] = 0;
//                    }
//                    if (!isset($validSubItemCancels2[$rowSub->produk_id])) {
//                        $validSubItemCancels2[$rowSub->produk_id] = 0;
//                    }
//                    if (!isset($validSubItemReqCancels2[$rowSub->produk_id])) {
//                        $validSubItemReqCancels2[$rowSub->produk_id] = 0;
//                    }
//                    if (!isset($validSubItemPackeds2[$rowSub->produk_id])) {
//                        $validSubItemPackeds2[$rowSub->produk_id] = 0;
//                    }
//                    if (!isset($validSubItemPreCancels2[$rowSub->produk_id])) {
//                        $validSubItemPreCancels2[$rowSub->produk_id] = 0;
//                    }
//
//                    $validSubItems2[$rowSub->produk_id] += isset($rowSub->valid_qty) ? $rowSub->valid_qty : 0;
//                    $validSubItemSends2[$rowSub->produk_id] += isset($arrTmp__['582spd'][$rowSub->produk_id]) ? $arrTmp__['582spd'][$rowSub->produk_id] : 0;
//                    $validSubItemCancels2[$rowSub->produk_id] += isset($rowSub->cancel_qty) ? $rowSub->cancel_qty : 0;
//                    $validSubItemReqCancels2[$rowSub->produk_id] += isset($rowSub->req_cancel_qty) ? $rowSub->req_cancel_qty : 0;
//                    $validSubItemPreCancels2[$rowSub->produk_id] += isset($arrPreTmp__['1982'][$rowSub->produk_id]) ? $arrPreTmp__['1982'][$rowSub->produk_id] : 0;
//                    $validSubItemPackeds2[$rowSub->produk_id] += isset($arrTmp__['582pkd'][$rowSub->produk_id]) ? $arrTmp__['582pkd'][$rowSub->produk_id] : 0;
//
//                    if (!isset($extractedSubItems2[$rowSub->produk_id])) {
//                        $extractedSubItems2[$rowSub->produk_id] = array();
//                    }
//                    $extractedSubItems2[$rowSub->produk_id][$rowSub->id_sub_detail] = array(
//                        "id" => $rowSub->id_sub_detail,
//                        "produk_id" => $rowSub->produk_id,
//                        "produk_nama" => $rowSub->produk_nama,
//                        "produk_ord_harga" => $rowSub->produk_ord_hrg,
//                        "qty" => $rowSub->produk_ord_jml,
//                        "valid_qty" => $rowSub->valid_qty,
//                        "transaksi_id" => $rowSub->transaksi_id,
//                        "packed_qty" => isset($arrTmp__['582pkd'][$rowSub->produk_id]) ? $arrTmp__['582pkd'][$rowSub->produk_id] : 0,
//                        "sent_qty" => isset($arrTmp__['582spd'][$rowSub->produk_id]) ? $arrTmp__['582spd'][$rowSub->produk_id] : 0,
//                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$rowSub->produk_id]) ? $arrPreTmp__['1982'][$rowSub->produk_id] : 0,
//                        "cancel_qty" => $rowSub->cancel_qty,
//                        "outstanding" => $rowSub->produk_ord_jml - ($rowSub->produk_ord_jml - $rowSub->valid_qty),
//                    );
//                    $rsltItem3_sub[$rowSub->produk_id] = array(
//                        "placeID" => $rowSub->cabang_id,
//                        "gudangID" => 0,
//                        "id" => $rowSub->id_sub_detail,
//                        "produk_id" => $rowSub->produk_id,
//                        "produk_nama" => $rowSub->produk_nama,
//                        "produk_ord_harga" => $rowSub->produk_ord_hrg,
//                        "produk_ord_jml" => $rowSub->produk_ord_jml,
//                        "qty" => $rowSub->produk_ord_jml,
//                        "valid_qty" => $rowSub->valid_qty,
//                        "transaksi_id" => $rowSub->transaksi_id,
//                        "produk_jenis" => $rowSub->produk_jenis,
//
//                    );
//                }
//            }

            //endregion

        }
        //------------------------
//arrPrintWebs($extractedSubItems);
        //region session-swapper
        $swappers = array(
            "main" => $regMainTop + $nomer_top + array("id_top" => $trIdSO),
            "items" => $items,
            "items2" => $items2["items2"],
            "items2_sum" => $items2_sum,
            "items3" => $items3["items3"],
            "items3_sum" => $items3_sum,
            "items4_sum" => $items4_sum,
            "items_child" => isset($itemChildData) ? $itemChildData : array(),
            "rsltItems" => $rsltItems,
            "rsltItems2" => $rsltItems2,
            "rsltItems3_sub" => isset($rsltItem3_sub) ? $rsltItem3_sub : array(),
            "extractedItems" => isset($extractedItems) ? $extractedItems : array(),
            "extractedSubItems" => isset($extractedSubItems) ? $extractedSubItems : array(),
            "extractedSubItems2" => isset($extractedSubItems2) ? $extractedSubItems2 : array(),
            "extractedSumSubItems" => isset($extractedSumSubItems) ? $extractedSumSubItems : array(),


            "tableIn_master" => $masterTableInParams,
            "tableIn_detail" => $childTableInParams,
            "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
            "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
            "tableIn_master_values" => $masterTableInValueParams,
            "tableIn_detail_values" => $childTableInValueParams,
            "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
            "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
            "main_add_values" => $masterAddValues,
            //        ""=>$childAddValues ,
            "main_add_fields" => $masterAddFields,
            //                "main_applets"          => $mainApplets,
            "main_elements" => $mainElements,
            "main_inputs" => $mainInputs,
            "items_komposisi" => $itemsKomposisi,
        );
        foreach ($swappers as $targetVar => $src) {
            $_SESSION[$cCode][$targetVar] = $src;

        }
        //--------
        $this->load->model("Mdls/MdlProdukProject");
        $pp = New MdlProdukProject();
        $pp->addFilter("id=" . $_SESSION[$cCode]['main']['projectID']);
        $ppTmp = $pp->lookupAll()->result();
        $_SESSION[$cCode]['main']['tarifGaransi'] = isset($ppTmp[0]->garansi) ? $ppTmp[0]->garansi : 0;
        //--------
        $this->load->helper("he_value_builder");
        resetValues($this->jenisTr);
        fillValues_he_value_builder($this->jenisTr, $this->uri->segment(7), $this->uri->segment(6), $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);

        //mati_disini("setelah fillValue, akan masuk ke followuppreview");
        $actionTarget = "top.BootstrapDialog.closeAll();top.BootstrapDialog.show(
                                   {
                                       title:'Followup preview',
                                       message: " . 'top.$' . "('<div></div>').load('" . MODUL_PATH . "FollowUp/followupMultiPreview/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/" . $trIdSO . "?rawBuilderURL=$rawBuilderURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        type:top.BootstrapDialog.TYPE_DEFAULT,
                                        draggable:true,
                                        closable:false,
                                        
                                        
                                        }
                                        );";

        echo "<script>top.close_holdon();$actionTarget</script>";
        //endregion

    }

    public function followupMultiPreview()
    {
//        arrPrint($this->uri->segment_array());
        $cCode = $this->cCode;
        $jenisTr = $this->jenisTr;
        $starttime = microtime(true);
        $no = rtrim($this->uri->segment(5), "-");
        $topID = rtrim($this->uri->segment(8), "-");
        $targetStepNum = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $afterTargetStepNum = ($targetStepNum + 1);
        $receipMultiMainFields = $this->configLayout[$this->jenisTr]["receiptMultiMainFields"];
        $receiptMultiItemFields = $this->configLayout[$this->jenisTr]["receiptMultiItemFields"];
        $receiptMultiItemSubFields = $this->configLayout[$this->jenisTr]["receiptMultiItemSubFields"];
        $receiptMultitemSubField_detils = $this->configLayout[$this->jenisTr]["receiptMultitemSubField_detils"][$targetStepNum];
        $elementConfigs = isset($this->configUi[$this->jenisTr]['receiptElements']) ? $this->configUi[$this->jenisTr]['receiptElements'] : array();
        $allowFollowup = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup'] : true;
        $rawPrevURL = blobEncode(current_url());
        $rawBuilderURL = $_GET['rawBuilderURL'];
        //region SIGNATURE
        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            //            cekkuning("ada signs");
            $sCtr = 0;
            foreach ($tmpSign as $row) {

                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }
        else {
            //            cekkuning("TAK ada signs");
        }
        //endregion


        //region approval spec
        $currentStepIndex = array_search($currentStepNum, $signNumbers, true);
        $origTCode = heGetOriginTCode($this->jenisTr);
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $userGroup_editElementAllowed = $this->config->item("userGroup_editElementAllowed") != NULL ? $this->config->item("userGroup_editElementAllowed") : array();
        $thisStepGID = isset($this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup'] : "";
        $nextStepGID = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup'] : "";
        $hideFollowUp = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp'] : false;
        $editElementAllowed = array_intersect($userGroup_editElementAllowed, $mems);
        $allowFollowup = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup'] : true;

        $preProcRevConfig = null != $this->config->item("hePreProcessors");
        $preCompRevConfig = null != $this->config->item("heComponents");

        $deleteSpec = array(
            "label" => "cannot delete",
            "targetUrl" => "",
            "warning" => "",
        );
        $undoSpec = array(
            "label" => "cannot undo",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpec = array(
            "label" => "cannot reject 1 step",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpecAll = array(
            "label" => "cannot reject all steps",
            "targetUrl" => "",
            "warning" => "",
        );
        $approvalSpec = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectAllAllowed = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $editSpec = array(
            "label" => "cannot edit",
            "targetUrl" => "",
            "warning" => "",
        );
        $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        //==approve
        if ($targetStepNum > $currentStepNum) {
            if ($allowFollowup == true) {
                if (isset($_SESSION[$cCode]['lockerPayment']['allowedFollow']) && $_SESSION[$cCode]['lockerPayment']['allowedFollow'] == true) {
                    if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                        if (isset($this->accessList[$this->jenisTr])) {
                            if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {

                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                        }
                        else {
                            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                                //                cekBiru(":: $currentStepNum :: $targetStepNum ::");
                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                $msgWarning2 = array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                //                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $approvalSpec = array(
                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                            );
                        }
                        else {
                            cekUngu("tidak ada approve");
                        }
                    }
                }
                else {
                    if (isset($this->accessList[$this->jenisTr])) {
                        if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(

                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            $msgWarning2 = array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {

                                $approvalSpec = array(
                                    //                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum/$topID",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                        else {

                        }
                    }
                }
            }
            if ((isset($lockerPreDownpayment)) && ($lockerPreDownpayment == true)) {
                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                $msgWarning2 = array();
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $paymentSrcCek['label'],
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
            if (isset($lockShipment) && ($lockShipment == true)) {
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $lockShipmentLabel,
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
        }
        else {
            //            cekmerah("NOT possible to approve");
        }
        //endregion
        if (sizeof($signNumbers) > 0) {
            if ($currentStepIndex > 0) {
                $beforeCurrentIndex = ($currentStepIndex - 1);
                $beforeCurrentStep = $signNumbers[$beforeCurrentIndex];
            }
            else {

                $beforeCurrentStep = 0;
            }

            $masterRevertStep = $beforeCurrentStep;
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "", $this->configUiJenis)) {
                $mComponents = isset($this->configCore[$this->jenisTr]['components'][$currentStepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$currentStepNum]['master'] : array();

                if (sizeof($mComponents) > 0) {
                    $comNames = array();
                    foreach ($mComponents as $cSpec) {
                        $comNames[] = $cSpec['comName'];
                    }
                    if (in_array("Jurnal", $comNames)) {
                        //==tidak bisa di-revert
                    }
                    else {
                        $allowRevert = true;
                        $revertLabel = "undo";
                        $childRevertStep = -($currentStepNum);
                        $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    }
                }
                else {
                    $allowRevert = true;
                    //                    $revertLabel = $masterRevertStep . "undo " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                    $revertLabel = "undo";
                    $childRevertStep = -($currentStepNum);
                    $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";
                }

            }

        }
        //region check if i may approve or unapprove current transaction
        if (isset($this->configUi[$jenisTr]['steps'][$targetStepNum])) {
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                $allowFollowup = true;
                $buttonLabel = $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'];
                $acceptTarget = MODUL_PATH . __CLASS__ . "/doFollowupMulti/$jenisTr/$no/$targetStepNum/$currentStepNum";
                if (isset($masterRevertStep)) {
                    $mPreProcs = heCountPreProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mPostProcs = heCountPostProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mComs = heCountComponents_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);

                    //==set default to ENABLED
                    $childRevertStep = -($currentStepNum);
                    $rejectionLabel = "reject (def)";
                    $rejectionTarget = MODUL_PATH . __CLASS__ . "/dontFollowup/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    if (sizeof($mPreProcs['reversable']) > 0 || sizeof($mPostProcs['reversable']) > 0) {//maka cek dulu, boleh  cancel apa kagak
                        //==set default to DISABLED
                        $rejectionLabel = "can not reject";
                        $rejectionTarget = "";

                    }
                    else {//==langsung bisa dicancel
                        if (heJournalExists($this->jenisTr, $currentStepNum)) {
                            $rejectionLabel = "can not reject";
                            $rejectionTarget = "";
                        }
                        else {
                            //boleh
                        }

                    }

                }
            }
        }
        //endregion

        $editableElements = array();
        $mainElements = $_SESSION[$cCode]["main_elements"];
        if (sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $aKey => $aSpec) {
                    if (array_key_exists($aKey, $mainElements) && in_array($targetStepNum, $aSpec['editPoints'])) {
                        $editableElements[] = $aKey;
                    }
                    if (isset($relElementConfigs[$aKey])) {
                        foreach ($relElementConfigs[$aKey] as $mainRel => $relData) {
                            foreach ($relData as $relKey => $relDetails) {
                                //                                if (in_array("o_seller_spv", $mems)) {
                                if (sizeof($editElementAllowed) > 0) {
                                    if (array_key_exists($relKey, $mainElements) && in_array($targetStepNum, $relDetails['editPoints'])) {
                                        $editableElements[] = $relKey;

                                        if (array_key_exists($relKey, $relElementConfigs)) {
                                            //                                        cekBiru("rel element $relKey mentrigger kelompoknya sendiri");
                                            foreach ($relElementConfigs[$relKey] as $ownRel => $ownData) {
                                                foreach ($ownData as $ownKey => $ownDetails) {
                                                    if (array_key_exists($ownKey, $mainElements) && in_array($targetStepNum, $ownDetails['editPoints'])) {
                                                        $editableElements[] = $ownKey;
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }
                                //                                }
                            }
                        }
                    }
                }
            }
        }

        $stepLabels = array();
        foreach ($this->configUi[$this->jenisTr]['steps'] as $num => $sSpec) {
            $stepLabels[$num] = $sSpec['label'];
        }
        $elStr = array();
        $elements = array();
        $aFilter = array();

        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                switch ($eSpec['elementType']) {
                    case "dataModel":
                        $addStr = "";
                        $editStr = "";
                        $amdlName = $eSpec['mdlName'];
                        $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                        $elStr[$eName] = "";
                        $this->load->model("Mdls/" . $amdlName);
                        $labelSrc = $eSpec['labelSrc'];
                        $keySrc = $eSpec['key'];
                        $oo = new $amdlName();
                        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);
                        if (sizeof($aFilter) > 0) {
                            foreach ($aFilter as $filter) {
                                $exFilter = explode("=", $filter);
                                if (sizeof($exFilter) > 1) {
                                    if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                        $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                        $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                    }
                                }
                            }
                        }
                        $addClick = "";
                        $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array(
                            "viewers" => array(),
                            "creators" => array(),
                            "creatorAdmins" => array(),
                            "updaters" => array(),
                            "updaterAdmins" => array(),
                            "deleters" => array(),
                            "deleterAdmins" => array(),
                            "historyViewers" => array(),
                        );
                        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        }
                                        );";
                                $addStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$addClick\"><span class='fa fa-plus'></span></a>";
                            }
                        }

                        $tmpo = $oo->lookupAll()->result();
                        $elPair[$amdlName] = array();
                        $selectorTarget = MODUL_PATH . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";

                        $elStr[$eName] .= "<div class='box-body'>";
                        $elStr[$eName] .= "<select class='form-control' onchange=\"top.$('#result').load('$selectorTarget');\">";
                        $elStr[$eName] .= "<option value=''>-select-</option>";
                        if (sizeof($tmpo) > 0) {
                            foreach ($tmpo as $row) {

                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";

                            }
                        }
                        $elStr[$eName] .= "</select>";
                        $elStr[$eName] .= "</div class='box-header'>";

                        $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                        $defValue = "";
                        if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                            if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                $defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                    $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                    $defValue .= "<tr>";
                                    $defValue .= "<td align='left'>$label";
                                    $defValue .= "</td>";
                                    $defValue .= "<td align='left'>" . $fieldLabel;
                                    $defValue .= "</td>";
                                    $defValue .= "</tr>";
                                }
                                $defValue .= "</table>";
                            }
                        }


                        if ($defKey > 0) {
                            if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                    $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        }
                                        );";

                                    $editStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$editClick\"><span class='fa fa-pencil'></span></a>";
                                }
                            }
                        }

                        $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                        $elStr[$eName] .= "</div id='el$amdlName'>";
                        $elStr[$eName] .= "<div class='box-footer'>";

                        $elStr[$eName] .= "<span class='pull-right'>$editStr $addStr</span>";
                        $elStr[$eName] .= "</div class='box-footer'>";

                        $elements[$eName] = array(
                            "mdlName" => $eSpec['mdlName'],
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );


                        break;
                    case "dataField":
                        $elStr[$eName] = "";
                        $defaultValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                        $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";
                        //                        $elStr[$eName] .="<div class='box'>";

                        $elStr[$eName] .= "<div class='box-body'>";
                        switch ($eSpec['inputType']) {
                            case "text":
                                $elStr[$eName] .= "<input type=text class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                            case "date":
                                $elStr[$eName] .= "<input type=date class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                        }
                        $elStr[$eName] .= "</div class='box-body'>";

                        $elements[] = array(
                            "mdlName" => null,
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );
                        break;
                }
            }
        }
        // arrPrint($_SESSION[$cCode]["items"]);

        //region preview bottom elements

        $saveWarning = "";
        $buttonLabel = $this->configUi[$jenisTr]["steps"][$targetStepNum]['actionLabel'];
        // if (isset($this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum])) {
        //     $saveWarning .= "clicking <strong>$buttonLabel</strong> button will make transaction state to: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . "</strong>";
        //     $saveWarning .= "<br>It would need to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum]['userGroup'] . "</strong>";
        // }
        // else {
        $saveWarning .= "clicking <strong>$buttonLabel</strong> button will instantly make transaction state to <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . " and make complete</strong>";
        // }

        //endregion
        $subData = array();
        $sumRows = array();
        foreach ($_SESSION[$cCode]["items"] as $Trid => $trData) {
            // arrPrint($trData);
            $subData["details"][$Trid]["produk"] = isset($_SESSION[$cCode]["items2"][$Trid]) ? $_SESSION[$cCode]["items2"][$Trid] : array();
            $subData["details"][$Trid]["biaya"] = isset($_SESSION[$cCode]["items3"][$Trid]) ? $_SESSION[$cCode]["items3"][$Trid] : array();
            if (sizeof($trData) > 0) {
                $subtotal = 0;
                foreach ($trData as $tmpItems) {
                    // arrprint($tmpItems);
                    // $subtotal +=$tmpItems["sub_harga"];
                }
            }
            $sumRows["sub_harga"] = $subtotal;
        }
        //------------------------
        $addMainSource = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum] : array();
        $addMainSourceField = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"] : array();
        $addMainSourceEdit = isset($this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"]) ? $this->configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"] : array();
        //------------------------
        $additionalPackinglist = isset($this->configUi[$this->jenisTr]["additionalPackinglist"][$targetStepNum]) ? $this->configUi[$this->jenisTr]["additionalPackinglist"][$targetStepNum] : array();
        // arrprint($subData);
        $data = array(
            "mode" => $this->uri->segment(3),

            "template" => $this->configUi[$jenisTr]["template"],
            "title" => $this->configUi[$jenisTr]["label"],
            "subTitle" => $this->configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "mainLabels" => $receipMultiMainFields,
            "subMainLabel" => $receiptMultiItemFields,
            "subItemLabels" => $receiptMultiItemSubFields,
            "subItemLabel2" => $receiptMultitemSubField_detils,
            "subData" => $subData,
            "sumRows" => $sumRows,
            "main" => $_SESSION[$cCode]["main"],
            "mainData" => $_SESSION[$cCode]["main"],
            "items" => $_SESSION[$cCode]["items"],
            "subItemData" => $_SESSION[$cCode]["items2"],
            "subItemData_biaya" => $_SESSION[$cCode]["items3"],
            "mainElements" => $_SESSION[$cCode]['main_elements'],
            "elements" => $elements,
            "editableElements" => $editableElements,
            "elementConfig" => $elementConfigs,
            "currentStepNum" => $currentStepNum,
            "stepLabels" => $stepLabels,
            "currentStep" => $targetStepNum,
            "elementEditTarget" => MODUL_PATH . "_followupLiveEdit/selectElement/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "rawPrevURL" => $rawPrevURL,
            "rawBuilderURL" => $rawBuilderURL,
            "clearContentTarget" => MODUL_PATH . get_class($this) . "/clearContent/" . $this->jenisTr,
            "descriptionAdditional" => isset($_SESSION[$cCode]['main']['description_additional'][$targetStepNum]) ? $_SESSION[$cCode]['main']['description_additional'][$targetStepNum] : "",
            "descriptionAdditionalPreviews" => isset($_SESSION[$cCode]['main']['description_additional']) ? $_SESSION[$cCode]['main']['description_additional'] : array(),
            "approvalSpec" => $approvalSpec,
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            "submitBtn" => "submit",
            "addMainSourceField" => $addMainSourceField,
            "addMainSourceEdit" => $addMainSourceEdit,
            "updateMainSourceTarget" => MODUL_PATH . "_followupLiveEdit/updateSourceField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/" . $this->uri->segment(8),
            //-------------
            "additionalPackinglist" => $additionalPackinglist,
            "extractedSumSubItems" => isset($_SESSION[$cCode]['extractedSumSubItems']) ? $_SESSION[$cCode]['extractedSumSubItems'] : array(),
            "checklistNotePaired" => MODUL_PATH . "_followupLiveEdit/updateChecklistField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/" . $this->uri->segment(8),
            "checklistnote_cek" => isset($_SESSION[$cCode]['main']['checklistnote_cek']) ? $_SESSION[$cCode]['main']['checklistnote_cek'] : 0,
        );
        $this->load->view("transaksi", $data);
        //endregion

        // arrprint($receipMultiMainFields);

    }

    // ----------------------------
    public function doFollowup()
    {

        echo "<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);

        if($stepNum > 2){
            if ($this->transaksiMaintenanceStock === true) {
                $msg = $this->transaksiMaintenanceMsgStock['title'] . "<br>" . $this->transaksiMaintenanceMsgStock['mesage'];
                mati_disini($msg);
            }

        }

        echo "<script>top.writeProgress('MEMUAT CONFIG', 'HEAD');</script>";

        $paramPatchers = $this->config->item('heTransaksi_paramPatchers') != null ? $this->config->item('heTransaksi_paramPatchers') : array();
        $paramForceFillers = $this->config->item('heTransaksi_paramForceFillers') != null ? $this->config->item('heTransaksi_paramForceFillers') : array();

        echo "<script>top.writeProgress('MENYIAPKAN CALCULATOR', 'HEAD');</script>";

        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        echo "<script>top.writeProgress('MENYIAPKAN DATA-DATA TRANSAKSI', 'HEAD');</script>";

        //==ambil datanya
        $stepNowParameter = array();
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("step_number='" . $stepNumCurrent . "'");
        $tr->addFilterJoin("transaksi_data.trash='0'");
        $tmpTr = $tr->lookupJoined();
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;

            $cCode = "_TR_" . $this->jenisTr;
            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            $_SESSION[$cCode]['rsltItems'] = array();
            $_SESSION[$cCode]['rsltItems2'] = array();
            //endregion

            $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["target"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["target"] : NULL;
            $detailValuesConfig = isset($this->configCore[$this->jenisTr]['tableIn']['detailValues']) ? $this->configCore[$this->jenisTr]['tableIn']['detailValues'] : array();
            $additionalData = isset($this->configUi[$this->jenisTr]["addDetailData"][$stepNum]) ? $this->configUi[$this->jenisTr]["addDetailData"][$stepNum] : array();

            $masterID = $_SESSION[$cCode]['main']['masterID'];
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;

            //            $trID = $tmpTr[0]->id_master;
            $trID = $tmpTr[0]->transaksi_id;


            $totalSteps = sizeof($this->configUi[$this->jenisTr]['steps']);


            //==references, previous entry
            $prevProp = array(
                "id" => $tmpTr[0]->transaksi_id,
                "jenis" => $tmpTr[0]->jenis,
                "nomer" => $tmpTr[0]->nomer,
            );


            //------
            $stepNowParameter = array(
                "next_step_code" => $tmpTr[0]->next_step_code,
                "next_step_label" => $tmpTr[0]->next_step_label,
                "next_group_code" => $tmpTr[0]->next_group_code,
                "next_step_num" => $tmpTr[0]->next_step_num,
                "step_current" => $tmpTr[0]->step_current,
            );


            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }


            $main = array();
            $items = array();
            $prevIDs = array();
            $prevNos = array();
            foreach ($tmpTr as $row) {
                $items[$row->produk_id] = array(
                    "id" => $row->produk_id,
                    "nama" => $row->produk_nama,
                    "jml" => $row->produk_ord_jml,
                    "harga" => $row->produk_ord_hrg,
                    "valid_qty" => $row->valid_qty,
                    "transaksi_id" => $row->transaksi_id,
                    "nomer" => $row->nomer,
                );

                if ($row->valid_qty > 0) {
                    cekHitam("ok lanjut");
                }
                else {
                    if (isset($_SESSION[$cCode]['items'][$row->produk_id])) {
                        matiHere("Followed up already. Please close and refresh your browser " . $row->produk_nama . " " . $row->produk_id);//kalo session active ya harus dimatiin biar gak dobel
                    }
                }

                if (!in_array($row->transaksi_id, $prevIDs)) {
                    $prevIDs[] = $row->transaksi_id;
                }
                if (!in_array($row->nomer, $prevNos)) {
                    $prevNos[] = $row->nomer;
                }
                if (sizeof($detailValuesConfig) > 0) {
                    echo "detail values ada..<br>";
                    foreach ($detailValuesConfig as $key => $src) {
                        echo "$key akan ambil nilai dari $src<br>";
                        echo "<script>top.writeProgress('$key akan ambil nilai dari $src');</script>";
                        //                            $tmp[$key]=isset($iSpec[$val])?$iSpec[$val]:0;
                        if (isset($detailValues[$row->produk_id][$key])) {
                            //                            $tmp[$key] = formatField($key, $detailValues[$row->produk_id][$key]);
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                //                                $tmp[$key] = formatField($key, $row->$key);
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "dan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                        echo "<script>top.writeProgress('dan sekarang nilainya: " . $items[$row->produk_id][$key] . "');</script>";
                    }
                }
            }

        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }

        // matiHEre();
        //==ongkir dll (additional fees) harus diselipkan kedalam masterGates aktual
        //region ongkir dll diselipkan ke masterGates
        if (isset($this->configCore[$this->jenisTr]['externalValues']) && sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configCore[$this->jenisTr]['externalValues'] as $exKey => $exSpec) {
                if ($exSpec['useAt'] == $stepNum) {
                    if (isset($exSpec['mdlName']) && strlen($exSpec['mdlName']) > 3) {
                        $_SESSION[$cCode]['main'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_src"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        }
                    }
                    $_SESSION[$cCode]['main'][$exKey] = $_POST[$exKey];
                    if (isset($_SESSION[$cCode]['main_add_values'][$exKey])) {
                        $_SESSION[$cCode]['main_add_values'][$exKey] = $_POST[$exKey];
                    }

                    if ($exSpec['taxFactor'] > 0) {
                        $_SESSION[$cCode]['main'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_tax"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        }
                    }
                }
            }
        }
        //endregion


        //region baca seting optional step
        if (isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) && strlen($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) > 0) {
            echo "<script>top.writeProgress('READING OPTIONAL STEPs', 'HEAD');</script>";
            $criteriaField = $this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField'];
            if (isset($_SESSION[$cCode]['main'][$criteriaField]) && $_SESSION[$cCode]['main'][$criteriaField] > 0) {
                echo "nextstepnum normal<br>";
                $nextStepNum = ($stepNum + 1);
                $useAdditionalStep = true;
            }
            else {
                echo "nextstepnum hampir normal<br>";
                $useAdditionalStep = false;
                $nextStepNum = ($stepNum + 2);
            }
        }
        else {
            //            //cekBiru("OPT TIDAK ditentukan");
            echo "nextstepnum TIDAK normal<br>";
            $useAdditionalStep = false;
            $nextStepNum = ($stepNum + 1);
            echo "yaitu $nextStepNum<br>";
        }
        //endregion


        //region build table rekening
        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        //arrPrint($buildTablesMaster);

        $addMasterTables = array(
            "rugilaba",
            "laba ditahan",
            "rugilaba lain lain",
        );
        foreach ($addMasterTables as $trek) {
            $buildTablesMaster[] = array(
                "comName" => "RugiLaba",
                "loop" => array(
                    "$trek" => .0,
                ),
            );
        }

        if (sizeof($buildTablesMaster) > 0) {
            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
                $mdlName = $buildTablesMaster_specs['comName'];
                if (substr($mdlName, 0, 1) == "{") {
                    //                        cekkuning("mengandung kurawal");
                    $mdlName = trim($mdlName, "{");
                    $mdlName = trim($mdlName, "}");
                    $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
                }
                else {
                    //                        cekkuning("TIDAK mengandung kurawal");
                }
                $mdlName = "Com" . $mdlName;
                cekHitam("model: $mdlName");


                if (isset($buildTablesMaster_specs['loop'])) {
                    foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
                        unset($buildTablesMaster_specs['loop'][$key]);
                        //                        if (isset($_SESSION[$cCode]['main'][$key])) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                        }
                        $buildTablesMaster_specs['loop'][$key] = $val;
                        //                        }
                    }
                }

                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();
                if (method_exists($m, "getTableNameMaster")) {
                    if (sizeof($m->getTableNameMaster())) {
                        $m->buildTables($buildTablesMaster_specs);
                    }
                }
            }
        }

        if (sizeof($buildTablesDetail) > 0) {
            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
                foreach ($_SESSION[$cCode]['items'] as $itemSpec) {

                    $mdlName = $buildTablesDetail_specs['comName'];
                    if (substr($mdlName, 0, 1) == "{") {
                        $mdlName = trim($mdlName, "{");
                        $mdlName = trim($mdlName, "}");
                        $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
                    }

                    if (isset($buildTablesDetail_specs['loop'])) {
                        foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
                            unset($buildTablesDetail_specs['loop'][$key]);

                            if (substr($key, 0, 1) == "{") {
                                $key = trim($key, "{");
                                $key = trim($key, "}");
                                $key = str_replace($key, $itemSpec[$key], $key);
                            }
                            $buildTablesDetail_specs['loop'][$key] = $val;
                            cekHitam("LINE: " . __LINE__ . " ::sini bukan??  akan build tabel detail $key");

                        }
                    }


                    $mdlName = "Com" . $mdlName;
                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();
                    if (method_exists($m, "getTableNameMaster")) {
                        if (sizeof($m->getTableNameMaster())) {
                            $m->buildTables($buildTablesDetail_specs);
                            arrPrint($buildTablesDetail_specs);
                            cekHitam(":: build tabel detail");
                        }
                    }
                }
            }
        }
        //endregion


        $this->db->trans_start();

        //region pembulatan replacer disini
        $injectBulat = isset($this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum]) ? $this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum] : array();
        if (sizeof($injectBulat) > 0) {
            echo "<script>top.writeProgress('PEMBULATAN', 'HEAD');</script>";
            //            arrPrint($injectBulat);
            $selectedSource = $injectBulat['source'];
            $injectSource = makeDppBulat($_SESSION[$cCode]['main'][$selectedSource]);
            foreach ($injectBulat['replacer'] as $k => $fields) {
                $_SESSION[$cCode]['main'][$fields] = $injectSource[$k];
                echo "<script>top.writeProgress('PEMBULATAN ($fields)');</script>";
            }

        }
        //endregion


        cekMerah(":: MEMULAI PRE-PROCC ITEMS...");


        //region pre-processors (item)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum] : array();
            echo "ITEM NUM LABELS";

            if (sizeof($iterator) > 0) {
                echo "<script>top.writeProgress('PERSIAPAN PRE-PROCESSOR...', 'HEAD');</script>";
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo __LINE__ . " :: sub-preproc: $comName, initializing values <br>";

                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        $tmpOutParams[$cCtr] = array();
                        //                        $id = $dSpec['id'];
                        $id = $xid;
                        $subParams = array();

                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['static'][$key] = $realValue;

                            }

                            if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                                foreach ($paramPatchers[$comName] as $k => $v) {
                                    if (!isset($subParams['static'][$k])) {
                                        $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    }
                                }
                            }
                            if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                                $jenis = $_SESSION[$cCode]['main']['jenis'];
                                foreach ($paramForceFillers[$comName] as $k => $v) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }

                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }

                        if (sizeof($subParams) > 0) {

                            $tmpOutParams[$cCtr][] = $subParams;
                        }


                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                        echo "sub preproc #$it: $comName, sending values <br>";

                        $mdlName = "Pre" . ucfirst($comName);
                        $this->load->model("Preprocs/" . $mdlName);
                        $m = new $mdlName($resultParams);
                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                            $tobeExecuted = true;
                        }
                        else {
                            $tobeExecuted = false;
                        }

                        if ($tobeExecuted) {
                            $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();
                            cekHitam(":: PRE-PROCC -> GOTNAME, ITERATING...");
                            arrprint($gotParams);
                            if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                foreach ($gotParams as $gateName => $paramSpec) {

                                    if (!isset($_SESSION[$cCode][$gateName])) {
                                        $_SESSION[$cCode][$gateName] = array();
                                        //                                    cekhijau("building the session: $gateName");
                                    }
                                    else {
                                        //                                    cekhijau("NOT building the session: $gateName");
                                    }

                                    foreach ($paramSpec as $id => $gSpec) {
                                        //                                        $id = $gSpec['id'];
                                        if (!isset($_SESSION[$cCode][$gateName][$id])) {
                                            $_SESSION[$cCode][$gateName][$id] = array();
                                        }

                                        if (isset($_SESSION[$cCode][$gateName][$id])) {
                                            if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                foreach ($gSpec as $key => $val) {
                                                    $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                }
                                            }
                                        }
                                        //==inject gotParams to child gate
                                        if ($gateName == $srcGateName) {
                                            if (isset($_SESSION[$cCode][$srcGateName][$id])) {
                                                if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                    foreach ($gSpec as $key => $val) {
                                                        $_SESSION[$cCode][$srcGateName][$id][$key] = $val;
                                                    }
                                                }
                                            }
                                        }

                                        //cekMerah("REBUILDING VALUES..");
                                        if (sizeof($itemNumLabels) > 0) {
                                            //cekHijau("REBUILDING SUBS FOR ITEMS");
                                            foreach ($itemNumLabels as $key => $label) {
                                                //cekHere("$id === $key => $label");
                                                $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                //                                        die();
                                            }
                                        }
                                    }
                                    //                                    arrPrint($_SESSION[$cCode][$gateName]);die();
                                }
                            }

                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }
                    }

                    $this->load->helper("he_value_builder");
                    fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);
                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }


            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);
        }
        else {
            echo("no processor defined. skipping preprocessor..<br>");
        }

        //endregion


        //region pre-processors (master)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();

            echo "ITEM NUM LABELS";

            if (sizeof($iterator) > 0) {
                echo "<script>top.writeProgress('PERSIAPAN PRE-PROCESSOR...', 'HEAD');</script>";
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    $switchResultParams = isset($tComSpec['switchResultParams']) ? $tComSpec['switchResultParams'] : false;

                    echo "master-preproc: $comName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();


                    $subParams = array();
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $subParams['static'][$key] = $realValue;

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr] = $subParams;
                    }


                    $mdlName = "Pre" . ucfirst($comName);
                    $this->load->model("Preprocs/" . $mdlName);
                    $m = new $mdlName($resultParams);


                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                        $tobeExecuted = true;
                    }
                    else {
                        $tobeExecuted = false;
                    }

                    if ($tobeExecuted) {
                        $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $gotParams = $m->exec();

                        cekbiru("gotparams dari $comName");
                        arrprint($gotParams);

                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {

                                if ($switchResultParams == true) {
                                    foreach ($gSpec as $id => $ggSpec) {
                                        if (!isset($_SESSION[$cCode][$gateName][$id])) {
                                            $_SESSION[$cCode][$gateName][$id] = array();
                                        }
                                        if (isset($_SESSION[$cCode][$gateName][$id])) {
                                            if (is_array($ggSpec) && sizeof($ggSpec) > 0) {
                                                foreach ($ggSpec as $key => $val) {
                                                    $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                }
                                            }
                                        }
                                        //cekMerah("REBUILDING VALUES..");
                                        if (sizeof($itemNumLabels) > 0) {
                                            //cekHijau("REBUILDING SUBS FOR ITEMS");
                                            foreach ($itemNumLabels as $key => $label) {
                                                //cekHere("$id === $key => $label");
                                                if (isset($_SESSION[$cCode][$gateName][$id][$key])) {
                                                    $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                }
                                            }
                                        }
                                    }
                                }
                                else {

                                    if (isset($_SESSION[$cCode]['main'])) {
                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                            foreach ($gSpec as $key => $val) {
                                                cekbiru("injecting param $key with $val");
                                                $_SESSION[$cCode]['main'][$key] = $val;
                                            }
                                        }
                                    }
                                    //==inject gotParams to child gate
                                    if (isset($_SESSION[$cCode]['main'])) {
                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                            foreach ($gSpec as $key => $val) {
                                                $_SESSION[$cCode]['main'][$key] = $val;
                                            }
                                        }
                                    }
                                }

                            }
                        }
                        else {
                            cekmerah("TIDAK ada gotparam, tidak perlu replace");
                        }

                    }
                    else {
                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                    }
                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }


            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);


        }
        else {
            echo("no processor defined. skipping preprocessor..<br>");
        }

        //endregion

        //region pre-proc value injector items2 items2_sum dari gerbang main
        $injectValues = isset($this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]) ? $this->configCore[$this->jenisTr]['preInjectValue'][$stepNum] : array();
        if (sizeof($injectValues) > 0) {
            $iterator = isset($this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]['master']) ? $this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]['master'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    //                    echo "master-preproc: $comName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();


                    $subParams = array();
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $subParams['static'][$key] = $realValue;

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr] = $subParams;
                    }


                    $mdlName = "Pre" . ucfirst($comName);
                    $this->load->model("Preprocs/" . $mdlName);
                    $m = new $mdlName($resultParams);


                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                        $tobeExecuted = true;
                    }
                    else {
                        $tobeExecuted = false;
                    }

                    if ($tobeExecuted) {
                        $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $gotParams = $m->exec();
                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            //                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {
                                if ($gateName == "main") {
                                    foreach ($gSpec as $key => $val) {
                                        $_SESSION[$cCode]['main'][$key] = $val;
                                    }
                                }
                                if ($gateName == "items2") {
                                    foreach ($_SESSION[$cCode]['items2'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            foreach ($tmpSes as $y => $sesData) {
                                                if (array_key_exists($key, $sesData)) {
                                                    $_SESSION[$cCode]['items2'][$k][$y][$key] = $val;
                                                }
                                            }
                                        }
                                    }

                                }
                                if ($gateName == "items2_sum") {
                                    foreach ($_SESSION[$cCode]['items2_sum'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            $_SESSION[$cCode]['items2_sum'][$k][$key] = $val;
                                        }
                                    }

                                }

                            }
                        }
                        else {
                            cekmerah("TIDAK ada gotparam, tidak perlu replace");
                        }

                    }
                    else {
                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                    }

                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }

            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);

        }
        //endregion

//        matiHere(__LINE__);
        //        $step = $_SESSION[$cCode]['main']['step_number'];
        $this->load->library("Validator");
        $va = new Validator();
        $va->setConfigUiJenis($this->configUiJenis);
        $va->setCCode($this->cCode);
        $va->midValidate($stepNum);
        $va->unionValidate();
        //==tulis komponen, if any


        //region update step2an
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
            echo "authorizing to next step..<br>";
            $nextProp = array(
                "num" => $nextStepNum,
                "code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                "label" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['label'],
                "groupID" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['userGroup'],
            );
        }
        else {//==ini step terakhir, tulis komponen jika ada

            $nextProp = array(
                "num" => 0,
                "code" => "",
                "label" => "",
                "groupID" => "",
            );
        }
        //endregion


        echo "checking components..<br>";
        echo "<script>top.writeProgress('CHECKING KOMPONEN');</script>";
        //referensi_id pada steps (dimatikan)
        //        $masterReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        $childReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        foreach ($masterReplacers as $key => $val) {
        //            $_SESSION[$cCode]['main'][$key] = $val;
        //        }
        //        foreach ($childReplacers as $key => $val) {
        //            foreach ($_SESSION[$cCode]['out_detail'] as $xid => $cSpec) {
        //                $id = $cSpec['id'];
        //                $_SESSION[$cCode]['out_detail'][$id][$key] = $val;
        //            }
        //
        //        }


        //==tulis signature

        $dwsign = $tr->writeSignature($masterID, array(
            "nomer" => $tmpNomorNota,
            "step_number" => $stepNum,
            "step_code" => $this->configUi[$origJenis]['steps'][$stepNum]['target'],
            "step_name" => $this->configUi[$origJenis]['steps'][$stepNum]['label'],
            "group_code" => $this->configUi[$origJenis]['steps'][$stepNum]['userGroup'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "keterangan" => $this->configUi[$origJenis]['steps'][$stepNum]['label'] . " oleh " . $this->session->login['nama'],
            "transaksi_id" => $masterID,
        )) or die("Failed to write signature");
        $mongoList['sign'][] = $dwsign;
        //cekKuning($this->db->last_query());

        //region update step terdahulu
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $topID), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$topID"),
            "value" => array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNum,
            ),
        );
        cekHijau($this->db->last_query());

        //-------------------------------------------------
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $trID), array(
            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$trID"),
            "value" => array(
                "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
            ),
        );


        //mati_disini("==== ==== ====");
        //endregion


        //==prepare kloningan
        $tCode = $this->configUi[$origJenis]['steps'][$stepNum]['target'];
        $tCodeName = $this->configUi[$origJenis]['steps'][$stepNum]['label'];
        $masterReplacers = array(
            //            "referensi_id" => $masterID, (dimatikan)
            //            "id_master"       => $masterID,
            //            "id_top"          => $topID,
            "inv" => $tmpNomorNota,
            //            "jenis_top"           => $tCode,
            "jenis" => $tCode,
            "jenis_label" => $tCodeName,
            "transaksi_jenis" => $tCode,
            "cabang_id" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangID'] : $this->session->login['cabang_id'],
            "cabang_nama" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangName'] : $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "step_current" => "0",
            "step_number" => $stepNum,
            //            "next_step_code"      => "",
            //            "next_step_label"     => "",
            //            "next_group_code"     => "",
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            //===references
            "id_master" => $masterID,
            "id_top" => $topID,
            "ids_prev" => base64_encode(serialize($prevIDs)),
            "ids_prev_intext" => print_r($prevIDs, true),
            "nomer_top2" => isset($_SESSION[$cCode]['main']['nomer_top2']) ? $_SESSION[$cCode]['main']['nomer_top2'] : "",
            "nomer_top" => $_SESSION[$cCode]['tableIn_master']['nomer_top'],
            "nomers_prev" => base64_encode(serialize($prevNos)),
            "nomers_prev_intext" => print_r($prevNos, true),
            //            "jenis_top"           => $this->jenisTr,
            "jenises_prev" => base64_encode(serialize(array($prevProp['jenis']))),
            "jenises_prev_intext" => print_r(array($prevProp['jenis']), true),
            "tail_number" => $stepNum,
            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
        );

        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $childTableRepaclers = array(
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
            }
        }

        foreach ($_SESSION[$cCode]['tableIn_sub_detail'] as $idd => $deSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_sub_detail'][$idd][$key] = $val;
            }
        }
        foreach ($_SESSION[$cCode]['tableIn_sub_detail_items'] as $idd => $deSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_sub_detail_items'][$idd][$key] = $val;
            }
        }

        // arrPrint($_SESSION[$cCode]['tableIn_sub_detail']);
        // matiHEre();

        $masterReplacersO = array(

            "jenisTr" => $tCode,
            "jenisTrName" => $tCodeName,
            "olehID" => $this->session->login['id'],
            "olehName" => $this->session->login['nama'],
            "stepNumber" => $stepNum,
            "stepCode" => $tCode,
        );
        foreach ($masterReplacersO as $key => $val) {
            $_SESSION[$cCode]['main'][$key] = $val;
        }

        //region menimbulkan nilai tagihan
        $unpaidList = null != $this->config->item('tr_unpaidList') ? $this->config->item('tr_unpaidList') : array();
        //        arrprint($_SESSION[$cCode]['tableIn_master']);
        if (in_array($tCode, $unpaidList)) {
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_tagihan"] = $_SESSION[$cCode]['tableIn_master']['transaksi_nilai'];
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_terbayar"] = 0;
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_sisa"] = ($_SESSION[$cCode]['tableIn_master']['transaksi_nilai_tagihan'] - $_SESSION[$cCode]['tableIn_master']['transaksi_nilai_terbayar']);
            //cekMerah("NULIS TAGIHANN");
        }
        else {
            //cekMerah("TIDAK NULIS TAGIHANN");
        }
        //endregion

        //region penomoran receipt #1
        $this->load->model("CustomCounter");
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);
        $counterForNumber = array($this->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

        foreach ($counterForNumber as $i => $cRawParams) {
            $cParams = explode("|", $cRawParams);
            $cValues = array();
            foreach ($cParams as $param) {
                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
            }
            $cRawValues = implode("|", $cValues[$i]);
            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
        }
        $tmpNomorNota2 = $paramSpec['paramString'];
        $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);
        //endregion

        //region dynamic counters #1
        echo "<script>top.writeProgress('sedang membuat penomoran');</script>";
        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);
        $configCustomParams = $this->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                switch ($paramSpec['id']) {
                    case 0: //===counter type is new
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                        break;
                    default: //===counter to be updated
                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                        break;
                }
                //echo "<hr>";
            }
        }
        $appliedCounters2 = base64_encode(serialize($cContent));
        $appliedCounters_inText2 = print_r($cContent, true);


        $masterReplacers = array(
            "nomer" => $tmpNomorNota2,
            "nomer2" => $tmpNomorNota2Alias,
            "counters" => $appliedCounters2,
            "counters_intext" => $appliedCounters_inText2,
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $addValues = array(
            'counters' => $appliedCounters2,
            'counters_intext' => $appliedCounters_inText2,
            'nomer' => $tmpNomorNota2,
            'nomer2' => $tmpNomorNota2Alias,
            'dtime' => date("Y-m-d H:i:s"),
            'fulldate' => date("Y-m-d"),
        );
        foreach ($addValues as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        // </editor-fold>
        //endregion

        //region numbering tambahan
        $this->load->library("CounterNumber");
        $ccn = new CounterNumber();
        $ccn->setCCode($this->cCode);
        $ccn->setJenisTr($this->jenisTr);
        $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
        $ccn->setMainGate($_SESSION[$cCode]['main']);
        $ccn->setItemsGate($_SESSION[$cCode]['items']);
        $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
        $new_counter = $ccn->getCounterNumber();
        cekHitam("jenistr yang disett dari create " . $this->jenisTr);

        if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
            foreach ($new_counter['main'] as $ckey => $cval) {
                $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                $_SESSION[$cCode]['main'][$ckey] = $cval;
            }
        }
        if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
            foreach ($new_counter['items'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                }
            }
        }
        if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
            foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                }
            }
        }
        //endregion
        //==tulis kloningan transaksi
        //region write entries
        if (sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

            // region locker transaksi---------------------------------
            if ($this->session->login['ghost'] == 0) {
//                $followUpValidator = isset($this->configUi[$origJenis]['followUpValidator'][$stepNum]) ? $this->configUi[$origJenis]['followUpValidator'][$stepNum] : false;
//                if ($followUpValidator == true) {

                $this->load->model("Mdls/MdlLockerTransaksi");
                $lt = New MdlLockerTransaksi();
                $lt->addFilter("transaksi_id='$no'");
                $lt->addFilter("state='hold'");
                $lt->addFilter("jumlah='1'");
                $lt->addFilter("oleh_id=" . my_id());
                $ltTmp = $lt->lookupAll()->result();
                showLast_query("biru");
                if (sizeof($ltTmp) == 1) {
                    cekHijau(":: lanjuut eksekusi transaksi ini....");
                }
                else {
                    $msg = "Transaksi sudah dieksekusi atau ada indikasi transaksi ganda. Silahkan tutup halaman ini dan refresh ulang.";
                    cekMerah($msg);
                    die(lgShowAlertBiru($msg));
                }

//                }
            }
//            mati_disini(__LINE__);
            // endregion locker transaksi---------------------------------

            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 0;

            $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
            $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];

            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);

//            showlast_query("hitam");
//matiHere(__LINE__);

            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);

            $mongoList['main'] = array($insertID, $epID);
            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;

            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }

            if (isset($_SESSION[$cCode]['tableIn_master']['ids_his'])) {
                $idHis_decode = blobDecode($_SESSION[$cCode]['tableIn_master']['ids_his']);
                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;


                $tr = new MdlTransaksi();
                $dup = $tr->updateData(array("id" => $insertID), array(
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekUngu($this->db->last_query());
            }

            cekUngu(":: insertID => $insertID ::");
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                $mongoList['mainValues'] = array();
                foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $inserMainValues[] = $dd;
                    $mongoList['mainValues'][] = $dd;
                }
                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }

            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                //                cekMerah("ada mainElements $cCode");
                //                arrprint($_SESSION[$cCode]['main_elements']);die();
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? print_r($aSpec['contents_intext'], true) : "",

                    ));
                }
            }
            else {
                //                cekMerah("TAK ada mainElements");
            }

            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }

                    }
                }
                if (sizeof($insertIDs) > 0) {
                    $arrBlob = blobEncode($insertIDs);
                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }


            //region update validQty pada step sebelumnya yang di-refer
            echo "<script>top.writeProgress('EXTRACT ITEMS...','head');</script>";
            $seluruhnya = true;
            $prevTrID = 0;
            $arrvalidQtySisa = array();
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $closedRequest = isset($this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled']) ? $this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled'] : false;
                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $iID => $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($insertDetailID < 1) {
                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                    else {
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;
                    }

                    if ($epID != 999) {
                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                        if ($insertEpID < 1) {
                            die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertEpID;
                            $insertDeIDs[$epID][] = $insertEpID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                    }

                    cekHitam("EXTRACTED ITEMS... [$iID] [target_jenis: $jenisTrTarget]");
                    echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                    $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $gate_update => $tbl_detail) {
                            if (isset($_SESSION[$cCode][$gate_update])) {
                                if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                    $itemFulfilledJml = 0;
                                    foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                        $prevTrID = $triSpec['transaksi_id'];
                                        $tru = new MdlTransaksi();
                                        $tru->setFilters(array());
                                        $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                        //----------------------------------------------------------
                                        if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                            $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                            //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                        }
                                        else {
                                            $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                            //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                        }
                                        //----------------------------------------------------------
                                        $newValidQtyNotApprove = 0;
                                        if ($closedRequest == true) {
                                            cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = 0;
                                                $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                            }
                                            cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                        }
                                        //----------------------------------------------------------


                                        $itemFulfilledJml += $newValidQty;
                                        $updateContents = array(
                                            "valid_qty" => $newValidQty,
                                            "valid_qty_no_approve" => $newValidQtyNotApprove,
                                        );
                                        if ($newValidQty < 1) {
                                            $childPrevRepaclers = array(
                                                "next_substep_code" => "",
                                                "next_substep_label" => "",
                                                "next_subgroup_code" => "",
                                                "sub_tail_number" => $stepNum,
                                                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                            );
                                            foreach ($childPrevRepaclers as $key => $val) {
                                                $updateContents[$key] = $val;
                                            }
                                        }
                                        else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                            $seluruhnya = false;
                                            $arrvalidQtySisa[$iID] = $newValidQty;
                                        }
                                        $dupState = $tru->updateData(array(
                                            "produk_id" => $iID,
                                            "id" => $triID,
                                            "transaksi_id" => $triSpec['transaksi_id'],
                                        ), $updateContents) or die("Failed to update previous detail entries!");
                                        cekHijau($this->db->last_query());

                                        $mongUpdateList['update'][$tbl_detail][] = array(
                                            "where" => array(
                                                //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                "id" => "$triID",
                                                //                                        "produk_id" => $iID,
                                            ),
                                            "value" => $updateContents,
                                        );
                                        unset($tru);
                                    }
                                }
                            }
                        }
                    }
                    else {
                        cekHitam("TIDAK ADA ITERATOR...");
                    }

                    // matiHEre("oo");
                    // arrPrint($iterator);
                    // matiHEre($jenisTrTarget);
                }

                if ($closedRequest == true) {
                    if (isset($_SESSION[$cCode]['extractedItems'])) {
                        foreach ($_SESSION[$cCode]['extractedItems'] as $iIDex => $exSpec) {
                            if (!array_key_exists($iIDex, $_SESSION[$cCode]['tableIn_detail'])) {
                                foreach ($exSpec as $trDataID => $trdSpec) {
                                    $tru = new MdlTransaksi();
                                    $tru->setFilters(array());
                                    $tru->setTableName($tru->getTableNames()['detail']);
                                    $updateContents = array(
                                        "valid_qty" => 0,
                                        "valid_qty_no_approve" => $trdSpec['qty'],
                                    );
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                    $dupState = $tru->updateData(array(
                                        "produk_id" => $iIDex,
                                        "id" => $trDataID,
                                        "transaksi_id" => $trdSpec['transaksi_id'],
                                    ), $updateContents) or die("Failed to update previous detail entries!");
                                    //                                    cekHijau($this->db->last_query());
                                    $mongUpdateList['update']['detail'][] = array(
                                        "where" => array(
                                            //                                            "transaksi_id" => $trdSpec['transaksi_id'],
                                            "id" => "$trDataID",
                                            //                                            "produk_id" => $iIDex,
                                        ),
                                        "value" => $updateContents,
                                    );
                                    unset($tru);
                                }
                            }
                        }
                    }
                }

                if (sizeof($insertIDs) == 0) {
                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                else {
                    $indexing_details = array();
                    foreach ($insertDeIDs as $key => $numb) {
                        $indexing_details[$key] = $numb;
                    }
                    foreach ($indexing_details as $k => $arrID) {
                        arrPrint($arrID);
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }

                //-------------
                $lastStepPartialApprove = isset($this->configUi[$this->jenisTr]['lastStepPartialApprove']) ? $this->configUi[$this->jenisTr]['lastStepPartialApprove'] : false;
                if ($lastStepPartialApprove == true) {
                    cekKuning(__LINE__ . " $lastStepPartialApprove :: $totalSteps");
                    if ($totalSteps == 2) {
                        if (sizeof($arrvalidQtySisa) > 0) {
                            cekPink("ada valid qty yang tersisa");
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $topID), $stepNowParameter) or die("Failed to update tr next-state!");
                            cekHitam(__LINE__ . " ## 2 step, dan step akhir partial, YESS...");
                            showLast_query("orange");
                        }
                    }
                }
            }
            else {
                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
            }

            if ($seluruhnya) {
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $prevTrID), array(
                    "tail_number" => $stepNum,
                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                    "status_4" => $_SESSION[$cCode]['main']['status_4'],
                    "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                )) or die("Failed to update tr next-state!");
                cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                $mongUpdateList['update']['main'][] = array(
                    "where" => array(
                        "id" => "$prevTrID",
                    ),
                    "value" => array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    ),
                );
                cekHijau($this->db->last_query());
            }
            //endregion


            //region cloner items to item_child
            if (sizeof($additionalData) > 0) {
                echo "<script>top.writeProgress('CLONING ITEMS TO ITEM CHILD...','head');</script>";
//                cekHitam("ini data");
                $dataMdl = $additionalData["mdlName"];
                $this->load->model("Mdls/" . $dataMdl);
                $da = new $dataMdl();
                $arrColl = $da->getFields();
                $selectedCol = array();
                foreach ($arrColl as $colSpec) {
                    $selectedCol[] = $colSpec['kolom'];
                }

                if (isset($_SESSION[$cCode]['items_child']) && sizeof($_SESSION[$cCode]['items_child'])) {
                    $gateData = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate'] : "detail";

                    $arrBlacklist = array(
                        "jml", "max_jml", "qty",
                    );
                    if (isset($_SESSION[$cCode]["items2_sum"])) {
                        unset($_SESSION[$cCode]["items2_sum"]);
                        unset($_SESSION[$cCode]["items2"]);
                        unset($_SESSION[$cCode]["tableIn_detail_values2_sum"]);
                    }
                    foreach ($_SESSION[$cCode]['items_child'] as $mainProdsID => $defData) {
                        if ($gateData == "detail") {
                            $itemsMain = isset($_SESSION[$cCode]['items'][$mainProdsID]) ? $_SESSION[$cCode]['items'][$mainProdsID] : array();
                        }
                        else {
                            $forceMainToItems = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData]) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData] : array();
                            if (sizeof($forceMainToItems) > 0) {
                                foreach ($forceMainToItems as $key1 => $key2) {
                                    $keyForce = strlen($key2) > 2 ? $key2 : $key1;
                                    $itemsMain[$key1] = isset($_SESSION[$cCode]['main'][$keyForce]) ? $_SESSION[$cCode]['main'][$keyForce] : "";
                                }
                                $itemsMain["jml"] = "1";
                                $itemsMain["qty"] = "1";
                                $itemsMain["max_jml"] = "1";

                            }
                            else {
                                matiHEre("detil aset gagal di tulis!");
                            }
                            //                            arrPrint($forceMainToItems);
                        }

                        $arrChilds = array_diff_key($itemsMain, array_flip($arrBlacklist));
                        //                        arrPrint($itemsMain);
                        //                        matiHEre();
                        //
                        //arrPrint($arrChilds);
                        cekLime("ini brooo " . $gateData);

                        $arrNew = array();
                        if (sizeof($itemsMain) > 0) {
                            foreach ($defData as $inID => $detil_child) {
                                //                        $arrNewChild = array_diff($itemsMain,$detil_child);

                                $paramDetil = array_replace($arrChilds, $detil_child);
                                if (array_key_exists("id", $paramDetil)) {

                                    $paramDetil["parent_id"] = $paramDetil["id"];
                                    if (!isset($paramDetil["folders"]) || $paramDetil["folders"] == 0) {
                                        $paramDetil["folders"] = $paramDetil["pihakMainId"];
                                        $paramDetil["keterangan"] = $paramDetil["pihakMainName"];
                                    }
                                    unset($paramDetil["id"]);
                                }
                                $tmpData = array();
                                foreach ($selectedCol as $i => $coloum) {
                                    if (isset($paramDetil[$coloum])) {
                                        $tmpData[$coloum] = $paramDetil[$coloum];
                                    }
                                }
                                //                                arrPrint($paramDetil);
                                if (isset($paramDetil["subtotal"])) {
                                    $paramDetil["subtotal"] = $paramDetil["jml"] * $paramDetil["harga"];
                                }

                                $insertDataID = $da->addData($tmpData, $da->getTableName()) or die(lgShowError("Gagal menulis pengajuan data", __FILE__));
                                cekHere($this->db->last_query());
                                $paramDetil["id"] = $insertDataID;
                                echo "<script>top.writeProgress('PENGAJUAN DATA (TRID:$insertDataID)');</script>";
                                $_SESSION[$cCode]["items2_sum"][$insertDataID] = $paramDetil;
                                $_SESSION[$cCode]["items2"][$mainProdsID][$insertDataID] = $paramDetil;
                                //                            $arrNew

                            }
                        }


                        //                        arrPrint($arrNew);
                        //


                        //                  arrPrint($itemsMain);
                    }

                }
            }

            //endregion

            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                    cekUngu($this->db->last_query());
                }
            }

            //region tulis sub transaksi data
            if (isset($this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget]) && $this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget] == true) {
                $seluruhnya = true;
                $prevTrID = 0;
                $arrvalidQtySisa = array();
                if (isset($_SESSION[$cCode]['tableIn_sub_detail']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail']) > 0) {

                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_sub_detail'] as $iID => $dSpec) {
                        $insertDetailID = $tr->writeDetailSubEntries($insertID, $dSpec);
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailSubEntries($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                // $mongoList['detail'][] = $insertEpID;
                            }
                        }

                        cekUngu($this->db->last_query());
                        cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                        echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                        $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $gate_update => $tbl_detail) {
                                if (isset($_SESSION[$cCode][$gate_update])) {
                                    if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                        $itemFulfilledJml = 0;
                                        foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                            arrPrintPink($triSpec);
                                            $prevTrID = $triSpec['transaksi_id'];
                                            $tru = new MdlTransaksi();
                                            $tru->setFilters(array());
                                            $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                            //----------------------------------------------------------
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
//                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                                $produk_ord_diterima = ($triSpec['dikirim_qty'] + $dSpec['produk_ord_jml']);
                                            }
                                            else {
                                                $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
//                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                                $produk_ord_diterima = ($triSpec['dikirim_qty'] + $triSpec['valid_qty']);
                                            }
                                            //----------------------------------------------------------
                                            $newValidQtyNotApprove = 0;
                                            if ($closedRequest == true) {
                                                cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = 0;
                                                    $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                }
                                                cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                            }
                                            //----------------------------------------------------------
                                            $itemFulfilledJml += $newValidQty;
                                            $updateContents = array(
                                                "valid_qty" => $newValidQty,
                                                "valid_qty_no_approve" => $newValidQtyNotApprove,
                                                "produk_ord_diterima" => $produk_ord_diterima,
                                            );
                                            if ($newValidQty < 1) {
                                                $childPrevRepaclers = array(
                                                    "next_substep_code" => "",
                                                    "next_substep_label" => "",
                                                    "next_subgroup_code" => "",
                                                    "sub_tail_number" => $stepNum,
                                                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                );
                                                foreach ($childPrevRepaclers as $key => $val) {
                                                    $updateContents[$key] = $val;
                                                }
                                            }
                                            else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                $seluruhnya = false;
                                                $arrvalidQtySisa[$iID] = $newValidQty;
                                            }
                                            $dupState = $tru->updateData(array(
                                                "produk_id" => $iID,
                                                "id" => $triID,
                                                "transaksi_id" => $triSpec['transaksi_id'],
                                            ), $updateContents) or die("Failed to update previous detail entries!");
                                            cekHijau($this->db->last_query());

                                            $mongUpdateList['update'][$tbl_detail][] = array(
                                                "where" => array(
                                                    //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                    "id" => "$triID",
                                                    //                                        "produk_id" => $iID,
                                                ),
                                                "value" => $updateContents,
                                            );
                                            unset($tru);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_sub_details = '$arrBlob' WHERE id=$k");
                            cekOrange($this->db->last_query());
                        }
                    }
                }
                else {
                    // matiHere("update subdetil biaya pos ervice");
                    //dimatiin karena bisa tanpa sub detail item
                    // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }

// matiHEre();
                if ($seluruhnya) {
                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array("id" => $prevTrID), array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    )) or die("Failed to update tr next-state!");
                    cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array(
                            "id" => "$prevTrID",
                        ),
                        "value" => array(
                            "tail_number" => $stepNum,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                            "status_4" => $_SESSION[$cCode]['main']['status_4'],
                            "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                        ),
                    );
                    cekHijau($this->db->last_query());
                }
                // matiHEre("tulis subdetail broo");
                // matiHere();
                //region tulis sub transaksi_data_items3_sum / biaya
                $seluruhnya = true;
                $prevTrID = 0;
                $arrvalidQtySisa = array();
                if (isset($_SESSION[$cCode]['tableIn_sub_detail_items']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail_items']) > 0) {
                    // matiHere(__LINE__);
                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_sub_detail_items'] as $iID => $dSpec) {
                        $insertDetailID = $tr->writeDetailSubEntries_items($insertID, $dSpec);
                        cekBiru($this->db->last_query());
                        // matiHere($this->db->last_query());
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailSubEntries_items($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                // $mongoList['detail'][] = $insertEpID;
                            }
                        }

                        cekUngu($this->db->last_query());
                        cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                        echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                        $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $gate_update => $tbl_detail) {
                                if (isset($_SESSION[$cCode][$gate_update])) {
                                    cekPink($gate_update);
                                    if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                        $itemFulfilledJml = 0;
                                        foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                            $prevTrID = $triSpec['transaksi_id'];
                                            $tru = new MdlTransaksi();
                                            $tru->setFilters(array());
                                            $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                            //----------------------------------------------------------
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                                //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                            }
                                            else {
                                                $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                                //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                            }
                                            // matiHEre(" ".$triSpec['valid_qty'] ." -". $dSpec['produk_ord_jml']);
                                            //----------------------------------------------------------
                                            $newValidQtyNotApprove = 0;
                                            if ($closedRequest == true) {
                                                cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = 0;
                                                    $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                }
                                                cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                            }
                                            //----------------------------------------------------------
                                            $itemFulfilledJml += $newValidQty;
                                            $updateContents = array(
                                                "valid_qty" => $newValidQty,
                                                "valid_qty_no_approve" => $newValidQtyNotApprove,
                                            );
                                            if ($newValidQty < 1) {
                                                $childPrevRepaclers = array(
                                                    "next_substep_code" => "",
                                                    "next_substep_label" => "",
                                                    "next_subgroup_code" => "",
                                                    "sub_tail_number" => $stepNum,
                                                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                );
                                                foreach ($childPrevRepaclers as $key => $val) {
                                                    $updateContents[$key] = $val;
                                                }
                                            }
                                            else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                $seluruhnya = false;
                                                $arrvalidQtySisa[$iID] = $newValidQty;
                                            }
                                            $dupState = $tru->updateData(array(
                                                "produk_id" => $iID,
                                                "id" => $triID,
                                                "transaksi_id" => $triSpec['transaksi_id'],
                                            ), $updateContents) or die("Failed to update previous detail entries!");
                                            cekHijau($this->db->last_query());
                                            // matiHEre();
                                            $mongUpdateList['update'][$tbl_detail][] = array(
                                                "where" => array(
                                                    //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                    "id" => "$triID",
                                                    //                                        "produk_id" => $iID,
                                                ),
                                                "value" => $updateContents,
                                            );
                                            unset($tru);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_items3_sum = '$arrBlob' WHERE id=$k");
                            cekHitam($this->db->last_query());
                        }
                    }
                }
                else {
                    // matiHere("update subdetil biaya pos ervice");
                    //dimatiin karena bisa tanpa sub detail item
                    // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                //endregion
            }
            else {
                cekMerah("tidak tulis subdetail broo");
            }
            // matiHEre("tulis subdetail broo ".__LINE__);
            //endregion

            if (isset($this->configUi[$this->jenisTr]['updateDueDate'][$stepNum])) {
                $dueDateConf = $this->configUi[$this->jenisTr]['updateDueDate'][$stepNum];
                $sourceDue = $dueDateConf['source'];
                $targetDue = $dueDateConf['target'];
                $datenow = date("Y-m-d");
                foreach ($sourceDue as $key => $val) {
                    $indexVal = isset($_SESSION[$cCode]['main_elements'][$key][$val]) ? $_SESSION[$cCode]['main_elements'][$key][$val] : 14;
                    $dueDate = dueDate($datenow, $indexVal);
                }
                $fieldDue = $tr->getFields()["dueDate"];
                $dataDue = array();
                foreach ($fieldDue as $kol) {
                    if (isset($_SESSION[$cCode]['tableIn_master'][$kol])) {
                        $dataDue[$kol] = $_SESSION[$cCode]['tableIn_master'][$kol];
                    }
                }
                $dataDue['due_date'] = $dueDate;
                $validateDue = validateDueDate($_SESSION[$cCode]['main']['customerID'], $_SESSION[$cCode]['main']['dtime']);

                arrPrint($validateDue);
                if ($validateDue['allow_create'] == "true") {
                    if (isset($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']) && $_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen'] > 0) {
                        cekBiru($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']);

                        $tr->writeDueDate($insertID, $dataDue);
                    }
                }
                else {
                    $allowedOver = validateOverDue($_SESSION[$cCode]['main']['customerID']);
                    if ($allowedOver['status'] == "allowed") {

                    }
                    else {
                        //                        matiHere($validateDue['error']);//matiin transaksi sudah over due
                    }
                    //                    arrPrint()
                    //                    matiHere($validateDue['error']);//matiin transaksi sudah over due
                }
                //                matiHere();
                //update main elementnya
                foreach ($targetDue as $keyTarget => $valTarget) {
                    $_SESSION[$cCode]['main_elements'][$keyTarget][$valTarget] = $dueDate;
                    $_SESSION[$cCode]['main']['dueDate'] = $dueDate;
                }
            }


            $baseRegistries = array(
                'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                'rsltItems3_sub' => isset($_SESSION[$cCode]['rsltItems3_sub']) ? $_SESSION[$cCode]['rsltItems3_sub'] : array(),

                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum] : array(),
                "jurnal_index" => isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
            );
            // arrPrint($baseRegistries);
            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            // matiHEre();
            echo "<script>top.writeProgress('MENULIS KE-REGISTRY.... LINE: ".__LINE__."');</script>";
        }
        else {
            die(lgShowAlert("Transaksi gagal disimpan, silahkan cek kembali transaksi ini."));
        }
        //endregion


        //region processing sub-post-processors, always
        //<editor-fold desc="----------sub postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, initializing values <br>";
                echo "<script>top.writeProgress('MENYIAPKAN DATA SUB-PROCESSORS UNTUK DIKIRIM...', 'head');</script>";

                $tmpOutParams[$cCtr] = array();
                if (isset($_SESSION[$cCode][$srcGateName]) && sizeof($_SESSION[$cCode][$srcGateName]) > 0) {
                    foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                $subParams['loop'][$key] = $realValue;

                            }
                        }
                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                $subParams['static'][$key] = $realValue;
                                cekBiru("$key diisi dengan $realValue");

                            }

                            if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                                foreach ($paramPatchers[$comName] as $k => $v) {
                                    if (!isset($subParams['static'][$k])) {
                                        $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    }
                                }
                            }
                            if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                                $jenis = $_SESSION[$cCode]['main']['jenis'];
                                foreach ($paramForceFillers[$comName] as $k => $v) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    cekorange(":: $k diisikan dengan " . $subParams['static'][$k]);
                                }
                            }

                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }
                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr][] = $subParams;
                        }
                        echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
                    }
                }

            }
            // matiHEre();

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                if (isset($_SESSION[$cCode][$srcGateName]) && sizeof($_SESSION[$cCode][$srcGateName]) > 0) {
                    $mdlName = "Com" . ucfirst($comName);
                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();
                    // matiHEre(__LINE__." $mdlName");
                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    cekBiru($this->db->last_query());
                }
                else {
                    ceklIme("skipping Com" . $comName);
                }

            }
        }

        //endregion
        // matiHEre(__LINE__);
        //
        //region processing main-post-processors, always
        //<editor-fold desc="----------postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('MEMPROSES MAIN-PROCESSORS...', 'head');</script>";
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //                cekBiru("kiriman komponem $comName");
                //                                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }


        //</editor-fold>
        //endregion

        //region postUpdaterMisc-detail untuk

        $iterator = isset($this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['detail'] : array();
        cekHitam("post procMisc pakai config core");
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "[$cCtr] sub-postProcessor: $comName, gate: $srcGateName, initializing values <br>";
                $tmpOutParams[$cCtr] = array();
                if (isset($_SESSION[$cCode][$srcGateName]) && (sizeof($_SESSION[$cCode][$srcGateName]) > 0)) {
                    arrPrint($_SESSION[$cCode][$srcGateName]);
                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        //                            $id = $dSpec['id'];
                        $id = $xid;
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['loop'][$key] = $realValue;

                            }
                        }
                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {
                                cekHitam("gate: $srcGateName, dengan key $id");
                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['static'][$key] = $realValue;

                            }
                            if (!isset($subParams['static']["transaksi_id"])) {
                                $subParams['static']["transaksi_id"] = $insertID;
                            }
                            if (!isset($subParams['static']["transaksi_no"])) {
                                $subParams['static']["transaksi_no"] = $insertNum;
                            }
                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            if (isset($_SESSION[$cCode]['revert']['postProc']['detail'])) {
                                $subParams['static']["reverted_target"] = $_SESSION[$cCode]['main']['pihakExternID'];
                            }

                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }

                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr][] = $subParams;
                        }
                    }
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                if (isset($_SESSION[$cCode][$srcGateName])) {
                    echo "[$cCtr] sub-postProcessor: $comName, sending values <br>";

                    $mdlName = "Com" . ucfirst($comName);
                    $this->load->model("Coms/" . $mdlName);
                    //arrPrint($tmpOutParams[$cCtr]);
                    $m = new $mdlName();
                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    cekPink($this->db->last_query());
                }

            }
        }

        //endregion


        //
        //region ----------subcomponents GESER KE CLI

        //        $componentGate['detail'] = array();
        //        //arrPrint($paramForceFillers);
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        $componentConfig['detail'] = $iterator;
        //        if (sizeof($iterator) > 0) {
        //            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
        //            $filterNeeded = false;
        //            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                $filterNeeded = true;
        //            }
        //            foreach ($iterator as $cCtr => $tComSpec) {
        ////                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub-component: $comName, $srcGateName, initializing values <br>";
        //                $tmpOutParams[$cCtr] = array();
        //                foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
        //                    cekmerah("mengevaluasi $srcGateName..");
        //                    $comName = $tComSpec['comName'];
        //                    if (substr($comName, 0, 1) == "{") {
        //                        $comName = trim($comName, "{");
        //                        $comName = trim($comName, "}");
        //                        $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
        //                        $tComSpec['comName'] = $comName;
        //                        $iterator[$cCtr]['comName'] = $comName;
        //                    }
        //
        //                    $filterNeeded = false;
        //                    $mdlName = "Com" . ucfirst($comName);
        //                    if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                        $filterNeeded = true;
        //                    }
        //
        //
        //                    $subParams = array();
        //                    if (isset($tComSpec['loop'])) {
        //                        foreach ($tComSpec['loop'] as $key => $value) {
        //                            if (substr($key, 0, 1) == "{") {
        //                                $key = trim($key, "{");
        //                                $key = trim($key, "}");
        //                                $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$id][$key], $key);
        //                            }
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['loop'][$key] = $realValue;
        //                            cekKuning("LOOP: $key diisi dengan $realValue");
        //
        //                            if ($filterNeeded) {
        //                                if ($subParams['loop'][$key] == 0) {
        //                                    unset($subParams['loop'][$key]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (isset($tComSpec['static'])) {
        //                        foreach ($tComSpec['static'] as $key => $value) {
        //
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['static'][$key] = $realValue;
        //                            cekKuning("STATIC: $key diisi dengan $realValue");
        //
        //                        }
        //                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
        //                            foreach ($paramPatchers[$comName] as $k => $v) {
        //                                if (!isset($subParams['static'][$k])) {
        //                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                    cekOrange("fill :: $comName :: $k => " . $subParams['static'][$k]);
        //                                }
        //                            }
        //                        }
        //                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
        //                            //                            cekOrange("comName:: $comName");
        //                            $jenis = $_SESSION[$cCode]['main']['jenis'];
        //                            foreach ($paramForceFillers[$comName] as $k => $v) {
        //                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                cekOrange("fillforce :: $comName :: $k => " . $subParams['static'][$k]);
        //                            }
        //                        }
        //                        $subParams['static']["fulldate"] = date("Y-m-d");
        //                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
        //                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
        //                    }
        //                    cekHitam("cetak subParams");
        //                    arrPrint($subParams);
        //                    if (sizeof($subParams) > 0) {
        //                        if ($filterNeeded) {
        //                            if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
        //                                $tmpOutParams[$cCtr][] = $subParams;
        //                            }
        //                        }
        //                        else {
        //
        //                            $tmpOutParams[$cCtr][] = $subParams;
        //                        }
        //                    }
        //                }
        //
        //                $componentGate['detail'][$cCtr] = $subParams;
        //            }
        //
        //
        //            $it = 0;
        //            foreach ($iterator as $cCtr => $tComSpec) {
        //                $it++;
        //
        //
        //                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub component #$it: $comName, sending values <br>";
        //
        //                $mdlName = "Com" . ucfirst($comName);
        //                $this->load->model("Coms/" . $mdlName);
        //                $m = new $mdlName();
        //
        //
        //                if (sizeof($tmpOutParams[$cCtr]) > 0) {
        //                    $tobeExecuted = true;
        //                }
        //                else {
        //                    $tobeExecuted = false;
        //                }
        //
        //
        //                if ($tobeExecuted) {
        //                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                }
        //                else {
        //                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
        //                }
        //            }
        //        }
        //        else {
        //            //cekKuning("subcomponents is not set");
        //        }

        //endregion


        //region ----------components
        //<editor-fold desc="----------components">

        $componentGate['master'] = array();
        $componentConfig['master'] = array();
        if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
            $iterator = isset($_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master']) ? $_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master'] : array();
        }
        else {
            if (isset($_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'])) {
                $iterator = $_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'])) {
                $iterator = $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'];
            }
            else {
                $iterator = array();
            }
        }


        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('KOMPONEN...', 'head');</script>";
            $componentConfig['master'] = $iterator;

            $it = 0;
            //==filter nilai, jika NOL tidak dikirim, sesuai config==
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            foreach ($iterator as $cCtr => $tComSpec) {
                //                cekPink($tComSpec);
                //                mati_disini();
                $it++;
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "component #$it: $comName :: $srcGateName <br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            //                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                            $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$key], $key);
                        }
                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        if ($key != null) {
                            $tmpOutParams['loop'][$key] = $realValue;
                        }

                    }
                }
                //                cekBiru($tmpOutParams);
                //                mati_disini(__LINE__);
                if (isset($tComSpec['static'])) {
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;
                        cekHijau(":: NORMAL :: $key => $realValue ::");
                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        cekHijau(":: masuk ke PATCHER ::");
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            cekHijau(":: ada yang mau di-PATCHER ::");
                            arrPrint($tmpOutParams['static']);
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekHijau(":: PATCHER :: $key => $realValue ::");
                            }

                        }
                    }
                    else {
                        cekMerah(":: TIDAK TERMASUK PATCHER ::");
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            cekHijau(":: FORCEFILL :: $key => $realValue ::");
                        }
                    }
                    $tmpOutParams['static']["urut"] = $cCtr;
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //===filter value nol, jika harus difilter
                $tobeExecuted = true;

                if (in_array($mdlName, $compValidators)) {

                    $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                    if (sizeof($loopParams) > 0) {
                        foreach ($loopParams as $key => $val) {
                            cekmerah("$comName : $key = $val ");
                            if ($val == 0) {
                                unset($tmpOutParams['loop'][$key]);
                            }
                        }
                    }
                    if (sizeof($tmpOutParams['loop']) < 1) {
                        $tobeExecuted = false;
                    }

                }


                if ($tobeExecuted) {
                    cekBiru("kiriman komponen $comName " . __LINE__);
                    arrPrint($tmpOutParams);
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("komponem $comName tidak memenuhi syarat untuk ditulis");
                }

                $componentGate['master'][$cCtr] = $tmpOutParams;
            }
        }
        else {
            //cekKuning("components is not set");
        }


        //endregion


        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    if (isset($paymentSrcConfig['model'])) {
                        $mdlName = $paymentSrcConfig['model'];
                        $this->load->model("Mdls/$mdlName");
                        $pMdl = New $mdlName();
                        $pTmpMdl = $pMdl->lookupAll()->result();
                        $pTmpMdlResult = array();
                        if (sizeof($pTmpMdl) > 0) {
                            foreach ($pTmpMdl as $pTmpMdlSpec) {
                                $pTmpMdlResult[$pTmpMdlSpec->id] = $pTmpMdlSpec;
                            }
                        }
                    }
                    else {
                        $pTmpMdlResult = array();
                    }

                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        if (isset($externSrc['extern_label2'])) {
                            //cek ada isinya atau kosong
                            $cek = strlen($_SESSION[$cCode]['main'][$externSrc['extern_label2']]) > 4 ? "" : matiHere("jenis biaya tidak dikenali " . __LINE__);//
                        }
                        //region cek duplikasi paymentsource
                        $tr->setFilters(array());
                        $tr->addFilter("transaksi_id='$insertID'");
                        $tr->addFilter("target_jenis='" . $paymentSrcConfig['jenisTarget'] . "'");
                        // $tr->addFilter("target_jenis='759'");
                        $validateIsInserted = $tr->lookUpAllPaymentSrc()->result();
                        if (sizeof($validateIsInserted) > 0) {
                            matiHEre("Gagal menulis transaksi. Silahkan relogin untuk membersihkan sesi demi menghindari duplikasi data, dan coba kembali transaksi yang gagal");
                        }
                        //endregion
                        $arrPymSrc = array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],

                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],

                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',

                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

                            //                            "extern_label2" => isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "",
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",

                            "ppn" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_approved" => (isset($externSrc['ppn_approved']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_approved']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_approved']] : 0,
                            "ppn_sisa" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_status" => (isset($externSrc['ppn_status'])) ? $externSrc['ppn_status'] : 0,
                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                            "extern_date2" => (isset($externSrc['extern_date2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_date2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_date2']] : "",
                            "pph_23" => (isset($externSrc['pph_23']) && ($_SESSION[$cCode]['main'][$externSrc['pph_23']])) ? $_SESSION[$cCode]['main'][$externSrc['pph_23']] : "",

                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : "",
                            "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : "",
                            "ppn_pph_faktor" => (isset($externSrc['ppn_pph_faktor']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']] : "",
                            "extern_jenis" => (isset($externSrc['extern_jenis']) && ($_SESSION[$cCode]['main'][$externSrc['extern_jenis']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_jenis']] : "",
                            "extern_nilai3" => (isset($externSrc['extern_nilai3']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai3']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai3']] : "",
                            "extern_nilai4" => (isset($externSrc['extern_nilai4']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai4']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai4']] : "",
                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            //                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : "",
                            "payment_locked" => (isset($externSrc['payment_locked']) && ($_SESSION[$cCode]['main'][$externSrc['payment_locked']])) ? $_SESSION[$cCode]['main'][$externSrc['payment_locked']] : 0,
                            "cash_account" => (isset($externSrc['cash_account']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account']] : 0,
                            "cash_account_nama" => (isset($externSrc['cash_account_nama']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account_nama']] : 0,
                            "project_id" => (isset($externSrc['project_id']) && ($_SESSION[$cCode]['main'][$externSrc['project_id']])) ? $_SESSION[$cCode]['main'][$externSrc['project_id']] : 0,
                            "project_nama" => (isset($externSrc['project_nama']) && ($_SESSION[$cCode]['main'][$externSrc['project_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['project_nama']] : 0,
                            "payment_source_keterangan" => (isset($externSrc['payment_source_keterangan']) && ($_SESSION[$cCode]['main'][$externSrc['payment_source_keterangan']])) ? $_SESSION[$cCode]['main'][$externSrc['payment_source_keterangan']] : "",
                        );
//                        arrPrintHijau($arrPymSrc);
                        $tr->writePaymentSrc($insertID, $arrPymSrc);

                        cekMerah($this->db->last_query());
                    }



                }
            }

        }
        else {
            cekMerah("TIDAK nulis paymentSrc | STEPCODE: $stepCode | STEPNUM: $stepNum | LINE: " . __LINE__);
        }

        //matiHere("hoopppp");
        //cek additional step
        $addPaymentSource = isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService']) ? $this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService'] : array();
        //        arrPrint($addPaymentSource);
        //endregion


        //
        //region nulis paymentAntiSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_antiSource");
        if (array_key_exists($stepCode, $paymentSources)) {
            cekMerah(":: starting PAYMENT ANTI SOURCE");
            $payConfigs = $paymentSources[$stepCode];
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    $tr->writePaymentAntiSrc($insertID, array(
                        "jenis" => $stepCode,
                        "target_jenis" => $paymentSrcConfig['jenisTarget'],
                        "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                        "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                        "nomer" => $tmpNomorNota2,
                        "label" => $paymentSrcConfig['label'],
                        "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                        "terbayar" => 0,
                        "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                        "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                        "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "dtime" => date("Y-m-d H:i:s"),
                        "fulldate" => date("Y-m-d"),
                    ));
                    //cekMerah($this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }
        //endregion

        //region nulis uangMukaSource
        /*dimatiin geser ke ComUangmukaSourceDetail karena ada di items.
        /*revisi tanggal 27 mei 2020 subject digeser ke vendor dari jenis transaksi misal uangmuka asuransi,uang muka pembelian ->uang muka.
         *
         */
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $uangMukaSources = $this->config->item("uang_muka");

        if (array_key_exists($stepCode, $uangMukaSources)) {
            cekMerah(":: starting UANG MUKA  SOURCE");
            //            matiHere();
            $uangMukaConfigs = isset($uangMukaSources[$stepCode][$stepNum]) ? $uangMukaSources[$stepCode][$stepNum] : array();
            if (sizeof($uangMukaConfigs) > 0) {
                $cekPreValue = "";
                $this->load->model("Mdls/MdlPaymentUangMuka");
                $l = new MdlPaymentUangMuka();
                foreach ($uangMukaConfigs as $uangMukaSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    //                    arrPrint($uangMukaSrcConfig);
                    $valueSrc = $uangMukaSrcConfig['valueSrc'];
                    $externSrc = $uangMukaSrcConfig['externSrc'];
                    $l->addFilter("extern_id='" . $_SESSION[$cCode]['main'][$externSrc['id']] . "'");
                    $l->addFilter("extern_label2='" . $externSrc['extLabel'] . "'");
                    $tmpUm = $l->lookupAll()->result();
                    //                    arrPrint($tmpUm);
                    if (sizeof($tmpUm) > 0) {
                        //update here broo
                        $preTagihan = $tmpUm[0]->tagihan;
                        $preSisa = $tmpUm[0]->sisa;

                        $newTahigan = $preTagihan + $_SESSION[$cCode]['main'][$valueSrc];
                        $newsisa = $preSisa + $_SESSION[$cCode]['main'][$valueSrc];
                        $update = array(
                            "tagihan" => $newTahigan,
                            "sisa" => $newsisa,
                        );
                        $where = array(
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        );
                        $tr->updateUangMukaSrc($where, $update);
                        cekHitam($this->db->last_query());
                    }
                    else {
                        //insertbaru brooo
                        $tr->writeUangMukaSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $uangMukaSrcConfig['jenisTarget'],
                            "reference_jenis" => $uangMukaSrcConfig['jenisSrc'],
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                            "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                            "nomer" => "",
                            "note" => "",
                            "label" => $uangMukaSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "extern_label2" => $externSrc['extLabel'],
                        ));
                    }
                    cekMerah($this->db->last_query());
                }
            }
            else {
                cekLime("not write uang muka");
            }

        }
        else {
            cekMerah("not write uang muka");
        }
        //endregion

        cekMerah("MULAI LAST_VALIDATE");
        $va->setJenisTr($this->jenisTr);
        $va->lastValidate($insertID);
        //        mati_disini("setelah lastValidate");


        cekKuning(":: mulai cek rek besar dan rek pembantu");
        $cabangID_validate = $this->session->login['cabang_id'];


        validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota2);
        validateJurnal($insertID, $componentConfig);
        validateAllBalances();


        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, $insertID);
        //==================================================================================================

        //
        //region connecting antar cabang
        $referensiIDProject = $insertID;
        $steps = isset($this->configUi[$origJenis]['steps']) ? $this->configUi[$origJenis]['steps'] : array();
        $connector = isset($this->configUi[$origJenis]['connectTo']) ? $this->configUi[$origJenis]['connectTo'] : "";
        $preReplacer = isset($this->configUi[$this->jenisTr]['replacerConnectTo']) ? $this->configUi[$this->jenisTr]['replacerConnectTo'] : array();
        $validateValueConnector = isset($this->configUi[$this->jenisTr]['connectoValidate'][$stepNum]) ? $this->configUi[$this->jenisTr]['connectoValidate'][$stepNum] : array();
        $mongoListConnect = array();
        $mongRegIDConnect = array();
//arrPrintPink($_SESSION[$cCode]['tableIn_master']);
        if (strlen($connector) > 0) {
            cekMerah("to be connected to $connector |$stepNum|" . sizeof($steps));
            // matiHere();
            $configUiMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiUi");
            $configCoreMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiCore");
            $configLayoutMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiLayout");
            if (isset($this->configUi[$this->jenisTr]['connectoValidate'][$stepNum])) {
                $validateValueConnector = $this->configUi[$this->jenisTr]['connectoValidate'][$stepNum];
                $preVal = $_SESSION[$cCode]['main'][$validateValueConnector];

                // $stepNum = $preVal > 0 ? $stepNum : "1000";//1000 untuk nglewatin step biar gak jalan connectingnya karena nilai yang dicari 0 kasusnya cash in advance ppn sudah masuk pusat tidak perlu diterbitkan auto dorong ppn ke pusat
                $validateStepNum = $preVal > 0 ? sizeof($steps) : "1000";//1000 untuk nglewatin step biar gak jalan connectingnya karena nilai yang dicari 0 kasusnya cash in advance ppn sudah masuk pusat tidak perlu diterbitkan auto dorong ppn ke pusat
            }
            else {
                $validateStepNum = $stepNum;
            }
            // matiHere($validateStepNum." ".sizeof($steps)." ".$preVal);
            if ($validateStepNum == sizeof($steps)) {
                cekMerah("NOW CONNECTING to $connector");
                //                if (!array_key_exists($connector, $this->configUi)) {
                //                    die("kode connector tidak dikenali!");
                //                }
                if (sizeof($configCoreMasterModulJenis) < 1) {
                    mati_disini("kode connector tidak dikenali!");
                }
                else {
                    cekHijau("kode connector dikenali, lanjutkan...");
                }

                //                mati_disini("konekting antar cabang");

                if (sizeof($configUiMasterModulJenis['steps']) < 2) {
                    die("konfigurasi connector harus memiliki step lebih dari satu!");
                }


                $oldCode = $cCode;
                $cCode = "_TR_" . $connector;

                $_SESSION[$cCode] = array();
                $_SESSION[$cCode] = array(
                    "main" => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                    "items" => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                    "items2" => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                    "items2_sum" => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                    "items3" => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                    "items3_sum" => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                    "items4_sum" => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                    "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),

                    "tableIn_master" => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                    "tableIn_detail" => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),

                    "rsltItems" => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                    "tableIn_detail_rsltItems" => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),

                    "tableIn_master_values" => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                    "tableIn_detail_values" => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                    "tableIn_detail_values_rsltItems" => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                    //---------------------------
                    "tableIn_sub_detail" => isset($_SESSION[$oldCode]['tableIn_sub_detail']) ? $_SESSION[$oldCode]['tableIn_sub_detail'] : array(),
                    "tableIn_sub_detail_items" => isset($_SESSION[$oldCode]['tableIn_sub_detail_items']) ? $_SESSION[$oldCode]['tableIn_sub_detail_items'] : array(),
                    "tableIn_detail2_sum" => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                    "tableIn_detail2" => isset($_SESSION[$oldCode]['tableIn_detail2']) ? $_SESSION[$oldCode]['tableIn_detail2'] : array(),
                    "items_child" => isset($_SESSION[$oldCode]['items_child']) ? $_SESSION[$oldCode]['items_child'] : array(),
                    "tableIn_detail_values" => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                    "tableIn_detail_values2_sum" => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                    //---------------------------
                );

                //==replace pertama
                $masterReplacersO = array(
                    "jenisTr" => $connector,
                    "jenisTrMaster" => $connector,
                    "jenisTrTop" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis_label" => $configUiMasterModulJenis['steps'][1]['label'],
                    "transaksi_jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "stepCode" => $configUiMasterModulJenis['steps'][1]['target'],
                    "placeID" => isset($preReplacer['place2ID']) ? $preReplacer['place2ID'] : $_SESSION[$cCode]['main']['place2ID'],
                    "placeName" => isset($preReplacer['place2Name']) ? $preReplacer['place2Name'] : $_SESSION[$cCode]['main']['place2Name'],
                    "place2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "place2Name" => $_SESSION[$cCode]['main']['placeName'],
                    "cabangID" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$cCode]['main']['place2ID'],
                    "cabangName" => isset($preReplacer['place2Name']) ? $preReplacer['place2Name'] : $_SESSION[$cCode]['main']['place2Name'],
                    "cabang2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "cabang2Name" => $_SESSION[$cCode]['main']['placeName'],
                    //
                    "gudang2ID" => $_SESSION[$cCode]['main']['gudangID'],
                    "gudang2Name" => $_SESSION[$cCode]['main']['gudangName'],
                    "gudangID" => isset($preReplacer['gudang2ID']) ? $preReplacer['gudang2ID'] : $_SESSION[$cCode]['main']['gudang2ID'],
                    "gudangName" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$cCode]['main']['gudang2Name'],
                    "pihakID" => isset($_SESSION[$cCode]['main']['placeID']) ? $_SESSION[$cCode]['main']['placeID'] : "",
                    "pihakName" => isset($_SESSION[$cCode]['main']['placeName']) ? $_SESSION[$cCode]['main']['placeName'] : "",
                    "pihakName2" => $_SESSION[$cCode]['main']['placeName'],
                    "gudang" => $_SESSION[$cCode]['main']['gudangID'],
                    "gudang__name" => $_SESSION[$cCode]['main']['gudangName'],
                    "gudang__label" => $_SESSION[$cCode]['main']['gudangName'],
                    "efaktur_source" => isset($preReplacer['efaktur_source']) ? $_SESSION[$cCode]['main']['nomer'] : "",

                );
                foreach ($masterReplacersO as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    //                    $_SESSION[$cCode]['main'][$key] = $val;
                }
                $masterReplacers = array(
                    //                    "referensi_id" => $masterID, (dimatikan)
                    "inv" => $tmpNomorNota,
                    "jenis_master" => $connector,
                    "jenis_top" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis_label" => $configUiMasterModulJenis['steps'][1]['label'],
                    "transaksi_jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "cabang_id" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$cCode]['tableIn_master']['cabang2_id'],
                    "cabang_nama" => isset($preReplacer['cabang2Name']) ? $preReplacer['cabang2Name'] : $_SESSION[$cCode]['tableIn_master']['cabang2_nama'],
                    "cabang2_id" => $_SESSION[$cCode]['tableIn_master']['cabang_id'],
                    "cabang2_nama" => $_SESSION[$cCode]['tableIn_master']['cabang_nama'],
                    "gudang_id" => isset($preReplacer['gudang2ID']) ? $preReplacer['gudang2ID'] : $_SESSION[$cCode]['tableIn_master']['gudang2_id'],
                    "gudang_nama" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$cCode]['tableIn_master']['gudang2_nama'],
                    "gudang2_id" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                    "gudang2_nama" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                    "gudang" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                    "gudang__name" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                    "gudang__label" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],

                    "step_avail" => sizeof($configUiMasterModulJenis['steps']),
                    "step_current" => 1,
                    "step_number" => 1,
                    "next_step_code" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['target'] : "",
                    "next_step_label" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['label'] : "",
                    "next_group_code" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['userGroup'] : "",
                    "next_step_num" => isset($configUiMasterModulJenis['steps'][2]) ? 2 : "0",
                    "efaktur_source" => isset($preReplacer['efaktur_source']) ? $_SESSION[$cCode]['main']['nomer'] : "",
                    //===references
                    //                    "id_master"            => $masterID,
                    //                    "id_top"               => $topID,
                    //                    "ids_prev"             => base64_encode(serialize(array($prevProp['id']))),
                    //                    "ids_prev_intext"      => print_r(array($prevProp['id'], true)),
                    //                    "nomer_top"            => $_SESSION[$cCode]['main']['nomer'],
                    //                    "nomers_prev"          => base64_encode(serialize(array($prevProp['nomer']))),
                    //                    "nomers_prev_intext"   => print_r(array($prevProp['nomer'], true)),
                    //                    "jenis_top"            => $this->jenisTr,
                    //                    "jenises_prev"        => base64_encode(serialize(array($prevProp['jenis']))),
                    //                    "jenises_prev_intext" => print_r(array($prevProp['jenis'], true)),
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }


                //region penomoran receipt #2
                //<editor-fold desc="==========penomoran">
                $this->load->model("CustomCounter");
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);

                $counterForNumber = array($configCoreMasterModulJenis['formatNota']);
                if (!in_array($counterForNumber[0], $configCoreMasterModulJenis['counters'])) {
                    die(__LINE__ . " Used number should be registered in 'counters' config as well");
                }

                foreach ($counterForNumber as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        //                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                }

                $tmpNomorNota2 = $paramSpec['paramString'];
                $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);


                //</editor-fold>
                //endregion

                //region dynamic counters #2
                // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);
                $configCustomParams = $configCoreMasterModulJenis['counters'];
                $configCustomParams[] = "stepCode";
                if (sizeof($configCustomParams) > 0) {
                    $cContent = array();
                    foreach ($configCustomParams as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                        switch ($paramSpec['id']) {
                            case 0: //===counter type is new
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                break;
                        }
                        //echo "<hr>";
                    }
                }
                $appliedCounters2 = base64_encode(serialize($cContent));
                $appliedCounters_inText2 = print_r($cContent, true);
                // </editor-fold>
                //endregion

                //region numbering tambahan
                $this->load->library("CounterNumber");
                $ccn = new CounterNumber();
                $ccn->setCCode($cCode);
                $ccn->setJenisTr($connector);
                $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
                $ccn->setMainGate($_SESSION[$cCode]['main']);
                $ccn->setItemsGate($_SESSION[$cCode]['items']);
                $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
                $new_counter = $ccn->getCounterNumber();
                cekHitam("jenistr yang disett dari create " . $this->jenisTr);

                if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
                    foreach ($new_counter['main'] as $ckey => $cval) {
                        $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                        $_SESSION[$cCode]['main'][$ckey] = $cval;
                    }
                }
                if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
                    foreach ($new_counter['items'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
                    foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                //endregion
                $addValues = array(
                    'counters' => $appliedCounters2,
                    'counters_intext' => $appliedCounters_inText2,
                    'nomer' => $tmpNomorNota2,
                    'nomer2' => $tmpNomorNota2Alias,
                    'dtime' => date("Y-m-d H:i:s"),
                    'fulldate' => date("Y-m-d"),
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning nota cab1 ke cab2
                //===daftar perbedaan
                //== referensi_id, inv, jenis, nomer, counters, counters_inText, cabang_id, cabang_nama, cabang2_id, cabang2_nama,

                //==replace kedua
                $masterReplacers = array(
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning detail/items cabang1 ke cabang2
                //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code
                $detailReplacers = array(
                    "sub_step_avail" => sizeof($configUiMasterModulJenis['steps']),
                    "sub_step_current" => 1,
                    "sub_step_number" => 1,
                    "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                    "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                    "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                    "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                );
                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    //                    cekmerah("tulis rincian transaksi kedua");
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                        foreach ($dSpec as $key => $val) {
                            $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                        }
                    }
                }
                else {
                    //                    cekmerah("GAGAL tulis rincian transaksi kedua");
                }


                //region ----------write transaksi & transaksi_data #2
                if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                    $_SESSION[$cCode]['tableIn_master']['referensi_id'] = $referensiIDProject;
                    $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                    $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                    cekUngu($this->db->last_query());
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                    $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                    $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                    $mongoListConnect['main'] = array($insertID, $epID);
                    cekmerah("tulis transaksi kedua :: trID $insertID");
                    cekmerah($this->db->last_query());
                    if ($insertID < 1) {
                        die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                }
                else {
                    cekmerah("GAGAL tulis transaksi kedua");
                }
                if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                    $inserMainValues = array();
                    foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                }
                if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                    foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }
                if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                    foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }
                if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                    //                    cekMerah("ada mainElements");
                    foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => $aSpec['label'],
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                        ));
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoListConnect['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                $mongoListConnect['detail'][] = $insertEpID;
                            }
                        }
                    }
                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                            cekOrange($this->db->last_query());
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                        $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                        $mongoListConnect['detail'] = $insertIDs;
                        if ($epID != 999) {
                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                            $mongoListConnect['detail'] = $mongoListConnect['detail'] = $insertIDs;;
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                //                                $insertIDs[$pID][] = $tr->writeDetailValues($insertID, array(
                                //                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                //                                    "produk_id" => $pID,
                                //                                    "key" => $key,
                                //                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                                //                                ));
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                                ));
                                $insertIDs[] = $dd;
                                $mongoListConnect['detailValues'][] = $dd;

                            }
                        }
                    }
                    if (sizeof($insertIDs) > 0) {
                        $arrBlob = blobEncode($insertIDs);
                        $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                $insertIDs[] = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));

                            }
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail2'] as $iID => $dSpec) {
                        $dd = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                        if ($epID != 999) {
                            $dd = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $dd;
                            $mongoList['detail'][] = $dd;
                        }
                        cekUngu($this->db->last_query());
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));
                                $insertIDs[$pID][] = $dd;
                                $mongoList['detailValues'][] = $dd;
                            }
                        }


                    }
                }


                //region cloner items to item_child
                if (sizeof($additionalData) > 0) {
                    echo "<script>top.writeProgress('CLONING ITEMS TO ITEM CHILD...','head');</script>";
                    cekHitam("ini data");
                    $dataMdl = $additionalData["mdlName"];
                    $this->load->model("Mdls/" . $dataMdl);
                    $da = new $dataMdl();
                    $arrColl = $da->getFields();
                    $selectedCol = array();
                    foreach ($arrColl as $colSpec) {
                        $selectedCol[] = $colSpec['kolom'];
                    }

                    if (isset($_SESSION[$cCode]['items_child']) && sizeof($_SESSION[$cCode]['items_child'])) {
                        $gateData = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate'] : "detail";

                        $arrBlacklist = array(
                            "jml", "max_jml", "qty",
                        );
                        if (isset($_SESSION[$cCode]["items2_sum"])) {
                            unset($_SESSION[$cCode]["items2_sum"]);
                            unset($_SESSION[$cCode]["items2"]);
                            unset($_SESSION[$cCode]["tableIn_detail_values2_sum"]);
                        }
                        foreach ($_SESSION[$cCode]['items_child'] as $mainProdsID => $defData) {
                            if ($gateData == "detail") {
                                $itemsMain = isset($_SESSION[$cCode]['items'][$mainProdsID]) ? $_SESSION[$cCode]['items'][$mainProdsID] : array();
                            }
                            else {
                                $forceMainToItems = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData]) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData] : array();
                                if (sizeof($forceMainToItems) > 0) {
                                    foreach ($forceMainToItems as $key1 => $key2) {
                                        $keyForce = strlen($key2) > 2 ? $key2 : $key1;
                                        $itemsMain[$key1] = isset($_SESSION[$cCode]['main'][$keyForce]) ? $_SESSION[$cCode]['main'][$keyForce] : "";
                                    }
                                    $itemsMain["jml"] = "1";
                                    $itemsMain["qty"] = "1";
                                    $itemsMain["max_jml"] = "1";

                                }
                                else {
                                    matiHEre("detil aset gagal di tulis!");
                                }
                                //                            arrPrint($forceMainToItems);
                            }

                            $arrChilds = array_diff_key($itemsMain, array_flip($arrBlacklist));
                            //                        arrPrint($itemsMain);
                            //                        matiHEre();
                            //
                            //arrPrint($arrChilds);
                            cekLime("ini brooo " . $gateData);

                            $arrNew = array();
                            if (sizeof($itemsMain) > 0) {
                                foreach ($defData as $inID => $detil_child) {
                                    //                        $arrNewChild = array_diff($itemsMain,$detil_child);

                                    $paramDetil = array_replace($arrChilds, $detil_child);
                                    if (array_key_exists("id", $paramDetil)) {

                                        $paramDetil["parent_id"] = $paramDetil["id"];
                                        if (!isset($paramDetil["folders"]) || $paramDetil["folders"] == 0) {
                                            $paramDetil["folders"] = $paramDetil["pihakMainId"];
                                            $paramDetil["keterangan"] = $paramDetil["pihakMainName"];
                                        }
                                        unset($paramDetil["id"]);
                                    }
                                    $tmpData = array();
                                    foreach ($selectedCol as $i => $coloum) {
                                        if (isset($paramDetil[$coloum])) {
                                            $tmpData[$coloum] = $paramDetil[$coloum];
                                        }
                                    }
                                    //                                arrPrint($paramDetil);
                                    if (isset($paramDetil["subtotal"])) {
                                        $paramDetil["subtotal"] = $paramDetil["jml"] * $paramDetil["harga"];
                                    }

                                    $insertDataID = $da->addData($tmpData, $da->getTableName()) or die(lgShowError("Gagal menulis pengajuan data", __FILE__));
                                    cekHere($this->db->last_query());
                                    $paramDetil["id"] = $insertDataID;
                                    echo "<script>top.writeProgress('PENGAJUAN DATA (TRID:$insertDataID)');</script>";
                                    $_SESSION[$cCode]["items2_sum"][$insertDataID] = $paramDetil;
                                    $_SESSION[$cCode]["items2"][$mainProdsID][$insertDataID] = $paramDetil;
                                    //                            $arrNew

                                }
                            }


                            //                        arrPrint($arrNew);
                            //


                            //                  arrPrint($itemsMain);
                        }

                    }
                }
                //endregion
                //region tulis sub transaksi data
                if (isset($this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget]) && $this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget] == true) {
                    $seluruhnya = true;
                    $prevTrID = 0;
                    $arrvalidQtySisa = array();
                    if (isset($_SESSION[$cCode]['tableIn_sub_detail']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail']) > 0) {

                        $insertIDs = array();
                        $insertDeIDs = array();
                        foreach ($_SESSION[$cCode]['tableIn_sub_detail'] as $iID => $dSpec) {
                            $insertDetailID = $tr->writeDetailSubEntries($insertID, $dSpec);
                            showLast_query("orange");
                            if ($insertDetailID < 1) {
                                die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertDetailID;
                                $insertDeIDs[$insertID][] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                            }
                            if ($epID != 999) {
                                $insertEpID = $tr->writeDetailSubEntries($epID, $dSpec);
                                if ($insertEpID < 1) {
                                    die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                                }
                                else {
                                    $insertIDs[] = $insertEpID;
                                    $insertDeIDs[$epID][] = $insertEpID;
                                    // $mongoList['detail'][] = $insertEpID;
                                }
                            }

                            cekUngu($this->db->last_query());
                            cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                            echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                            $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $gate_update => $tbl_detail) {
                                    if (isset($_SESSION[$cCode][$gate_update])) {
                                        if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                            $itemFulfilledJml = 0;
                                            foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                                arrPrintPink($triSpec);
                                                $prevTrID = $triSpec['transaksi_id'];
                                                $tru = new MdlTransaksi();
                                                $tru->setFilters(array());
                                                $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                                //----------------------------------------------------------
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
//                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                                    $produk_ord_diterima = ($triSpec['dikirim_qty'] + $dSpec['produk_ord_jml']);
                                                }
                                                else {
                                                    $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
//                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                                    $produk_ord_diterima = ($triSpec['dikirim_qty'] + $triSpec['valid_qty']);
                                                }
                                                //----------------------------------------------------------
                                                $newValidQtyNotApprove = 0;
                                                if ($closedRequest == true) {
                                                    cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                    if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                        $newValidQty = 0;
                                                        $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                    }
                                                    cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                                }
                                                //----------------------------------------------------------
                                                $itemFulfilledJml += $newValidQty;
                                                $updateContents = array(
                                                    "valid_qty" => $newValidQty,
                                                    "valid_qty_no_approve" => $newValidQtyNotApprove,
                                                    "produk_ord_diterima" => $produk_ord_diterima,
                                                );
                                                if ($newValidQty < 1) {
                                                    $childPrevRepaclers = array(
                                                        "next_substep_code" => "",
                                                        "next_substep_label" => "",
                                                        "next_subgroup_code" => "",
                                                        "sub_tail_number" => $stepNum,
                                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                    );
                                                    foreach ($childPrevRepaclers as $key => $val) {
                                                        $updateContents[$key] = $val;
                                                    }
                                                }
                                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                    $seluruhnya = false;
                                                    $arrvalidQtySisa[$iID] = $newValidQty;
                                                }
                                                $dupState = $tru->updateData(array(
                                                    "produk_id" => $iID,
                                                    "id" => $triID,
                                                    "transaksi_id" => $triSpec['transaksi_id'],
                                                ), $updateContents) or die("Failed to update previous detail entries!");
                                                cekHijau($this->db->last_query());

                                                $mongUpdateList['update'][$tbl_detail][] = array(
                                                    "where" => array(
                                                        //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                        "id" => "$triID",
                                                        //                                        "produk_id" => $iID,
                                                    ),
                                                    "value" => $updateContents,
                                                );
                                                unset($tru);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (sizeof($insertIDs) == 0) {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                        }
                        else {
                            $indexing_details = array();
                            foreach ($insertDeIDs as $key => $numb) {
                                $indexing_details[$key] = $numb;
                            }

                            foreach ($indexing_details as $k => $arrID) {
                                $arrBlob = blobEncode($arrID);
                                $this->db->query("UPDATE transaksi SET indexing_sub_details = '$arrBlob' WHERE id=$k");
                                cekOrange($this->db->last_query());
                            }
                        }
                    }
                    else {
                        cekMerah("tidak ada tableIn_sub_detail");
                        //dimatiin karena bisa tanpa sub detail item
                        // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                    }

// matiHEre();
                    if ($seluruhnya) {
                        $tr = new MdlTransaksi();
                        $dupState = $tr->updateData(array("id" => $prevTrID), array(
                            "tail_number" => $stepNum,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                            "status_4" => $_SESSION[$cCode]['main']['status_4'],
                            "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                        )) or die("Failed to update tr next-state!");
                        cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                        $mongUpdateList['update']['main'][] = array(
                            "where" => array(
                                "id" => "$prevTrID",
                            ),
                            "value" => array(
                                "tail_number" => $stepNum,
                                "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                "status_4" => $_SESSION[$cCode]['main']['status_4'],
                                "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                            ),
                        );
                        cekHijau($this->db->last_query());
                    }
                    // matiHEre("tulis subdetail broo");
                    // matiHere();
                    //region tulis sub transaksi_data_items3_sum / biaya
                    $seluruhnya = true;
                    $prevTrID = 0;
                    $arrvalidQtySisa = array();
                    if (isset($_SESSION[$cCode]['tableIn_sub_detail_items']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail_items']) > 0) {
                        // matiHere(__LINE__);
                        $insertIDs = array();
                        $insertDeIDs = array();
                        foreach ($_SESSION[$cCode]['tableIn_sub_detail_items'] as $iID => $dSpec) {
                            $insertDetailID = $tr->writeDetailSubEntries_items($insertID, $dSpec);
                            cekBiru($this->db->last_query());
                            // matiHere($this->db->last_query());
                            if ($insertDetailID < 1) {
                                die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertDetailID;
                                $insertDeIDs[$insertID][] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                            }
                            if ($epID != 999) {
                                $insertEpID = $tr->writeDetailSubEntries_items($epID, $dSpec);
                                if ($insertEpID < 1) {
                                    die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                                }
                                else {
                                    $insertIDs[] = $insertEpID;
                                    $insertDeIDs[$epID][] = $insertEpID;
                                    // $mongoList['detail'][] = $insertEpID;
                                }
                            }

                            cekUngu($this->db->last_query());
                            cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                            echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                            $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $gate_update => $tbl_detail) {
                                    if (isset($_SESSION[$cCode][$gate_update])) {
                                        cekPink($gate_update);
                                        if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                            $itemFulfilledJml = 0;
                                            foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                                $prevTrID = $triSpec['transaksi_id'];
                                                $tru = new MdlTransaksi();
                                                $tru->setFilters(array());
                                                $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                                //----------------------------------------------------------
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                                    //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                                }
                                                else {
                                                    $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                                    //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                                }
                                                // matiHEre(" ".$triSpec['valid_qty'] ." -". $dSpec['produk_ord_jml']);
                                                //----------------------------------------------------------
                                                $newValidQtyNotApprove = 0;
                                                if ($closedRequest == true) {
                                                    cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                    if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                        $newValidQty = 0;
                                                        $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                    }
                                                    cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                                }
                                                //----------------------------------------------------------
                                                $itemFulfilledJml += $newValidQty;
                                                $updateContents = array(
                                                    "valid_qty" => $newValidQty,
                                                    "valid_qty_no_approve" => $newValidQtyNotApprove,
                                                );
                                                if ($newValidQty < 1) {
                                                    $childPrevRepaclers = array(
                                                        "next_substep_code" => "",
                                                        "next_substep_label" => "",
                                                        "next_subgroup_code" => "",
                                                        "sub_tail_number" => $stepNum,
                                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                    );
                                                    foreach ($childPrevRepaclers as $key => $val) {
                                                        $updateContents[$key] = $val;
                                                    }
                                                }
                                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                    $seluruhnya = false;
                                                    $arrvalidQtySisa[$iID] = $newValidQty;
                                                }
                                                $dupState = $tru->updateData(array(
                                                    "produk_id" => $iID,
                                                    "id" => $triID,
                                                    "transaksi_id" => $triSpec['transaksi_id'],
                                                ), $updateContents) or die("Failed to update previous detail entries!");
                                                cekHijau($this->db->last_query());
                                                // matiHEre();
                                                $mongUpdateList['update'][$tbl_detail][] = array(
                                                    "where" => array(
                                                        //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                        "id" => "$triID",
                                                        //                                        "produk_id" => $iID,
                                                    ),
                                                    "value" => $updateContents,
                                                );
                                                unset($tru);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (sizeof($insertIDs) == 0) {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                        }
                        else {
                            $indexing_details = array();
                            foreach ($insertDeIDs as $key => $numb) {
                                $indexing_details[$key] = $numb;
                            }

                            foreach ($indexing_details as $k => $arrID) {
                                $arrBlob = blobEncode($arrID);
                                $this->db->query("UPDATE transaksi SET indexing_items3_sum = '$arrBlob' WHERE id=$k");
                                cekHitam($this->db->last_query());
                            }
                        }
                    }
                    else {
                        // matiHere("update subdetil biaya pos ervice");
                        //dimatiin karena bisa tanpa sub detail item
                        // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                    }
                    //endregion
                }
                else {
                    cekMerah("tidak tulis subdetail broo");
                }
                // matiHEre("tulis subdetail broo ".__LINE__);
                //endregion


                //
                //region nulis paymentSource
                //                $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
                $stepCode = $configUiMasterModulJenis['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_source");
                if (array_key_exists($stepCode, $paymentSources)) {

                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                                "valas_id" => isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                                "valas_nama" => isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                                "valas_nilai" => isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                                "tagihan_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                                "terbayar_valas" => 0,
                                "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                            ));
                        }
                    }


                    //cekMerah($this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion


                //region nulis paymentAntiSource
                $stepCode = $configUiMasterModulJenis['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_antiSource");
                if (array_key_exists($stepCode, $paymentSources)) {
                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentAntiSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                            ));
                        }
                    }


                    //cekMerah($this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion


                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;

                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "id_master" => $masterID,
                    "id_top" => $insertID,

                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");

                //                if($seluruhnya){
                //                    $dupState = $tr->updateData(array("id" => $insertID), array(
                //                        "tail_number" => $nextStepNum,
                //                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                //
                //                    )) or die("Failed to update trans tail!");
                //                }
                //cekHijau($this->db->last_query());


                $baseRegistries = array(
                    'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                    'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                    'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                    'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                    'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                    'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                    'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),

                    'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                    'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                    'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                    'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),

                    'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                    'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                    'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                    'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                    'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                    'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                    'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                    'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                    'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                    'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                    'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                    'rsltItems3_sub' => isset($_SESSION[$cCode]['rsltItems3_sub']) ? $_SESSION[$cCode]['rsltItems3_sub'] : array(),

                    'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                    'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                    'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                    'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                    'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                    'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                    'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                    'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                    'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                    'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                    'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                    'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                    'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                    'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    "receiptDetailFields" => isset($configLayoutMasterModulJenis['receiptDetailFields'][1]) ? $configLayoutMasterModulJenis['receiptDetailFields'][1] : array(),
                    "receiptSumFields" => isset($configLayoutMasterModulJenis['receiptSumFields'][1]) ? $configLayoutMasterModulJenis['receiptSumFields'][1] : array(),
                    "receiptDetailFields2" => isset($configLayoutMasterModulJenis['receiptDetailFields2'][1]) ? $configLayoutMasterModulJenis['receiptDetailFields2'][1] : array(),
                    "receiptSumFields2" => isset($configLayoutMasterModulJenis['receiptSumFields2'][1]) ? $configLayoutMasterModulJenis['receiptSumFields2'][1] : array(),
                    "receiptDetailSrcFields" => isset($configLayoutMasterModulJenis['receiptDetailSrcFields'][1]) ? $configLayoutMasterModulJenis['receiptDetailSrcFields'][1] : array(),
                    "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                    "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                    "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                    "jurnal_index" => isset($_SESSION[$cCode]['jurnal_index']) ? $_SESSION[$cCode]['jurnal_index'] : array(),
                    "postProcessor" => isset($_SESSION[$cCode]['postProcessor']) ? $_SESSION[$cCode]['postProcessor'] : array(),
                    "preProcessor" => isset($_SESSION[$cCode]['preProcessor']) ? $_SESSION[$cCode]['preProcessor'] : array(),
                    "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),

                );
                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                $mongRegIDConnect = $doWriteReg;
                showLast_query("ungu");
                //endregion

                //==================================================================================================
                //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
                $this->load->model("Mdls/MdlLockerTransaksi");
                $lt = New MdlLockerTransaksi();
                $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], NULL, $insertID);
                //                mati_disini();
                //==================================================================================================
            }
            else {
                cekMerah("to be delayed to connect to $connector");
            }
        }
        else {
            //cekKuning("not connecting to any tCode");
        }
        // matiHEre(__LINE__);
        //endregion


        //region extConnecting
        // triger dari items contoh produk komposit yang perlu direpack dipusat sebelum di distribusi
        $extConnecting = isset($this->configUi[$this->jenisTr]['extConnectTo']) ? $this->configUi[$this->jenisTr]['extConnectTo'] : array();
        // arrPrint($extConnecting);
        // matiHere();
        if (isset($extConnecting[$stepNum]) && sizeof($extConnecting[$stepNum]) > 0) {
            // $connector = $extConnecting


            $oldCode = $cCode;
            $connector = $extConnecting[$stepNum]['connecTo'];
            $configUiMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiUi");
            $configCoreMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiCore");
            $configLayoutMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiLayout");
            // arrPrint($configUiMasterModulJenis);
            // matiHere();
            $this->load->Model("Mdls/MdlProdukKomposit");
            $this->load->Model("Mdls/MdlProdukKompositKomposisi");
            $pk = new MdlProdukKomposit();
            $ck = new MdlProdukKompositKomposisi();
            $tempProdukKomposit = $pk->lookUpAll()->result();
            $produkKomposit = array();
            $idProdukKomposit = array();
            $komposisiKomposit = array();
            if (sizeof($tempProdukKomposit) > 0) {
                foreach ($tempProdukKomposit as $kIndex => $kData) {
                    if (isset($_SESSION[$cCode]["items"][$kData->id])) {
                        $produkKomposit[$kData->id] = $_SESSION[$cCode]["items"][$kData->id];
                        $idProdukKomposit[] = $kData->id;
                        $requiredParamKomposit[$kData->id] = array("jml" => $_SESSION[$cCode]["items"][$kData->id]["jml"]);
                    }
                }

            }
            // arrPRint($requiredParamKomposit);
            // matiHEre();
            if (sizeof($produkKomposit) > 0) {
                $ck->addFilter("produk_id in (" . implode(",", $idProdukKomposit) . ")");
                $tmpProdukKompositKomposisi = $ck->lookUpAll_res();
                if (sizeof($tmpProdukKompositKomposisi) > 0) {
                    foreach ($tmpProdukKompositKomposisi as $prID => $tmpProdukKompositKomposisi_0) {
                        $ix = 0;
                        foreach ($tmpProdukKompositKomposisi_0 as $tData) {
                            $ix++;
                            $komposisiKomposit[$prID]["produk"][$ix] = $tData;
                        }
                    }
                }
            }
            $intems2Komposit = array();
            $detil2Sum = array();
            if (sizeof($requiredParamKomposit)) {
                foreach ($requiredParamKomposit as $pid => $pidData) {
                    if (isset($komposisiKomposit[$pid])) {
                        $iex = 0;
                        foreach ($komposisiKomposit[$pid]["produk"] as $iExtID => $extData) {
                            $iex++;
                            $intems2Komposit[$pid]["produk"][$iex] = array(
                                "id" => $extData->produk_dasar_id,
                                "nama" => $extData->produk_dasar_nama,
                                "name" => $extData->produk_dasar_nama,
                                "satuan" => $extData->satuan_nama,
                                "jenis" => $extData->jenis,
                                "jml" => $extData->jml * $pidData["jml"],
                            );
                            $detil2Sum[$extData->produk_dasar_id][] = array(
                                "id" => $extData->produk_dasar_id,
                                "nama" => $extData->produk_dasar_nama,
                                "name" => $extData->produk_dasar_nama,
                                "satuan" => $extData->satuan_nama,
                                "jenis" => $extData->jenis,
                                "jml" => $extData->jml * $pidData["jml"],
                            );
                            // $intemsKomposit
                        }
                    }
                }

                foreach ($_SESSION[$cCode]["items"] as $pID => $iSPec) {
                    if (!isset($requiredParamKomposit[$pID])) {
                        unset($_SESSION[$cCode]['tableIn_detail'][$pID]);
                        unset($_SESSION[$cCode]['tableIn_detail_values'][$pID]);
                    }
                }
            }
            $intems2_sumKomposit = array();
            if (sizeof($detil2Sum) > 0) {
                $srcFieldsExt = $configUiMasterModulJenis[$connector]["shoppingCartFields"]["1"];
                foreach ($detil2Sum as $PID => $dataKomposit) {
                    $jmlNeed = 0;
                    foreach ($dataKomposit as $iiD => $tmpData_komposit) {
                        // arrPrint($tmpData_komposit);
                        $jmlNeed += $tmpData_komposit['jml'];
                        $intems2_sumKomposit[$PID] = array(
                            "handler" => "",
                            "id" => $tmpData_komposit['id'],
                            "nama" => $tmpData_komposit['nama'],
                            "name" => $tmpData_komposit['name'],
                            "satuan" => $tmpData_komposit['satuan'],
                            "jenis" => $tmpData_komposit['jenis'],
                            "jml" => $jmlNeed,
                        );
                    }
                }

            }
            // matiHEre(__LINE__);
            // $steps = isset($configUiMasterModulJenis[$origJenis]['steps']) ? $configUiMasterModulJenis[$origJenis]['steps'] : array();
            if (isset($extConnecting[$stepNum]['connecTo']) && (sizeof($produkKomposit) > 0)) {

                cekMerah("NOW CONNECTING to $connector");
                //                 arrPrint($configUiMasterModulJenis);
                // matiHEre();
                if (sizeof($configCoreMasterModulJenis) < 1) {
                    mati_disini("kode connector tidak dikenali!");
                }
                else {
                    cekHijau("kode connector dikenali, lanjutkan...");
                }
                if (sizeof($configUiMasterModulJenis['steps']) < 2) {
                    die("konfigurasi connector harus memiliki step lebih dari satu!");
                }


                $cCode = "_TR_" . $connector;

                $_SESSION[$cCode] = array();

                // matiHere($cCode . " LINE --:::" . __LINE__);
                $_SESSION[$cCode] = array(
                    "main" => $_SESSION[$oldCode]['main'],
                    "items" => $produkKomposit,
                    "items_komposisi" => $komposisiKomposit,
                    "items2" => $intems2Komposit,
                    "items2_sum" => $intems2_sumKomposit,
                    "items3" => array(),
                    "items3_sum" => array(),
                    "items4_sum" => array(),
                    "items_noapprove" => array(),

                    "tableIn_master" => $_SESSION[$oldCode]['tableIn_master'],
                    "tableIn_detail" => $_SESSION[$oldCode]['tableIn_detail'],
                    //
                    "rsltItems" => $_SESSION[$oldCode]['rsltItems'],
                    "tableIn_detail_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_rsltItems'],
                    //
                    "tableIn_master_values" => $_SESSION[$oldCode]['tableIn_master_values'],
                    "tableIn_detail_values" => $_SESSION[$oldCode]['tableIn_detail_values'],
                    "tableIn_detail_values_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'],
                );

                //                    print_r($_SESSION[$cCode]);die();

                //==replace pertama
                $masterReplacersO = array(
                    "jenisTr" => $connector,
                    "jenisTrMaster" => $connector,
                    "jenisTrTop" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis_label" => $configUiMasterModulJenis['steps'][1]['label'],
                    "transaksi_jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "stepCode" => $configUiMasterModulJenis['steps'][1]['target'],
                    "placeID" => isset($preReplacer['place2ID']) ? $preReplacer['place2ID'] : $_SESSION[$cCode]['main']['place2ID'],
                    "placeName" => isset($preReplacer['place2Name']) ? $preReplacer['place2Name'] : $_SESSION[$cCode]['main']['place2Name'],
                    "place2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "place2Name" => $_SESSION[$cCode]['main']['placeName'],
                    "cabangID" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$cCode]['main']['place2ID'],
                    "cabangName" => isset($preReplacer['place2Name']) ? $preReplacer['place2Name'] : $_SESSION[$cCode]['main']['place2Name'],
                    "cabang2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "cabang2Name" => $_SESSION[$cCode]['main']['placeName'],
                    //
                    "gudang2ID" => $_SESSION[$cCode]['main']['gudangID'],
                    "gudang2Name" => $_SESSION[$cCode]['main']['gudangName'],
                    "gudangID" => isset($preReplacer['gudang2ID']) ? $preReplacer['gudang2ID'] : $_SESSION[$cCode]['main']['gudang2ID'],
                    "gudangName" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$cCode]['main']['gudang2Name'],
                    "pihakID" => isset($_SESSION[$cCode]['main']['placeID']) ? $_SESSION[$cCode]['main']['placeID'] : "",
                    "pihakName" => isset($_SESSION[$cCode]['main']['placeName']) ? $_SESSION[$cCode]['main']['placeName'] : "",
                    "pihakName2" => $_SESSION[$cCode]['main']['placeName'],
                    "gudang" => $_SESSION[$cCode]['main']['gudangID'],
                    "gudang__name" => $_SESSION[$cCode]['main']['gudangName'],
                    "gudang__label" => $_SESSION[$cCode]['main']['gudangName'],
                    "efaktur_source" => isset($preReplacer['efaktur_source']) ? $_SESSION[$cCode]['main']['nomer'] : "",

                );
                foreach ($masterReplacersO as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    //                    $_SESSION[$cCode]['main'][$key] = $val;
                }
                $masterReplacers = array(
                    //                    "referensi_id" => $masterID, (dimatikan)
                    "inv" => $tmpNomorNota,
                    "jenis_master" => $connector,
                    "jenis_top" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "jenis_label" => $configUiMasterModulJenis['steps'][1]['label'],
                    "transaksi_jenis" => $configUiMasterModulJenis['steps'][1]['target'],
                    "cabang_id" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$cCode]['tableIn_master']['cabang2_id'],
                    "cabang_nama" => isset($preReplacer['cabang2Name']) ? $preReplacer['cabang2Name'] : $_SESSION[$cCode]['tableIn_master']['cabang2_nama'],
                    "cabang2_id" => $_SESSION[$cCode]['tableIn_master']['cabang_id'],
                    "cabang2_nama" => $_SESSION[$cCode]['tableIn_master']['cabang_nama'],
                    "gudang_id" => isset($preReplacer['gudang2ID']) ? $preReplacer['gudang2ID'] : $_SESSION[$cCode]['tableIn_master']['gudang2_id'],
                    "gudang_nama" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$cCode]['tableIn_master']['gudang2_nama'],
                    "gudang2_id" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                    "gudang2_nama" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                    "gudang" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                    "gudang__name" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                    "gudang__label" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],

                    "step_avail" => sizeof($configUiMasterModulJenis['steps']),
                    "step_current" => 1,
                    "step_number" => 1,
                    "next_step_code" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['target'] : "",
                    "next_step_label" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['label'] : "",
                    "next_group_code" => isset($configUiMasterModulJenis['steps'][2]) ? $configUiMasterModulJenis['steps'][2]['userGroup'] : "",
                    "next_step_num" => isset($configUiMasterModulJenis['steps'][2]) ? 2 : "0",
                    "efaktur_source" => isset($preReplacer['efaktur_source']) ? $_SESSION[$cCode]['main']['nomer'] : "",
                    //===references
                    //                    "id_master"            => $masterID,
                    //                    "id_top"               => $topID,
                    //                    "ids_prev"             => base64_encode(serialize(array($prevProp['id']))),
                    //                    "ids_prev_intext"      => print_r(array($prevProp['id'], true)),
                    //                    "nomer_top"            => $_SESSION[$cCode]['main']['nomer'],
                    //                    "nomers_prev"          => base64_encode(serialize(array($prevProp['nomer']))),
                    //                    "nomers_prev_intext"   => print_r(array($prevProp['nomer'], true)),
                    //                    "jenis_top"            => $this->jenisTr,
                    //                    "jenises_prev"        => base64_encode(serialize(array($prevProp['jenis']))),
                    //                    "jenises_prev_intext" => print_r(array($prevProp['jenis'], true)),
                );

                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }


                //region penomoran receipt #2
                //<editor-fold desc="==========penomoran">
                $this->load->model("CustomCounter");
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);

                $counterForNumber = array($configCoreMasterModulJenis['formatNota']);
                if (!in_array($counterForNumber[0], $configCoreMasterModulJenis['counters'])) {
                    die(__LINE__ . " Used number should be registered in 'counters' config as well");
                }

                foreach ($counterForNumber as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        //                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                }

                $tmpNomorNota2 = $paramSpec['paramString'];
                $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);


                //</editor-fold>
                //endregion

                //region dynamic counters #2
                // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);
                $configCustomParams = $configCoreMasterModulJenis['counters'];
                $configCustomParams[] = "stepCode";
                if (sizeof($configCustomParams) > 0) {
                    $cContent = array();
                    foreach ($configCustomParams as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                        switch ($paramSpec['id']) {
                            case 0: //===counter type is new
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                break;
                        }
                        //echo "<hr>";
                    }
                }
                $appliedCounters2 = base64_encode(serialize($cContent));
                $appliedCounters_inText2 = print_r($cContent, true);
                // </editor-fold>
                //endregion

                //region numbering tambahan
                $this->load->library("CounterNumber");
                $ccn = new CounterNumber();
                $ccn->setCCode($cCode);
                $ccn->setJenisTr($connector);
                $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
                $ccn->setMainGate($_SESSION[$cCode]['main']);
                $ccn->setItemsGate($_SESSION[$cCode]['items']);
                $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
                $new_counter = $ccn->getCounterNumber();
                cekHitam("jenistr yang disett dari create " . $this->jenisTr);

                if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
                    foreach ($new_counter['main'] as $ckey => $cval) {
                        $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                        $_SESSION[$cCode]['main'][$ckey] = $cval;
                    }
                }
                if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
                    foreach ($new_counter['items'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
                    foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                //endregion
                $addValues = array(
                    'counters' => $appliedCounters2,
                    'counters_intext' => $appliedCounters_inText2,
                    'nomer' => $tmpNomorNota,
                    'dtime' => date("Y-m-d H:i:s"),
                    'fulldate' => date("Y-m-d"),
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning nota cab1 ke cab2
                //===daftar perbedaan
                //== referensi_id, inv, jenis, nomer, counters, counters_inText, cabang_id, cabang_nama, cabang2_id, cabang2_nama,

                //==replace kedua
                $masterReplacers = array(
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning detail/items cabang1 ke cabang2
                //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code
                $detailReplacers = array(
                    "sub_step_avail" => sizeof($configUiMasterModulJenis[$connector]['steps']),
                    "sub_step_current" => 1,
                    "sub_step_number" => 1,
                    "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                    "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                    "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                    "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                    //                    "next_substep_code" => isset($configUiMasterModulJenis[$connector]['steps'][2]) ? $configUiMasterModulJenis[$connector]['steps'][2]['target'] : "",
                    //                    "next_substep_label" => isset($configUiMasterModulJenis[$connector]['steps'][2]) ? $configUiMasterModulJenis[$connector]['steps'][2]['label'] : "",
                    //                    "next_subgroup_code" => isset($configUiMasterModulJenis[$connector]['steps'][2]) ? $configUiMasterModulJenis[$connector]['steps'][2]['userGroup'] : "",
                );
                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    //                    cekmerah("tulis rincian transaksi kedua");
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                        foreach ($dSpec as $key => $val) {
                            $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                        }
                    }
                }
                else {
                    //                    cekmerah("GAGAL tulis rincian transaksi kedua");
                }


                //region ----------write transaksi & transaksi_data #2
                if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                    $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                    $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                    cekUngu($this->db->last_query());
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                    $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                    $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                    $mongoListConnect['main'] = array($insertID, $epID);
                    cekmerah("tulis transaksi kedua :: trID $insertID");
                    cekmerah($this->db->last_query());
                    if ($insertID < 1) {
                        die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                }
                else {
                    cekmerah("GAGAL tulis transaksi kedua");
                }

                if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                    $inserMainValues = array();
                    foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                    if (sizeof($inserMainValues) > 0) {
                        $arrBlob = blobEncode($inserMainValues);
                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                    }
                }


                if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                    foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }
                if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                    foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }

                if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                    //                    cekMerah("ada mainElements");
                    foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => $aSpec['label'],
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                        ));
                    }
                }


                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoListConnect['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                $mongoListConnect['detail'][] = $insertEpID;
                            }
                        }
                    }
                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                            cekOrange($this->db->last_query());
                        }
                    }
                }

                if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                        $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                        $mongoListConnect['detail'] = $insertIDs;
                        if ($epID != 999) {
                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                            $mongoListConnect['detail'] = $mongoListConnect['detail'] = $insertIDs;;
                        }
                    }
                }

                if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                        if (isset($configCoreMasterModulJenis[$this->jenisTr]['tableIn']['detailValues'])) {
                            foreach ($configCoreMasterModulJenis[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                //                                $insertIDs[$pID][] = $tr->writeDetailValues($insertID, array(
                                //                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                //                                    "produk_id" => $pID,
                                //                                    "key" => $key,
                                //                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                                //                                ));
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                                ));
                                $insertIDs[] = $dd;
                                $mongoListConnect['detailValues'][] = $dd;

                            }
                        }
                    }
                    if (sizeof($insertIDs) > 0) {
                        $arrBlob = blobEncode($insertIDs);
                        $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                    }
                }


                if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                        if (isset($configCoreMasterModulJenis[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                            foreach ($configCoreMasterModulJenis[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                $insertIDs[] = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));

                            }
                        }
                    }
                }

                //
                //region nulis paymentSource
                //                $stepCode = $configUiMasterModulJenis[$this->jenisTr]['steps'][1]['target'];
                $stepCode = $configUiMasterModulJenis['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_source");
                if (array_key_exists($stepCode, $paymentSources)) {

                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                                "valas_id" => isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                                "valas_nama" => isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                                "valas_nilai" => isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                                "tagihan_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                                "terbayar_valas" => 0,
                                "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                            ));
                        }
                    }


                    //cekMerah($this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion


                //region nulis paymentAntiSource
                //                $stepCode = $configUiMasterModulJenis[$this->jenisTr]['steps'][1]['target'];
                $stepCode = $configUiMasterModulJenis['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_antiSource");
                if (array_key_exists($stepCode, $paymentSources)) {
                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentAntiSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                            ));
                        }
                    }


                    //cekMerah($this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion


                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;

                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "id_master" => $masterID,
                    "id_top" => $insertID,

                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");

                //                if($seluruhnya){
                //                    $dupState = $tr->updateData(array("id" => $insertID), array(
                //                        "tail_number" => $nextStepNum,
                //                        "tail_code" => $configUiMasterModulJenis[$this->jenisTr]['steps'][$nextStepNum]['target'],
                //
                //                    )) or die("Failed to update trans tail!");
                //                }
                //cekHijau($this->db->last_query());


                $baseRegistries = array(
                    'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                    'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                    'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                    'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                    'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                    'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                    'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                    'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                    'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                    'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                    'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                    'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                    'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                    'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),

                    'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                    'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                    'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                    'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                    'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                    'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                    'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                    'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                    'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                    'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                    'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                    'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                    'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                    'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    "receiptDetailFields" => isset($configLayoutMasterModulJenis['receiptDetailFields'][1]) ? $configLayoutMasterModulJenis['receiptDetailFields'][1] : array(),
                    "receiptSumFields" => isset($configLayoutMasterModulJenis['receiptSumFields'][1]) ? $configLayoutMasterModulJenis['receiptSumFields'][1] : array(),
                    "receiptDetailFields2" => isset($configLayoutMasterModulJenis['receiptDetailFields2'][1]) ? $configLayoutMasterModulJenis['receiptDetailFields2'][1] : array(),
                    "receiptSumFields2" => isset($configLayoutMasterModulJenis['receiptSumFields2'][1]) ? $configLayoutMasterModulJenis['receiptSumFields2'][1] : array(),
                    "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                );
                // arrPrint($baseRegistries);
                // matiHere();
                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                cekMerah($this->db->last_query());
                $mongRegIDConnect = $doWriteReg;
                //endregion


                //==================================================================================================
                //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
                $this->load->model("Mdls/MdlLockerTransaksi");
                $lt = New MdlLockerTransaksi();
                $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], NULL, $insertID);
                //                mati_disini();
                //==================================================================================================


            }
            else {
                cekMerah("no data ext to conected");
            }

            // matiHEre($connector);
            // arrPrint($_SESSION[$cCode]["items"]);
            // arrPrint($produkKomposit);


        }
        // arrPrint($komposisiKomposit);
        // matiHEre(__LINE__ . " cek extConnectig antar cabang");
        //endregion


        //region check stoc produk

        //        $stopdulu=false;
        //        if(!$stopdulu){

        $trr = new MdlTransaksi();
        $trr->setFilters(array());
        $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        //        $trr->addFilter("param='main'");
        $trr->setJointSelectFields("main");
        $tmpReg = $trr->lookupDataRegistries()->result();

        $origRequest = array();
        $stockActive = array();
        $pushToRequestPO = array();
        $pushToDisribution = array();

        $totalUnitToPush = 0;
        if (isset($this->configUi[$this->jenisTr]['pushPurchas'][$stepNum])) {

            if (sizeof($tmpTr) > 0) {
                $items = array();
                $trIDs = array();
                $lastTRID = 0;
                $cabang2_id = array();
                $gudang2_id = array();
                foreach ($tmpTr as $row) {
                    $cabang2_id[$row->produk_id] = $row->cabang2_id;
                    $gudang2_id[$row->produk_id] = $row->gudang2_id;
                    if (!array_key_exists($row->produk_id, $items)) {
                        $items[$row->produk_id] = 0;
                    }
                    $items[$row->produk_id] += $row->valid_qty;
                    if (!in_array($row->id_master, $trIDs)) {
                        $trIDs[] = $row->id_master;
                    }
                    $lastTRID = $row->transaksi_id;
                }
                if (sizeof($tmpReg) > 0) {
                    $oldMain = unserialize(base64_decode($tmpReg[0]->values));
                }
                $targetProc = base_url() . $this->configUi[$this->jenisTr]['itemSwapper'] . "/$this->jenisTr/?items=" . base64_encode(serialize($items)) . "&main=" . base64_encode(serialize($oldMain)) . "&trs=" . base64_encode(serialize($trIDs));
                $lockerConfig = isset($this->configUi[$this->jenisTr]['lockerCheckAppr']) ? $this->configUi[$this->jenisTr]['lockerCheckAppr'] : array();
                $selectorModel = $this->configUi[$this->jenisTr]['selectorModel'];
                $selectorSrcModel = $this->configUi[$this->jenisTr]['selectorSrcModel'];
                $this->load->model("Mdls/" . $selectorSrcModel);
                $b = new $selectorSrcModel();
                $arrItems = isset($items) ? $items : array();
                $arrTrID = isset($trIDs) ? $trIDs : array();
                $arrMain = isset($oldMain) ? $oldMain : array();

                if (sizeof($arrItems) > 0) {

                    foreach ($arrItems as $id => $jmlParam) {
                        $tmpB = $b->lookupByID($id)->result();
                        $jml = $jmlParam;//jumlah dari request

                        if (!isset($origRequest[$id])) {
                            $origRequest[$id] = $jml;
                        }
                        if (!isset($pushToRequestPO[$id])) {
                            $pushToRequestPO[$id] = 0;
                        }
                        if (!isset($pushToDisribution[$id])) {
                            $pushToDisribution[$id] = 0;
                        }

                        if (sizeof($tmpB) > 0) {
                            foreach ($tmpB as $row) {
                                cekHitam("####BEGIN####");
                                if (isset($lockerConfig['enabled']) && $lockerConfig['enabled'] == true) {
                                    cekMerah("masuk locker config");
                                    $mdlName = $lockerConfig['mdlName'];
                                    $this->load->model("Mdls/" . $mdlName);
                                    $c = new $mdlName();
                                    $c->addFilter("produk_id='$id'");
                                    $c->addFilter("state='active'");
                                    $c->addFilter("cabang_id=" . $cabang2_id[$id]);
                                    $c->addFilter("gudang_id=" . $gudang2_id[$id]);
                                    $tmpC = $c->lookupAll($id)->result();
                                    cekHere($this->db->last_query());

                                    if (sizeof($tmpC) > 0) {

                                        foreach ($tmpC as $row) {
                                            $satuan = strlen($row->satuan) > 0 ? $row->satuan : "n/a";
                                            $nama = $row->nama;

                                            $jml_now = $row->jumlah;//jumlah dari stocklocker
                                            $stockActive[$id] = $row->jumlah;
                                            if (!array_key_exists($id, $_SESSION[$cCode]['items'])) {
                                                $jml_sudah_diambil = 0;
                                                $jml_diperlukan = $jml_now > $jmlParam ? $jmlParam : $jml_now;
                                                $jml_nambah = $jml_now > $jmlParam ? $jmlParam : $jml_now;
                                            }
                                            else {
                                                if (isset($_GET['newQty'])) {
                                                    $jml_sudah_diambil = $_SESSION[$cCode]['items'][$id]['jml'];
                                                    $jml_diperlukan = $_GET['newQty'];
                                                    $jml_nambah = $jml_diperlukan - $jml_sudah_diambil;
                                                }
                                                else {
                                                    $jml_sudah_diambil = $_SESSION[$cCode]['items'][$id]['jml'];
                                                    $jml_diperlukan = $jml_sudah_diambil + $jml;
                                                    $jml_nambah = $jml_now > $jml ? $jml : $jml_now;
                                                }
                                            }
                                            //  region validasi stok
                                            //  jml=jml direq || jml_now=jml yg active di locker

                                            if ($jml > $jml_now) {
                                                //                                                echo "<script>top.alert('stok $nama tidak cukup. (perlu $jmlParam, nambah $jml_nambah stok $jml_now)')";
                                                //                                                echo "</script>";
                                                $pushToRequestPO[$id] = $jml - $jml_now;
                                                $pushToDisribution[$id] = $jml_now;
                                                $totalUnitToPush += $jml - $jml_now;
                                            }
                                            else {
                                                $pushToDisribution[$id] = $jml;
                                            }


                                            //  endregion validasi stok
                                            //                                            $this->db->trans_start();
                                            //  region update locker active

                                            $where = array(
                                                "id" => $row->id,
                                            );
                                            $data_active = array(
                                                "jumlah" => $jml_now - $jml_nambah,
                                                "state" => "active",
                                            );
                                            //                                            $c->updateData($where, $data_active);
                                            //                                            cekHere($this->db->last_query());
                                            //  endregion update locker active

                                            //  region locker hold
                                            //                                            $array_hold_sebelumnya = $c->cekLoker($this->session->login['cabang_id'], $id, "hold", $this->session->login['id'], "0", $this->session->login['gudang_id']);
                                            $array_hold_sebelumnya = $c->cekLoker($cabang2_id[$id], $id, "hold", $this->session->login['id'], "0", $gudang2_id[$id]);
                                            if (sizeof($array_hold_sebelumnya) > 0) {
                                                $where = array(
                                                    "id" => $array_hold_sebelumnya['id'],
                                                );
                                                $data_hold = array(
                                                    "jumlah" => $array_hold_sebelumnya['jumlah'] + $jml_nambah,
                                                );
                                                //                                                $c->updateData($where, $data_hold);
                                                //                                                cekHere($this->db->last_query());
                                            }
                                            else {
                                                $data_hold = array(
                                                    "jenis" => "supplies",
                                                    "cabang_id" => $cabang2_id[$id],
                                                    "produk_id" => $id,
                                                    "nama" => $nama,
                                                    "satuan" => $row->satuan,
                                                    "state" => "hold",
                                                    "jumlah" => $jml_nambah,
                                                    "oleh_id" => $this->session->login['id'],
                                                    "oleh_nama" => $this->session->login['nama'],
                                                    "gudang_id" => $gudang2_id[$id],
                                                );
                                                //                                                $c->addData($data_hold);
                                                //                                                cekHere($this->db->last_query());
                                            }

                                            //  endregion locker hold
                                            //  $this->db->trans_complete() or die("Gagal bro");

                                            $tmpJml = $jml_diperlukan;

                                        }
                                        //                                        arrPrint($tmpC);
                                    }
                                    else {
                                        //                                        mati_disini("tidak ditemukan item " . $row->nama . " di locker stock.");
                                        $pushToRequestPO[$id] = $jml;
                                        $totalUnitToPush += $jml;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        //endregion check stock produk

        //region connecting connectToPrePurchase
        $mongPrePurcash = array();
        $mongPrePurcashReg = array();
        if ($totalUnitToPush > 0) {

            cekMerah("total Unit To Push: $totalUnitToPush || ada yg akan masuk purchase...!");
            //cekMerah("//cek connecting dari $origJenis========================================");
            $steps = isset($this->configUi[$origJenis]['steps']) ? $this->configUi[$origJenis]['steps'] : array();
            $connector = isset($this->configUi[$origJenis]['connectToPrePurchase']) ? $this->configUi[$origJenis]['connectToPrePurchase'] : "";

            if (strlen($connector) > 0) {
                cekMerah("to be connected to $connector");
                if ($stepNum == sizeof($steps)) {
                    cekMerah("now connecting to $connector");
                    if (!array_key_exists($connector, $this->configUi)) {
                        die("kode connector tidak dikenali!");
                    }
                    if (sizeof($this->configUi[$connector]['steps']) < 2) {
                        die("konfigurasi connector harus memiliki step lebih dari satu!");
                    }

                    $oldCode = $cCode;
                    $cCode = "_TR_" . $connector;

                    $_SESSION[$cCode] = array();
                    $_SESSION[$cCode] = array(
                        "main" => $_SESSION[$oldCode]['main'],
                        "items" => $_SESSION[$oldCode]['items'],
                        "tableIn_master" => $_SESSION[$oldCode]['tableIn_master'],
                        "tableIn_detail" => $_SESSION[$oldCode]['tableIn_detail'],
                        "rsltItems" => $_SESSION[$oldCode]['rsltItems'],
                        //                    "out_detail_rsltItems" => $_SESSION[$oldCode]['out_detail_rsltItems'],
                        "tableIn_detail_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_rsltItems'],
                        "tableIn_master_values" => $_SESSION[$oldCode]['tableIn_master_values'],
                        "tableIn_detail_values" => $_SESSION[$oldCode]['tableIn_detail_values'],
                        "tableIn_detail_values_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'],
                    );

                    //==replace pertama
                    $masterReplacersO = array(
                        "jenisTr" => $connector,
                        "jenisTrMaster" => $connector,
                        "jenisTrTop" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                        "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "stepCode" => $this->configUi[$connector]['steps'][1]['target'],
                        "placeID" => $_SESSION[$cCode]['main']['placeID'],
                        "placeName" => $_SESSION[$cCode]['main']['placeName'],
                        "place2ID" => $_SESSION[$cCode]['main']['place2ID'],
                        "place2Name" => $_SESSION[$cCode]['main']['place2Name'],
                        "cabangID" => $_SESSION[$cCode]['main']['placeID'],
                        "cabangName" => $_SESSION[$cCode]['main']['placeName'],
                        "cabang2ID" => $_SESSION[$cCode]['main']['place2ID'],
                        "cabang2Name" => $_SESSION[$cCode]['main']['place2Name'],
                        "gudang2ID" => $_SESSION[$cCode]['main']['gudang2ID'],
                        "gudang2Name" => $_SESSION[$cCode]['main']['gudang2Name'],
                        "gudangID" => $_SESSION[$cCode]['main']['gudangID'],
                        "gudangName" => $_SESSION[$cCode]['main']['gudangName'],
                        "pihakID" => "",
                        "pihakName" => "",
                        "pihakName2" => "",
                        "gudang" => "",
                        "gudang__name" => "",
                        "gudang__label" => "",

                    );
                    //                arrPrint($masterReplacersO);
                    //                matiHere();
                    foreach ($masterReplacersO as $key => $val) {
                        $_SESSION[$cCode]['main'][$key] = $val;
                    }

                    //                arrPrint($_SESSION[$cCode]['main']);
                    //                matiHere();
                    $masterReplacers = array(
                        //                    "referensi_id" => $masterID, (dimatikan)
                        "inv" => $tmpNomorNota,
                        "jenis_master" => $connector,
                        "jenis_top" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                        "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "cabang_id" => $_SESSION[$cCode]['tableIn_master']['cabang_id'],
                        "cabang_nama" => $_SESSION[$cCode]['tableIn_master']['cabang_nama'],
                        "cabang2_id" => $_SESSION[$cCode]['tableIn_master']['cabang2_id'],
                        "cabang2_nama" => $_SESSION[$cCode]['tableIn_master']['cabang2_nama'],
                        "gudang_id" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                        "gudang_nama" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                        "gudang2_id" => $_SESSION[$cCode]['tableIn_master']['gudang2_id'],
                        "gudang2_nama" => $_SESSION[$cCode]['tableIn_master']['gudang2_nama'],
                        "gudang" => "",
                        "gudang__name" => "",
                        "gudang__label" => "",

                        "step_avail" => sizeof($this->configUi[$connector]['steps']),
                        "step_current" => 1,
                        "step_number" => 1,
                        "next_step_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['target'] : "",
                        "next_step_label" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['label'] : "",
                        "next_group_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['userGroup'] : "",
                        "next_step_num" => isset($this->configUi[$connector]['steps'][2]) ? 2 : "0",
                        //===references
                        //                    "id_master"            => $masterID,
                        //                    "id_top"               => $topID,
                        //                    "ids_prev"             => base64_encode(serialize(array($prevProp['id']))),
                        //                    "ids_prev_intext"      => print_r(array($prevProp['id'], true)),
                        //                    "nomer_top"            => $_SESSION[$cCode]['main']['nomer'],
                        //                    "nomers_prev"          => base64_encode(serialize(array($prevProp['nomer']))),
                        //                    "nomers_prev_intext"   => print_r(array($prevProp['nomer'], true)),
                        //                    "jenis_top"            => $this->jenisTr,
                        //                    "jenises_prev"        => base64_encode(serialize(array($prevProp['jenis']))),
                        //                    "jenises_prev_intext" => print_r(array($prevProp['jenis'], true)),
                    );
                    //                arrPrint($masterReplacers);
                    //                matiHere();
                    foreach ($masterReplacers as $key => $val) {
                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                    }

                    //region penomoran receipt #2
                    //<editor-fold desc="==========penomoran">
                    $this->load->model("CustomCounter");
                    $cn = new CustomCounter("transaksi");
                    $cn->setType("transaksi");
                    $cn->setModul($this->modul);
                    $cn->setStepCode($jenisTrTarget);

                    $counterForNumber = array($this->configCore[$connector]['formatNota']);
                    arrPrint($counterForNumber);
                    arrPrint($connector);
                    if (!in_array($counterForNumber[0], $this->configCore[$connector]['counters'])) {
                        die(__LINE__ . " Used number should be registered in 'counters' config as well");
                    }

                    foreach ($counterForNumber as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            //                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                    }

                    $tmpNomorNota2 = $paramSpec['paramString'];
                    $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);

                    //</editor-fold>
                    //endregion

                    //region dynamic counters #2
                    // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                    $cn = new CustomCounter("transaksi");
                    $cn->setType("transaksi");
                    $cn->setModul($this->modul);
                    $cn->setStepCode($jenisTrTarget);
                    $configCustomParams = $this->configCore[$connector]['counters'];
                    $configCustomParams[] = "stepCode";
                    if (sizeof($configCustomParams) > 0) {
                        $cContent = array();
                        foreach ($configCustomParams as $i => $cRawParams) {
                            $cParams = explode("|", $cRawParams);
                            $cValues = array();
                            foreach ($cParams as $param) {
                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            }
                            $cRawValues = implode("|", $cValues[$i]);
                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                            $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                            switch ($paramSpec['id']) {
                                case 0: //===counter type is new
                                    $paramKeyRaw = print_r($cParams, true);
                                    $paramValuesRaw = print_r($cValues[$i], true);
                                    $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                    break;
                                default: //===counter to be updated
                                    $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                    break;
                            }
                            //echo "<hr>";
                        }
                    }
                    $appliedCounters2 = base64_encode(serialize($cContent));
                    $appliedCounters_inText2 = print_r($cContent, true);
                    // </editor-fold>
                    //endregion

                    //region numbering tambahan
                    $this->load->library("CounterNumber");
                    $ccn = new CounterNumber();
                    $ccn->setCCode($cCode);
                    $ccn->setJenisTr($connector);
                    $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
                    $ccn->setMainGate($_SESSION[$cCode]['main']);
                    $ccn->setItemsGate($_SESSION[$cCode]['items']);
                    $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
                    $new_counter = $ccn->getCounterNumber();
                    cekHitam("jenistr yang disett dari create " . $this->jenisTr);

                    if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
                        foreach ($new_counter['main'] as $ckey => $cval) {
                            $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                            $_SESSION[$cCode]['main'][$ckey] = $cval;
                        }
                    }
                    if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
                        foreach ($new_counter['items'] as $ikey => $iSpec) {
                            foreach ($iSpec as $iikey => $iival) {
                                $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                            }
                        }
                    }
                    if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
                        foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                            foreach ($iSpec as $iikey => $iival) {
                                $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                            }
                        }
                    }
                    //endregion
                    $addValues = array(
                        'counters' => $appliedCounters2,
                        'counters_intext' => $appliedCounters_inText2,
                        'nomer' => $tmpNomorNota,
                        'dtime' => date("Y-m-d H:i:s"),
                        'fulldate' => date("Y-m-d"),
                    );
                    foreach ($addValues as $key => $val) {
                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                    }

                    //===cloning nota cab1 ke cab2
                    //===daftar perbedaan
                    //== referensi_id, inv, jenis, nomer, counters, counters_inText, cabang_id, cabang_nama, cabang2_id, cabang2_nama,

                    //==replace kedua
                    $masterReplacers = array(
                        "nomer" => $tmpNomorNota2,
                        "nomer2" => $tmpNomorNota2Alias,
                        "counters" => $appliedCounters2,
                        "counters_intext" => $appliedCounters_inText2,
                    );
                    foreach ($masterReplacers as $key => $val) {
                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                    }

                    //===cloning detail/items cabang1 ke cabang2
                    //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code

                    //                arrPrint($_SESSION[$cCode]['tableIn_detail']);

                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                            if (isset($pushToRequestPO)) {
                                foreach ($pushToRequestPO as $pid => $vals) {

                                    $detailReplacers[$pid] = array(
                                        "valid_qty" => $vals,
                                        "sub_step_avail" => sizeof($this->configUi[$connector]['steps']),
                                        "sub_step_current" => 1,
                                        "sub_step_number" => 1,
                                        "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                                        "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                                        "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                                        "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                                    );

                                    if ($vals > 0) {
                                        foreach ($dSpec as $key => $val) {
                                            if ($pid == $k) {
                                                $_SESSION[$cCode]['tableIn_detail'][$pid][$key] = isset($detailReplacers[$pid][$key]) ? $detailReplacers[$pid][$key] : $val;
                                                //                                            cekMerah("pid build: " . $pid);
                                            }
                                        }

                                    }
                                    else {
                                        foreach ($dSpec as $key => $val) {
                                            if ($pid == $k) {
                                                unset($_SESSION[$cCode]['tableIn_detail'][$pid]);
                                                //                                            cekMerah("pid delete: " . $pid);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //                    cekmerah("GAGAL tulis rincian transaksi kedua");
                    }
                    //region ----------write transaksi & transaksi_data #2
                    if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                        $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                        $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                        $tr = new MdlTransaksi();
                        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                        $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                        cekUngu(__LINE__ . " " . $this->db->last_query());
                        $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                        $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                        $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                        $mongPrePurcash['main'] = array($insertID, $epID);
                        cekmerah("tulis transaksi kedua :: trID $insertID");
                        cekmerah(__LINE__ . " " . $this->db->last_query());
                        if ($insertID < 1) {
                            die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                    }
                    else {
                        cekmerah("GAGAL tulis transaksi ketiga");
                    }
                    if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                            $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                            $mongPrePurcash['mainValues'][] = $dd;
                        }
                    }
                    if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                        foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                            $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                            $mongPrePurcash['mainValues'][] = $dd;
                        }
                    }
                    if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                        foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                            $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                            $mongPrePurcash['mainValues'][] = $dd;
                        }
                    }
                    if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                        //                    cekMerah("ada mainElements");
                        foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                            $tr->writeMainElements($insertID, array(
                                "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                "name" => $aSpec['name'],
                                "label" => $aSpec['label'],
                                "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                            ));
                        }
                    }
                    else {
                        //                    cekMerah("TAK ada mainElements");
                    }
                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                        $insertIDs = array();
                        $insertDeIDs = array();
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                            $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongPrePurcash['detail'][] = $insertDetailID;
                            if ($epID != 999) {
                                $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                $mongPrePurcash['detail'][] = $insertEpID;
                            }
                        }
                        if (sizeof($insertIDs) == 0) {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                        }
                        else {
                            $indexing_details = array();
                            foreach ($insertDeIDs as $key => $numb) {
                                $indexing_details[$key] = $numb;
                            }
                            foreach ($indexing_details as $k => $arrID) {
                                $arrBlob = blobEncode($arrID);
                                $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                cekOrange($this->db->last_query());
                            }
                        }
                    }
                    if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                        $insertIDs = array();
                        foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                            $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                            $mongPrePurcash['detail'] = $insertIDs;
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongPrePurcash['detail'] = $insertIDs;
                            }
                        }
                    }
                    if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                    $dd = $tr->writeDetailValues($insertID, array(
                                        "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                        "produk_id" => $pID,
                                        "key" => $key,
                                        "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                                    ));
                                    $insertIDs[] = $dd;
                                    $mongPrePurcash['detailValues'][] = $dd;

                                }
                            }
                        }
                    }
                    if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                    $dd = $tr->writeDetailValues($insertID, array(
                                        "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                        "produk_id" => $pID,
                                        "key" => $key,
                                        "value" => $dSpec[$src],
                                    ));
                                    $insertIDs[] = $dd;
                                    $mongPrePurcash['detailValues'][] = $dd;

                                }
                            }
                        }
                    }

                    //
                    //region nulis paymentSource
                    //                $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
                    $stepCode = $this->configUi[$connector]['steps'][1]['target'];
                    $paymentSources = $this->config->item("payment_source");
                    if (array_key_exists($stepCode, $paymentSources)) {

                        $payConfigs = $paymentSources[$stepCode];
                        if (sizeof($payConfigs) > 0) {
                            foreach ($payConfigs as $paymentSrcConfig) {
                                //					$paymentSrcConfig = $paymentSources[$stepCode];
                                $valueSrc = $paymentSrcConfig['valueSrc'];
                                $externSrc = $paymentSrcConfig['externSrc'];
                                $tr->writePaymentSrc($insertID, array(
                                    "jenis" => $stepCode,
                                    "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                    "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                    "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                    "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                    "nomer" => $tmpNomorNota2,
                                    "label" => $paymentSrcConfig['label'],
                                    "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                    "terbayar" => 0,
                                    "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                    "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                    "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                    "oleh_id" => $this->session->login['id'],
                                    "oleh_nama" => $this->session->login['nama'],
                                    "dtime" => date("Y-m-d H:i:s"),
                                    "fulldate" => date("Y-m-d"),
                                    "valas_id" => isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                                    "valas_nama" => isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                                    "valas_nilai" => isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                                    "tagihan_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                                    "terbayar_valas" => 0,
                                    "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                                ));
                            }
                        }


                        //cekMerah(__LINE__. " " .$this->db->last_query());

                    }
                    else {
                        //cekMerah("TIDAK nulis paymentSrc");
                    }
                    //endregion

                    //region nulis paymentAntiSource
                    //                $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
                    $stepCode = $this->configUi[$connector]['steps'][1]['target'];
                    $paymentSources = $this->config->item("payment_antiSource");
                    if (array_key_exists($stepCode, $paymentSources)) {
                        $payConfigs = $paymentSources[$stepCode];
                        if (sizeof($payConfigs) > 0) {
                            foreach ($payConfigs as $paymentSrcConfig) {
                                //					$paymentSrcConfig = $paymentSources[$stepCode];
                                $valueSrc = $paymentSrcConfig['valueSrc'];
                                $externSrc = $paymentSrcConfig['externSrc'];
                                $tr->writePaymentAntiSrc($insertID, array(
                                    "jenis" => $stepCode,
                                    "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                    "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                    "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                    "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                    "nomer" => $tmpNomorNota2,
                                    "label" => $paymentSrcConfig['label'],
                                    "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                    "terbayar" => 0,
                                    "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                    "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                    "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                    "oleh_id" => $this->session->login['id'],
                                    "oleh_nama" => $this->session->login['nama'],
                                    "dtime" => date("Y-m-d H:i:s"),
                                    "fulldate" => date("Y-m-d"),
                                ));
                            }
                        }


                        //cekMerah(__LINE__. " " .$this->db->last_query());

                    }
                    else {
                        //cekMerah("TIDAK nulis paymentSrc");
                    }
                    //endregion

                    $idHis_decode[$stepNum] = array(
                        "step" => $stepNum,
                        "trID" => $insertID,
                        "nomer" => $tmpNomorNota2,
                        "nomer2" => $tmpNomorNota2Alias,
                        "counters" => $appliedCounters2,
                        "counters_intext" => $appliedCounters_inText2,
                    );
                    $idHis_blob = blobEncode($idHis_decode);
                    $idHis_intext = print_r($idHis_decode, true);

                    $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                    $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;

                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array("id" => $insertID), array(
                        "id_master" => $masterID,
                        "id_top" => $insertID,

                        "ids_his" => $idHis_blob,
                        "ids_his_intext" => $idHis_intext,

                    )) or die("Failed to update tr next-state!");

                    //                if($seluruhnya){
                    //                    $dupState = $tr->updateData(array("id" => $insertID), array(
                    //                        "tail_number" => $nextStepNum,
                    //                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                    //
                    //                    )) or die("Failed to update trans tail!");
                    //                }
                    //cekHijau(__LINE__. " " .$this->db->last_query());


                    $baseRegistries = array(
                        'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                        'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                        'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                        'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                        'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                        'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                        'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                        'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                        'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                        'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                        'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                        'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                        'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                        'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                        'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                        'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                        'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                        'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                        'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                        'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                        'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                        'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),

                        'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                        'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                        'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                        'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                        'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                        'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                        'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                        'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                        'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                        'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                        'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                        'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                        'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                        'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                        'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                        "receiptDetailFields" => isset($this->configLayout[$connector]['receiptDetailFields'][1]) ? $this->configLayout[$connector]['receiptDetailFields'][1] : array(),
                        "receiptSumFields" => isset($this->configLayout[$connector]['receiptSumFields'][1]) ? $this->configLayout[$connector]['receiptSumFields'][1] : array(),
                        "receiptDetailFields2" => isset($this->configLayout[$connector]['receiptDetailFields2'][1]) ? $this->configLayout[$connector]['receiptDetailFields2'][1] : array(),
                        "receiptSumFields2" => isset($this->configLayout[$connector]['receiptSumFields2'][1]) ? $this->configLayout[$connector]['receiptSumFields2'][1] : array(),
                        "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum] : array(),
                        "jurnal_index" => isset($this->configCore[$this->jenisTr]['components'][$stepNum]) ? $this->configCore[$this->jenisTr]['components'][$stepNum] : array(),
                        "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$stepNum]) ? $this->configCore[$this->jenisTr]['preProcessor'][$stepNum] : array(),
                        "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$stepNum]) ? $this->configCore[$this->jenisTr]['postProcessor'][$stepNum] : array(),
                        "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                        "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                        "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                        "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),

                    );
                    $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                    $mongPrePurcashReg = $doWriteReg;
                    //endregion
                }
                else {
                    //cekMerah("to be delayed to connect to $connector");
                }
            }
            else {
                //cekKuning("not connecting to any tCode");
            }
        }
        //endregion

        //region nonactive allowed shipment
        $cekvalidateOverDue = isset($_SESSION[$cCode]['main']['customerID']) ? validateOverDue($_SESSION[$cCode]['main']['customerID']) : array();
        if (isset($cekvalidateOverDue['status']) && $cekvalidateOverDue['status'] == "allowed") {
            $this->load->model("Mdls/MdlOverDuePass");
            $od = new MdlOverDuePass();
            $where = array(
                "customers_id" => $_SESSION[$cCode]['main']['customerID'],
                "jenis" => "forever",
            );
            $arrUpdate = array(
                "status" => "0",
                "used_byID" => $_SESSION['login']['nama'],
                "used_byNama" => $_SESSION['login']['nama'],
                "used_id" => $insertID,
                "nomor" => $tmpNomorNota,

            );
            $od->updateData($where, $arrUpdate, $od->getTableName());
        }
        //endregion

        //region Com pre purchase
        //split to Pre Pre Purchase Supplies dari Request Cabang untuk stok yang tidak ada/kurang diPusat.
        //sekaligus check jika valid_qty sudah nol maka update next_substep_code transaksi bayangannya.
        $iterator = isset($this->configUi[$this->jenisTr]['comPrePurchase'][$stepNum]['detail']) ? $this->configUi[$this->jenisTr]['comPrePurchase'][$stepNum]['detail'] : array();
        $aliasMainTrans = isset($this->configUi[$this->jenisTr]['aliasMainTrans']) ? $this->configUi[$this->jenisTr]['aliasMainTrans'] : 999;

        //        cekOrange("LINE: " . __LINE__ . " || JENIS: " . $this->jenisTr);
        //        cekOrange("LINE: " . __LINE__ . " || aliasMainTrans: " . $aliasMainTrans);

        if (sizeof($iterator) > 0) {

            $this->load->model("MdlTransaksi");
            $l = new MdlTransaksi();
            $l->setFilters(array());
            $l->addFilterJoin("transaksi_data.valid_qty>0");
            $l->addFilterJoin("transaksi_data.next_substep_code='" . $aliasMainTrans . "'");
            $l->addFilter("link_id=0");
            $l->addFilterJoin("produk_id in (" . implode(",", array_keys($_SESSION[$cCode]['items'])) . ")");
            $tmp = $l->lookupJoined();

            if (sizeof($tmp) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];

                    echo "post-processor: $comName<br>LINE: " . __LINE__;
                    $dSpec = $_SESSION[$cCode][$srcGateName];
                    $tmpOutParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {
                            $tmpOutParams['loop'][$key] = $value;
                        }
                    }
                    if (sizeof($dSpec) > 0) {
                        foreach ($dSpec as $pid => $arrValue) {
                            $tmpOutParams[$srcGateName][$pid] = $arrValue['jml'];
                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {
                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['static'][$key] = $realValue;
                        }
                        if (!isset($tmpOutParams['static']["jenis"])) {
                            $tmpOutParams['static']["jenis"] = $aliasMainTrans;
                        }
                        if (!isset($tmpOutParams['static']["jenis_master"])) {
                            $tmpOutParams['static']["jenis_master"] = $this->jenisTr;
                        }
                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                        }
                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                        }
                        $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                        $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    $mdlName = "Com" . ucfirst($comName);
                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
            }

        }
        else {
            cekHere("LINE: " . __LINE__ . " || jenis: " . $this->jenisTr . " Tidak masuk Iterator PRE PURCHASE SUPPLIES");
        }
        //endregion Com pre purchase

        //region nulis ke data jika ada
        $addTodata = isset($this->configUi[$this->jenisTr]["addData"][$stepNum]) ? $this->configUi[$this->jenisTr]["addData"][$stepNum] : array();
        if (sizeof($addTodata) > 0) {
            $gateData = isset($_SESSION[$cCode][$addTodata["gate"]]) ? $_SESSION[$cCode][$addTodata["gate"]] : array();
            $selectedFields = $addTodata["fieldName"];
            $dataMdl = $addTodata["MdlNameMain"];
            $this->load->model("DComs/" . $dataMdl);
            $d = new $dataMdl();
            $childMdl = $addTodata["MdlNameChild"];
            $d = new $dataMdl();
            if (sizeof($gateData) > 0) {
                $outparams = array();
                $ctr = 0;
                foreach ($gateData as $gateValues) {
                    $params = array();
                    $ctr++;
                    foreach ($selectedFields as $colum => $gate_collom) {
                        $params['static'][$colum] = $gateValues[$gate_collom];
                    }
                    if ($masterID != "") {
                        $params['static']['transaksi_id_request_bunga'] = $masterID;
                    }
                    if ($insertID != "") {
                        $params['static']['transaksi_id'] = $insertID;
                    }
                    if ($this->session->login['nama_login'] != "") {
                        $params['static']['nama_login'] = $this->session->login['nama_login'];
                    }
                    if ($this->session->login['id'] != "") {
                        $params['static']['pihakid'] = $this->session->login['id'];
                    }
                    if ($tmpNomorNota2 != "") {
                        $params['static']['tmpNomorNota2'] = $tmpNomorNota2;
                    }
                    $outparams[] = $params + array("MdlName" => $childMdl);
                }

                if (sizeof($outparams) > 0) {
                    $d->pair($outparams) or die("Tidak berhasil memasang  values pada post-processor: $dataMdl/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $d->exec() or die("Gagal saat berusaha  exec values pada post-processor: $dataMdl/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    //                cekLime($this->db->last_query());

                }
                else {
                    matiHEre("error on insert data");
                }
            }
        }
//                matiHere($stepNum);


        //endregion

        //region nulis ke database project
        $idTargetProject = 0;
        switch ($stepNum) {
            case 1:
                matiHere("stepNum: $stepNum");
                break;
            case 2:
                $arrUpdate = array(
                    "quot_id" => $insertID,
                    "quot_nomer" => $tmpNomorNota2,
                    "quot_status" => 1,
                    "quot_appr_id" => $this->session->login['id'],
                    "quot_appr_nama" => $this->session->login['nama'],
                    "quot_appr_dtime" => date("Y-m-d H:i:s"),
                    "quot_desc" => $_SESSION[$cCode]['main']['description'],
                    "harga" => $_SESSION[$cCode]['main']['nilai_credit'],
                    "tarif_ppn" => $_SESSION[$cCode]['main']['ppnFactor'],
                    "ppn" => $_SESSION[$cCode]['main']['nilai_credit'] * $_SESSION[$cCode]['main']['ppnFactor'] / 100,
                    "harga_nppn" => $_SESSION[$cCode]['main']['tagihan'],
                );

                $this->load->model("Mdls/" . "MdlHargaProduk");
                $this->load->model("Mdls/" . "MdlProdukProject");
                $this->load->model("Mdls/" . "MdlProjectKomposisi");
                $this->load->model("Mdls/" . "MdlProjectWorkOrder");
                $this->load->model("Mdls/" . "MdlProjectWorkOrderSub");
                $this->load->model("Mdls/" . "MdlProjectKomposisiWorkorder");
                $this->load->model("Mdls/" . "MdlProjectKomposisiWorkorderSub");

                $pwo = new MdlProjectWorkOrder();
                $pwos = new MdlProjectWorkOrderSub();
                $pwok = new MdlProjectKomposisi();
                $pkwo = new MdlProjectKomposisiWorkorder();
                $pkwos = new MdlProjectKomposisiWorkorderSub();

                $this->load->model("Mdls/MdlProdukRakitanPreBiaya");
                //region biaya biaya
                $ob = new MdlProdukRakitanPreBiaya();
                $tempBiaya = $ob->lookUpAll()->result();
                $prebiaya = array();
                if (sizeof($tempBiaya) > 0) {
                    foreach ($tempBiaya as $ic => $biayaData) {
                        $prebiaya[$biayaData->id] = (array)$biayaData;
                    }
                }
                //endregion

//                $this->db->select("id, biaya_id, biaya_nama, cat_id, cat_nama biaya_dasar_id, biaya_dasar_nama");
//                $this->db->group_by("biaya_id");
//                $tmpPreBiaya = $this->db->get("project_komponen_biaya_details")->result();

                $this->db->select("id, nama, cat_id, cat_nama");
//                $this->db->group_by("biaya_id");
                $this->db->where("status", 1);
                $tmpPreBiaya = $this->db->get("dta_biayaproduksi")->result();
                $arrPreBiaya=array();
                foreach($tmpPreBiaya as $k => $tPB){
                    $arrPreBiaya[$tPB->id] = $tPB->cat_id;
                }

//                $arrPreBiaya = array(
//                    40 => 2, //direct labor
//                    41 => 4, //quality
//                    42 => 2, //direct labor
//                    43 => 2, //direct labor
//                    44 => 2, //direct labor
//                    45 => 2, //direct labor
//                    46 => 2, //direct labor
//                );

                $o = new MdlProdukProject();
                $o->addFilter("transaksi_no='$tmpNomorNota'");
                $o->addFilter("quot_status='0'");
                $tempProdukMaster = $o->lookUpAll()->result();
                $produk_id = $tempProdukMaster[0]->id;

                if (count($tempProdukMaster) == 1) {
                    $where = array(
                        "id" => $tempProdukMaster[0]->id
                    );
                    $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
                }
                else {
                    die(lgShowError("Ada kesalahan", "Duplikasi transaksi_no='$tmpNomorNota' pada produk project"));
                }

                cekMerah("MULAI NULIS");

                // project_workoder
                $pwo->setFilters(array());
                $pwo->addFilter("produk_id = " . $produk_id);
                $pwo->addFilter("status = 1");
                $existing_data = $pwo->lookUpAll()->row();

                if ($existing_data) {
                    // Jika sudah ada, update hanya dtime-nya saja
                    $update_data = array(
                        "dtime" => date("Y-m-d H:i:s"),
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama']
                    );
                    $where = array("id" => $existing_data->id);
                    $pwo->updateData($update_data, $where);

                }
                else {

                    // Jika belum ada, tambahkan data baru
                    $arr_project_workoder = array(
                        "produk_id" => $produk_id,
                        "qty" => "1",
                        "produk_nama" => $tempProdukMaster[0]->nama,
                        "nama" => $tempProdukMaster[0]->nama,
                        "status" => 1,
                        "trash" => 0,
                        "dtime" => date("Y-m-d H:i:s"),
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                    );
                    $ins_project_workoder = $pwo->addData($arr_project_workoder) or matiHere("gagal project workoder, silahkan ulangi beberapa saat lagi");
                }


//                $arr_project_workoder = array(
//                    "produk_id" => $tempProdukMaster[0]->id,
//                    "qty" => "1",
//                    "produk_nama" => $tempProdukMaster[0]->nama,
//                    "nama" => $tempProdukMaster[0]->nama,
//                    "status" => 1,
//                    "trash" => 0,
//                    "dtime" => date("Y-m-d H:i:s"),
//                    "oleh_id" => $this->session->login['id'],
//                    "oleh_nama" => $this->session->login['nama'],
//                );
//                $ins_project_workoder = $pwo->addData($arr_project_workoder) or matiHere("gagal project workoder, silahkan ulangi beberapa saat lagi");

                showLast_query("orange");

                // project_workoder_sub
                // Cek apakah produk_id dengan status = 1 sudah ada
                $pwos->setFilters(array());
                $pwos->addFilter("produk_id = " . $produk_id);
                $pwos->addFilter("status = 1");
                $existingData = $pwos->lookUpAll()->result();
                showLast_query("hitam");
                cekMerah("produk_id:: $produk_id");
                arrPrint($existingData);
                if (empty($existingData)) {
                    // Jika tidak ada data, tambahkan data baru
                    $arr_project_workoder_sub = array(
                        "produk_id" => $produk_id,
                        "fase_id" => $ins_project_workoder,
                        "qty" => 1,
                        "produk_nama" => $tempProdukMaster[0]->nama,
                        "nama" => $tempProdukMaster[0]->nama,
                        "status" => 1,
                        "trash" => 0,
                        "dtime" => date("Y-m-d H:i:s"),
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                    );

                    $ins_project_workoder_sub = $pwos->addData($arr_project_workoder_sub) or matiHere("gagal project workoder sub, silahkan ulangi beberapa saat lagi");
                }
                else {
                    // Jika data sudah ada, update dtime saja
                    $update_data = array(
                        "dtime" => date("Y-m-d H:i:s"),
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                    );

                    $where = array(
                        "produk_id" => $produk_id,
                        "status" => 1,
                    );

                    $pwos->updateData($update_data, $where) or matiHere("gagal update dtime, silahkan ulangi beberapa saat lagi");
                }

//                showLast_query("biru");
//                matiHere(__LINE__);
//                $arr_project_workoder_sub = array(
//                    "produk_id" => $tempProdukMaster[0]->id,
//                    "fase_id" => $ins_project_workoder,
//                    "qty" => 1,
//                    "produk_nama" => $tempProdukMaster[0]->nama,
//                    "nama" => $tempProdukMaster[0]->nama,
//                    "status" => 1,
//                    "trash" => 0,
//                    "dtime" => date("Y-m-d H:i:s"),
//                    "oleh_id" => $this->session->login['id'],
//                    "oleh_nama" => $this->session->login['nama'],
//                );
//                $ins_project_workoder_sub = $pwos->addData($arr_project_workoder_sub) or matiHere("gagal project workoder sub, silahkan ulangi beberapa saat lagi");

                showLast_query("orange");

                $arrMaterialProject = $_SESSION[$cCode]['items2_sum'];
                $arrBiayaProject = $_SESSION[$cCode]['items3_sum'];

                // project_komposisi
                $writeMaterialProject = array();
                if (!empty($arrMaterialProject)) {
                    foreach ($arrMaterialProject as $row) {
                        $tmpMaterialProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['hpp'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => $row['satuan'],
                            "satuan_nama" => $row['satuan_nama'],
                            "jenis" => isset($row['jenis']) && $row['jenis'] == "item_komposit" ? $row['jenis'] : "produk",
                            "harga" => $row['harga'],
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => "6",
                            "cat_nama" => "bahan baku",
                            "status" => 1,
                            "trash" => 0,
                        );
                        $writeMaterialProject[] = $tmpMaterialProject;
                    }
                }

                $writeBiayaProject = array();
                if (!empty($arrBiayaProject)) {
                    foreach ($arrBiayaProject as $row) {
                        $tmpBiayaProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['harga'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => 1,
                            "satuan_nama" => "unit",
                            "jenis" => "biaya",
                            "harga" => $row['harga'],
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => $arrPreBiaya[$row['id']],
                            "cat_nama" => $prebiaya[$arrPreBiaya[$row['id']]]['nama'],
                            "status" => 1,
                            "trash" => 0,
                        );
                        $writeBiayaProject[] = $tmpBiayaProject;
                    }
                }

                $write_project_komposisi = array_merge($writeMaterialProject, $writeBiayaProject);

                foreach ($write_project_komposisi as $wrData) {
                    $pwok->addData($wrData) or matiHere("gagal project workoder, silahkan ulangi beberapa saat lagi");
                    showLast_query("orange");
                }

                $writeKomposisiWo = array();

                // project_komposisi_workorder
                $writeMaterialProject = array();
                if (!empty($arrMaterialProject)) {
                    foreach ($arrMaterialProject as $row) {
                        $tmpMaterialProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['hpp'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => $row['satuan'],
                            "satuan" => $row['satuan_nama'],
                            "jenis" => isset($row['jenis']) && $row['jenis'] == "item_komposit" ? $row['jenis'] : "produk",
                            "harga" => $row['harga'],
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => "6",
                            "cat_nama" => "bahan baku",
                            "status" => 1,
                            "trash" => 0,
                            //===============
                            "fase_id" => $ins_project_workoder,
                            "jenis_transaksi" => "5582",
                            "gudang_id" => my_gudang_id(),
                            "gudang_nama" => my_gudang_nama(),
                            "gudang2_id" => my_cabang_id() . "" . $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                            "gudang2_nama" => "gudang2project ",
                            "author" => $this->session->login['id'],
                        );
                        $writeMaterialProject[] = $tmpMaterialProject;
                    }
                }

                $writeBiayaProject = array();
                if (!empty($arrBiayaProject)) {
                    foreach ($arrBiayaProject as $row) {
                        $tmpBiayaProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['harga'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => 1,
                            "satuan" => "unit",
                            "jenis" => "biaya",
                            "harga" => $row['harga'],
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => $arrPreBiaya[$row['id']],
                            "cat_nama" => $prebiaya[$arrPreBiaya[$row['id']]]['nama'],
                            "status" => 1,
                            "trash" => 0,
                            //==============
                            "fase_id" => $ins_project_workoder,
                            "jenis_transaksi" => "5582",
                            "gudang_id" => my_gudang_id(),
                            "gudang_nama" => my_gudang_nama(),
                            "gudang2_id" => my_cabang_id() . "" . $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                            "gudang2_nama" => "gudang2project ",
                            "author" => $this->session->login['id'],
                        );
                        $writeBiayaProject[] = $tmpBiayaProject;
                    }
                }

                $preWriteKomposisiWo = array_merge($writeMaterialProject, $writeBiayaProject);

                $jual_nilai = 0;
                foreach ($preWriteKomposisiWo as $ro) {
                    $jual_nilai += $ro['saldo'];
                }
                $writeJual[] = array(
                    "produk_id" => $tempProdukMaster[0]->id,
                    "produk_nama" => $tempProdukMaster[0]->nama,
                    "jml" => 1,
                    "nilai" => $jual_nilai,
                    "dtime" => date("Y-m-d H:i:s"),
                    "jenis" => "jual",
                    "harga" => $jual_nilai,
                    "status" => 1,
                    "trash" => 0,
                    //==============
                    "fase_id" => $ins_project_workoder,
                    "jenis_transaksi" => "5582",
                    "gudang_id" => $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                    "gudang2_id" => $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                    "author" => $this->session->login['id'],
                );
                $writeKomposisiWo = array_merge($preWriteKomposisiWo, $writeJual);
                foreach ($writeKomposisiWo as $wrData) {
                    $pkwo->addData($wrData) or matiHere("gagal project workoder, silahkan ulangi beberapa saat lagi");
                    showLast_query("orange");
                }

                $s = new MdlHargaProduk;
                $s->addFilter("cabang_id='-1'");
                $s->addFilter("status='1'");
                $tempHarga = $s->lookUpAll()->result();
                $arrPrice = array();
                if (!empty($tempHarga)) {
                    foreach ($tempHarga as $k => $prcData) {
                        $arrPrice[$prcData->produk_id][$prcData->jenis_value] = $prcData->nilai;
                    }
                }

                // project_komposisi_sub_workorder
                $writeKomposisiSubWo = array();
                $writeMaterialProject = array();
                if (!empty($arrMaterialProject)) {
                    foreach ($arrMaterialProject as $row) {
                        $tmpMaterialProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['hpp'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => $row['satuan'],
                            "satuan" => $row['satuan_nama'],
                            "jenis" => isset($row['jenis']) && $row['jenis'] == "item_komposit" ? $row['jenis'] : "produk",
                            "harga" => $row['harga'],
                            "hrg_hpp" => isset($arrPrice[$row['id']]['hpp_supplier']) && $arrPrice[$row['id']]['hpp_supplier']*1 > 0 ? round($arrPrice[$row['id']]['hpp_supplier']) : (isset($arrPrice[$row['id']]['hpp_supplier']) ? round($arrPrice[$row['id']]['hpp_supplier']) : 0),
                            "hrg_ppv" => isset($arrPrice[$row['id']]['hpp_supplier']) && $arrPrice[$row['id']]['hpp_supplier']*1 > 0 ? round($arrPrice[$row['id']]['hpp_supplier']) : (isset($arrPrice[$row['id']]['hpp_supplier']) ? round($arrPrice[$row['id']]['hpp_supplier']) : 0),
                            "hrg_jual" => isset($arrPrice[$row['id']]['jual']) ? round($arrPrice[$row['id']]['jual']) : 0,
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => "6",
                            "cat_nama" => "bahan baku",
                            "status" => 1,
                            "trash" => 0,
                            //===============
                            "fase_id" => $ins_project_workoder,
                            "sub_fase_id" => $ins_project_workoder_sub,
                            "jenis_transaksi" => "5582",
                            "gudang_id" => my_gudang_id(),
                            "gudang_nama" => my_gudang_nama(),
                            "gudang2_id" => my_cabang_id() . "" . $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                            "gudang2_nama" => "gudang2project ",
                            "author" => $this->session->login['id'],
                        );
                        $writeMaterialProject[] = $tmpMaterialProject;
                    }
                }

                //biaya details
                $this->load->model("Mdls/" . "MdlProjectKomponenBiayaDetails");
                $by = new MdlProjectKomponenBiayaDetails();
                $arrTmpByDetails = $by->lookUpAll()->result();
                $arrByDetails = array();
                if(!empty($arrTmpByDetails)){
                    foreach($arrTmpByDetails as $byData){
                        $by_id = $byData->biaya_id;
                        $by_dsr_id = $byData->biaya_dasar_id;
                        $arrByDetails[$by_id][$by_dsr_id] = (array)$byData;
                    }
                }
                //biaya details

                $writeBiayaProject = array();
                if (!empty($arrBiayaProject)) {
                    foreach ($arrBiayaProject as $row) {

                        $total_biaya = 0;
                        if(isset($arrByDetails[$row['id']])){
                            foreach($arrByDetails[$row['id']] as $iddet => $datDet){
                                $total_biaya += $datDet['harga'];
                            }
                        }

                        $tmpBiayaProject = array(
                            "produk_id" => $tempProdukMaster[0]->id,
                            "produk_nama" => $tempProdukMaster[0]->nama,
                            "produk_dasar_id" => $row['id'],
                            "produk_dasar_nama" => $row['nama'],
                            "jml" => $row['jml'],
                            "nilai" => $row['harga'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "satuan_id" => 1,
                            "satuan" => "unit",
                            "jenis" => "biaya",
                            "harga" => $row['harga'],
                            "hrg_hpp" => $total_biaya,
                            "hrg_ppv" => $total_biaya,
                            "harga" => $row['harga'],
                            "debet" => $row['subtotal'],
                            "saldo" => $row['subtotal'],
                            "qty_debet" => $row['jml'],
                            "qty_saldo" => $row['jml'],
                            "cat_id" => $arrPreBiaya[$row['id']],
                            "cat_nama" => $prebiaya[$arrPreBiaya[$row['id']]]['nama'],
                            "status" => 1,
                            "trash" => 0,
                            //==============
                            "fase_id" => $ins_project_workoder,
                            "sub_fase_id" => $ins_project_workoder_sub,
                            "jenis_transaksi" => "5582",
                            "gudang_id" => my_gudang_id(),
                            "gudang_nama" => my_gudang_nama(),
                            "gudang2_id" => my_cabang_id() . "" . $ins_project_workoder . "" . $tempProdukMaster[0]->id,
                            "gudang2_nama" => "gudang2project ",
                            "author" => $this->session->login['id'],
                        );
                        $writeBiayaProject[] = $tmpBiayaProject;
                    }
                }
                $writeKomposisiSubWo = array_merge($writeMaterialProject, $writeBiayaProject);
                foreach ($writeKomposisiSubWo as $wrData) {
                    $pkwos->addData($wrData) or matiHere("gagal project sub workoder, silahkan ulangi beberapa saat lagi");
                    showLast_query("orange");
                }
                break;
            case 3:
//                arrPrintCyan($_SESSION[$cCode]["main"]);
                $projectID = isset($_SESSION[$cCode]["main"]["projectID"]) ? $_SESSION[$cCode]["main"]["projectID"] : 0;
                $arrUpdate = array(
                    "project_start_id" => $insertID,
                    "project_start_nomer" => $tmpNomorNota2,
                    "project_start" => 1,
                    "project_started_id" => $this->session->login['id'],
                    "project_started_name" => $this->session->login['nama'],
                    "project_started_dtime" => date("Y-m-d H:i:s"),
                    "project_started_desc" => $_SESSION[$cCode]['main']['description'],
                    "nomor_kontrak" => $_SESSION[$cCode]['main']['no_kontrak'],
                    "tanggal_kontrak" => $_SESSION[$cCode]['main']['tgl_kontrak'],
                    "start_dtime" => $_SESSION[$cCode]['main']['startDate'],
                    "end_dtime" => $_SESSION[$cCode]['main']['endDate'],
                );

                $this->load->model("Mdls/" . "MdlProdukProject");
                $o = new MdlProdukProject();
                $o->addFilter("quot_nomer='$tmpNomorNota'");
                $o->addFilter("quot_status='1'");
                $o->addFilter("project_start='0'");
                $tempProdukMaster = $o->lookUpAll()->result();

                if (count($tempProdukMaster) == 1) {
                    $idTargetProject = $tempProdukMaster[0]->id;
                    if($projectID != $idTargetProject){
                        $msg = "Otorisasi Start Project gagal. Pastikan Project yang anda pilih sudah benar dan hanya aktif pada 1 browser.";
                        $msg .= " Silahkan refresh halaman ini. code: " . __LINE__;
                        mati_disini($msg);
                    }
                    else{
                        cekHijau("cocok");
                    }
                    $where = array(
                        "id" => $idTargetProject
                    );
                    $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
                    $updQuery = $this->db->last_query();
                }
                else {
                    die(lgShowError("Ada kesalahan", "Duplikasi quot_nomer='$tmpNomorNota' pada produk project"));
                }
                break;
            case 4:
                //closing project
                $projectID = isset($_SESSION[$cCode]["main"]["projectID"]) ? $_SESSION[$cCode]["main"]["projectID"] : 0;
                $arrUpdate = array(
                    "closing_transaksi_id" => $insertID,
                    "closing_transaksi_nomer" => $tmpNomorNota2,
                    "closing_status" => 1,
                    "closing_oleh_id" => $this->session->login['id'],
                    "closing_oleh_nama" => $this->session->login['nama'],
                    "closing_dtime" => date("Y-m-d H:i:s"),
                );

                $this->load->model("Mdls/" . "MdlProdukProject");
                $o = new MdlProdukProject();
                $o->addFilter("project_start_nomer='$tmpNomorNota'");
                $o->addFilter("quot_status='1'");
                $o->addFilter("project_start='1'");
                $tempProdukMaster = $o->lookUpAll()->result();

//                cekMerah($tmpNomorNota2);
//                cekMerah($tmpNomorNota);
// cekMerah($tempProdukMaster);
// arrPrintWebs($_SESSION[$cCode]["main"]);
//matiHere( count($tempProdukMaster) );

                if (count($tempProdukMaster) == 1) {
                    $idTargetProject = $tempProdukMaster[0]->id;
// if ($projectID != $idTargetProject) {
//     $msg = "Otorisasi Start Project gagal. Pastikan Project yang anda pilih sudah benar dan hanya aktif pada 1 browser.";
//     $msg .= " Silahkan refresh halaman ini. code: " . __LINE__;
                 //     mati_disini($msg);
// }
// else {
//     cekHijau("cocok");
// }
                    $where = array(
                        "id" => $idTargetProject
                    );
                    $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
// showLast_query("hijau");
                }
                else {
                    die(lgShowError("Ada kesalahan", "Duplikasi quot_nomer='$tmpNomorNota' pada produk project"));
                }

                break;
            default:
                matiHere("stepNum: $stepNum");
                break;
        }

        //endregion nulis ke database project

        //==tampilkan receipt
        cekOrange("-- DONE --");

        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion

        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;

//        mati_disini(__FUNCTION__ . " [$insertID] TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");
        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        //generate tasklist
        switch ($stepNum) {
            case 2:
                //generate biaya jika ada
                $modulTarget = "eusvc";
                $controllerTarget = "NonRest";
                $methodTarget = "makeDetailsBiayaFromProjectID";
                $project_id = $tempProdukMaster[0]->id;
                $urlConnect = base_url() . "$modulTarget/$controllerTarget/$methodTarget/$project_id";
                $curl = New Curl();
                $api = $curl->_simple_call("get", $urlConnect);
                break;
            case 3:
//                if ($idTargetProject) {
//                    $upd = $this->doCreteTasklistProject($idTargetProject);
//                    if (!$upd['status']) {
//                        matiHere("gagal generate tasklist | (" . $upd['status'] . ")" . "<br>" . json_encode($upd));
//                    }
//                }
                break;
        }

        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }

        if (isset($_SESSION["_TR_" . $origJenis])) {
            unset($_SESSION["_TR_" . $origJenis]);
        }

        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }

        //region feedback msg
        $this->session->errMsg = "transaction entry has been saved<br>";
        $nextNum = $nextProp["num"];
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextNum])) {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $this->session->errMsg .= "This entry needs to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['userGroup'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewIncomplete/" . $this->jenisTr;

        }
        else {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

        }
        $trBackClick = "location.href='$trBackLink'";
        //        $this->session->errMsg .= "<br><a href='javascript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
        //endregion

        if (isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum])) {
            $printLocation = $this->configLayout[$this->jenisTr]['printLocation'];
            $printException = isset($this->configLayout[$this->jenisTr]['printException'][$stepNum]) ? "/" . $this->configLayout[$this->jenisTr]['printException'][$stepNum] : "";
            $printSettings = isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum]) ? $this->configLayout[$this->jenisTr]['allowPrint'][$stepNum] : array();
            if (isset($printSettings['size'])) {
                switch ($printSettings['size']) {
                    case "normal":
                        //                        cekkuning("size: NORMAL");
                        echo "<script>";
                        echo "top.popBig('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/" . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    case "small":
                        //                        cekkuning("size: SMALL");
                        echo "<script>";
                        echo "top.popSmall('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/" . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    default:
                        //                        cekkuning("size: UNKNOWN");
                        break;
                }
            }
            else {
                $arrAlert = array(
                    "type" => "success",
                    "title" => "Transaction saved",
                    //                        "html" => "your order has been saved and ready to process",
                    "html" => $this->session->errMsg,
                    "timer" => "1500",
                    "showConfirmButton" => false,
                    "allowOutsideClick" => false,
                );
                echo swalAlert($arrAlert);
                echo "<script>top.topReload(1500)</script>";
//                echo topReload();
//                echo "</script>";
                unset($this->session->errMsg);
            }

        }
        else {
            $arrAlert = array(
                "type" => "success",
                "title" => "Transaction saved",
                //                        "html" => "your order has been saved and ready to process",
                "html" => $this->session->errMsg,
                "timer" => "1500",
                "showConfirmButton" => false,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            echo "<script>top.window.location.reload();</script>";
            unset($this->session->errMsg);
        }

    }

    public function doCreteTasklistProject($idTargetProject)
    {
//        $idTargetProject = $this->uri->segment(4);
        $url = base_url() . "master_project/MasterData/generatePreSPK/MdlTasklistProject/" . $idTargetProject . "?debuger=0";
        $login_url = base_url() . "auth/Login/authCheck";

        $path = DOC_ROOT . "/ctemp";
        $cookie_file_path = $path . "/cookie.txt";

        $username = trim("root");
        $password = trim("123456");
        $postinfo = "nama=" . $username . "&password=" . $password;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_URL, $login_url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
        curl_exec($ch);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->session->login);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec($ch);
        curl_close($ch);
        $arrOutput = json_decode($server_output);

        $lap = array();
        $logID = 0;
        if (!empty($arrOutput)) {
            $result = array(
                "status" => 1,
                "arrOutput" => $arrOutput,
                "server_output" => $server_output,
            );
        }
        else {
            $result = array(
                "status" => 0,
                "url" => $url,
                "arrOutput" => $arrOutput,
                "server_output" => $server_output,
            );
        }

        return $result;
    }

    public function doFollowupMulti()
    {
        echo "<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
//        $top_id = rtrim($this->uri->segment(8), "-");
        $stepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);


        echo "<script>top.writeProgress('MEMUAT CONFIG', 'HEAD');</script>";

        $paramPatchers = $this->config->item('heTransaksi_paramPatchers') != null ? $this->config->item('heTransaksi_paramPatchers') : array();
        $paramForceFillers = $this->config->item('heTransaksi_paramForceFillers') != null ? $this->config->item('heTransaksi_paramForceFillers') : array();

        echo "<script>top.writeProgress('MENYIAPKAN CALCULATOR', 'HEAD');</script>";

        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        echo "<script>top.writeProgress('MENYIAPKAN DATA-DATA TRANSAKSI', 'HEAD');</script>";

        //==ambil datanya

        $this->load->model("Mdls/MdlProdukProject");
        $prjPrd = new MdlProdukProject();
        $prjPrd->addFilter("project_start_id =$no");
        $tmpPrj = $prjPrd->lookupAll();
        $dataPrjPrd = $tmpPrj->result();
        showLast_query("biru");

        $top_id = $dataPrjPrd[0]->transaksi_id;
        cekHitam($no);
        cekHitam($top_id);
//        cekMerah(count($tmpPrj[0]));
//        matiHere(__LINE__);

        $stepNowParameter = array();
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        // $tr->addFilter("id in (" . implode(",", explode("-", $top_id)) . ")");
        $tr->addFilter("id in ($no)");
        // $tr->addFilter("step_number='" . $stepNumCurrent . "'");
        $tr->addFilterJoin("transaksi_data.trash='0'");
        $tmpTr = $tr->lookupJoined();
        cekMErah($this->db->last_query());
        // matiHEre();
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;

            $cCode = "_TR_" . $this->jenisTr;

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            $_SESSION[$cCode]['rsltItems'] = array();
            $_SESSION[$cCode]['rsltItems2'] = array();
            //endregion

            $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["target"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["target"] : NULL;
            $detailValuesConfig = isset($this->configCore[$this->jenisTr]['tableIn']['detailValues']) ? $this->configCore[$this->jenisTr]['tableIn']['detailValues'] : array();
            $additionalData = isset($this->configUi[$this->jenisTr]["addDetailData"][$stepNum]) ? $this->configUi[$this->jenisTr]["addDetailData"][$stepNum] : array();

            $masterID = $_SESSION[$cCode]['main']['masterID'];
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;

            //            $trID = $tmpTr[0]->id_master;
            $trID = $tmpTr[0]->transaksi_id;


            $totalSteps = sizeof($this->configUi[$this->jenisTr]['steps']);


            //==references, previous entry
            $prevProp = array(
                "id" => $tmpTr[0]->transaksi_id,
                "jenis" => $tmpTr[0]->jenis,
                "nomer" => $tmpTr[0]->nomer,
            );


            //------
            $stepNowParameter = array(
                "next_step_code" => $tmpTr[0]->next_step_code,
                "next_step_label" => $tmpTr[0]->next_step_label,
                "next_group_code" => $tmpTr[0]->next_group_code,
                "next_step_num" => $tmpTr[0]->next_step_num,
                "step_current" => $tmpTr[0]->step_current,
            );


            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }


            $main = array();
            $items = array();
            $prevIDs = array();
            $prevNos = array();
            foreach ($tmpTr as $row) {
                $items[$row->produk_id] = array(
                    "id" => $row->produk_id,
                    "nama" => $row->produk_nama,
                    "jml" => $row->produk_ord_jml,
                    "harga" => $row->produk_ord_hrg,
                    "valid_qty" => $row->valid_qty,
                    "transaksi_id" => $row->transaksi_id,
                    "nomer" => $row->nomer,
                );

                if ($row->valid_qty > 0) {
                    cekHitam("ok lanjut");
                }
                else {
                    if (isset($_SESSION[$cCode]['items'][$row->produk_id])) {
                        matiHere("Followed up already. Please close and refresh your browser " . $row->produk_nama . " " . $row->produk_id);//kalo session active ya harus dimatiin biar gak dobel
                    }
                }

                if (!in_array($row->transaksi_id, $prevIDs)) {
                    $prevIDs[] = $row->transaksi_id;
                }
                if (!in_array($row->nomer, $prevNos)) {
                    $prevNos[] = $row->nomer;
                }
                if (sizeof($detailValuesConfig) > 0) {
                    echo "detail values ada..<br>";
                    foreach ($detailValuesConfig as $key => $src) {
                        echo "$key akan ambil nilai dari $src<br>";
                        echo "<script>top.writeProgress('$key akan ambil nilai dari $src');</script>";
                        //                            $tmp[$key]=isset($iSpec[$val])?$iSpec[$val]:0;
                        if (isset($detailValues[$row->produk_id][$key])) {
                            //                            $tmp[$key] = formatField($key, $detailValues[$row->produk_id][$key]);
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                //                                $tmp[$key] = formatField($key, $row->$key);
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "dan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                        echo "<script>top.writeProgress('dan sekarang nilainya: " . $items[$row->produk_id][$key] . "');</script>";
                    }
                }
            }

        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }


        //update step terdahulu

        //region baca seting optional step
        if (isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) && strlen($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) > 0) {
            echo "<script>top.writeProgress('READING OPTIONAL STEPs', 'HEAD');</script>";
            $criteriaField = $this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField'];
            if (isset($_SESSION[$cCode]['main'][$criteriaField]) && $_SESSION[$cCode]['main'][$criteriaField] > 0) {
                echo "nextstepnum normal<br>";
                $nextStepNum = ($stepNum + 1);
                $useAdditionalStep = true;
            }
            else {
                echo "nextstepnum hampir normal<br>";
                $useAdditionalStep = false;
                $nextStepNum = ($stepNum + 2);
            }
        }
        else {
            //            //cekBiru("OPT TIDAK ditentukan");
            echo "nextstepnum TIDAK normal<br>";
            $useAdditionalStep = false;
            $nextStepNum = ($stepNum + 1);
            echo "yaitu $nextStepNum<br>";
        }
        //endregion


        //region build table rekening
        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        //arrPrint($buildTablesMaster);

        $addMasterTables = array(
            "rugilaba",
            "laba ditahan",
            "rugilaba lain lain",
        );
        foreach ($addMasterTables as $trek) {
            $buildTablesMaster[] = array(
                "comName" => "RugiLaba",
                "loop" => array(
                    "$trek" => .0,
                ),
            );
        }

        if (sizeof($buildTablesMaster) > 0) {
            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
                $mdlName = $buildTablesMaster_specs['comName'];
                if (substr($mdlName, 0, 1) == "{") {
                    //                        cekkuning("mengandung kurawal");
                    $mdlName = trim($mdlName, "{");
                    $mdlName = trim($mdlName, "}");
                    $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
                }
                else {
                    //                        cekkuning("TIDAK mengandung kurawal");
                }
                $mdlName = "Com" . $mdlName;
                cekHitam("model: $mdlName");


                if (isset($buildTablesMaster_specs['loop'])) {
                    foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
                        unset($buildTablesMaster_specs['loop'][$key]);
                        //                        if (isset($_SESSION[$cCode]['main'][$key])) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                        }
                        $buildTablesMaster_specs['loop'][$key] = $val;
                        //                        }
                    }
                }

                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();
                if (method_exists($m, "getTableNameMaster")) {
                    if (sizeof($m->getTableNameMaster())) {
                        $m->buildTables($buildTablesMaster_specs);
                    }
                }
            }
        }

        if (sizeof($buildTablesDetail) > 0) {
            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
                foreach ($_SESSION[$cCode]['items'] as $itemSpec) {

                    $mdlName = $buildTablesDetail_specs['comName'];
                    if (substr($mdlName, 0, 1) == "{") {
                        $mdlName = trim($mdlName, "{");
                        $mdlName = trim($mdlName, "}");
                        $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
                    }

                    if (isset($buildTablesDetail_specs['loop'])) {
                        foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
                            unset($buildTablesDetail_specs['loop'][$key]);

                            if (substr($key, 0, 1) == "{") {
                                $key = trim($key, "{");
                                $key = trim($key, "}");
                                $key = str_replace($key, $itemSpec[$key], $key);
                            }
                            $buildTablesDetail_specs['loop'][$key] = $val;
                            cekHitam("LINE: " . __LINE__ . " ::sini bukan??  akan build tabel detail $key");

                        }
                    }


                    $mdlName = "Com" . $mdlName;
                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();
                    if (method_exists($m, "getTableNameMaster")) {
                        if (sizeof($m->getTableNameMaster())) {
                            $m->buildTables($buildTablesDetail_specs);
                            arrPrint($buildTablesDetail_specs);
                            cekHitam(":: build tabel detail");
                        }
                    }
                }
            }
        }
        //endregion


        $this->db->trans_start();

        //regin update step terdahulu
        $plID = array();
        foreach ($_SESSION[$cCode]["items"] as $trPackingList => $plData) {
            $plID[] = $plData["produk_id"];
        }
        //region ItemPL udpate validqty item->project,subitem->fg,subitem3->biaya dari PO service
        $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();
        if (sizeof($plID) > 0) {
            if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
                echo "authorizing to next step..<br>";
                $nextProp = array(
                    "num" => $nextStepNum,
                    "code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                    "label" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['label'],
                    "groupID" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['userGroup'],
                );
            }
            else {//==ini step terakhir, tulis komponen jika ada

                $nextProp = array(
                    "num" => 0,
                    "code" => "",
                    "label" => "",
                    "groupID" => "",
                );
            }
            $tr = new MdlTransaksi();
            //region update step terdahulu main
            foreach ($plID as $trPl) {
                $dupState = $tr->updateData(array("id" => $trPl), array(
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "next_step_num" => $nextProp['num'],
                    "step_current" => $stepNum,

                    "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

                )) or die("Failed to update tr next-state!");
                cekLime($this->db->last_query());
                //lanjut update itemsnya
                $updateSubItems = array(
                    "valid_qty" => 0,
                    "sub_step_number" => $stepNum,
                    "sub_step_current" => $stepNum,
                    "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                    "next_substep_num" => $nextProp['num'],
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                );
                $tru = new MdlTransaksi();
                $tru->setFilters(array());
                $tru->setTableName($tru->getTableNames()["detail"]);
                $dupState = $tru->updateData(array(
                    "transaksi_id" => $trPl,
                ), $updateSubItems) or die("Failed to update previous detail entries!");
                cekHijau($this->db->last_query());
                $updtaeSubitem3 = array(
                    "valid_qty" => 0,
                );
                $tru = new MdlTransaksi();
                $tru->setFilters(array());
                $tru->setTableName($tru->getTableNames()["sub_detail"]);
                $dupState = $tru->updateData(array(
                    "transaksi_id" => $trPl,
                ), $updtaeSubitem3) or die("Failed to update previous detail entries!");
                cekHijau($this->db->last_query());
            }
            //endregion
            //update valid qty
        }


        //region pembulatan replacer disini
        $injectBulat = isset($this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum]) ? $this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum] : array();
        if (sizeof($injectBulat) > 0) {
            echo "<script>top.writeProgress('PEMBULATAN', 'HEAD');</script>";
            //            arrPrint($injectBulat);
            $selectedSource = $injectBulat['source'];
            $injectSource = makeDppBulat($_SESSION[$cCode]['main'][$selectedSource]);
            foreach ($injectBulat['replacer'] as $k => $fields) {
                $_SESSION[$cCode]['main'][$fields] = $injectSource[$k];
                echo "<script>top.writeProgress('PEMBULATAN ($fields)');</script>";
            }

        }
        //endregion


        cekMerah(":: MEMULAI PRE-PROCC ITEMS...");


        //        $step = $_SESSION[$cCode]['main']['step_number'];
        $this->load->library("Validator");
        $va = new Validator();
        $va->setConfigUiJenis($this->configUiJenis);
        $va->setCCode($this->cCode);
        $va->midValidate($stepNum);
        // matiHEre(__LINE__);
        $va->unionValidate();
        //==tulis komponen, if any
        // matiHEre(__LINE__);

        //region update step2an
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
            echo "authorizing to next step..<br>";
            $nextProp = array(
                "num" => $nextStepNum,
                "code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                "label" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['label'],
                "groupID" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['userGroup'],
            );
        }
        else {//==ini step terakhir, tulis komponen jika ada

            $nextProp = array(
                "num" => 0,
                "code" => "",
                "label" => "",
                "groupID" => "",
            );
        }
        //endregion


        echo "checking components..<br>";
        echo "<script>top.writeProgress('CHECKING KOMPONEN');</script>";


        //==tulis signature

        $dwsign = $tr->writeSignature($masterID, array(
            "nomer" => $tmpNomorNota,
            "step_number" => $stepNum,
            "step_code" => $this->configUi[$origJenis]['steps'][$stepNum]['target'],
            "step_name" => $this->configUi[$origJenis]['steps'][$stepNum]['label'],
            "group_code" => $this->configUi[$origJenis]['steps'][$stepNum]['userGroup'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "keterangan" => $this->configUi[$origJenis]['steps'][$stepNum]['label'] . " oleh " . $this->session->login['nama'],
            "transaksi_id" => $masterID,
        )) or die("Failed to write signature");
        $mongoList['sign'][] = $dwsign;
        //cekKuning($this->db->last_query());

        //region update step terdahulu SPO
        $tr = new MdlTransaksi();
        $tr->updateData(array("id" => $masterID), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

        )) or die("Failed to update tr next-state!");
        cekHitam($this->db->last_query());
        $arrUpdateITems = array(
            "valid_qty" => 0,
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        $tr->setFilters(array());
        $tr->setTableName($tru->getTableNames()["detail"]);
        $tr->updateData(array(
            "transaksi_id" => $masterID,
        ), $arrUpdateITems) or die("Failed to update previous detail entries!");
        cekHitam($this->db->last_query());
        //endregion SPO
        // matiHEre(__LINE__);
        //region update step terdahulu SO
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $dupState = $tr->updateData(array("id" => $top_id), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

        )) or die("Failed to update tr next-state!");
        //update item// transaksi_data SO
        $arrUpdateITems = array(
            "valid_qty" => 0,
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        $tr->setFilters(array());
        $tr->setTableName($tru->getTableNames()["detail"]);
        $tr->updateData(array(
            "transaksi_id" => $top_id,
        ), $arrUpdateITems) or die("Failed to update previous detail entries!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$top_id"),
            "value" => array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNum,
            ),
        );
        cekHijau($this->db->last_query());

        // region udpate subdetail SO
        $tr->setFilters(array());
        $tr->setTableName($tru->getTableNames()["sub_detail"]);
        $tr->addFilter("transaksi_id='$top_id'");
        $trTmp = $tr->lookupAll()->result();
        if (sizeof($trTmp) > 0) {
            foreach ($trTmp as $trSpec) {
                $valid_qty = $trSpec->valid_qty;
                $cancel_qty = $trSpec->valid_qty;
                $arrUpdateITems = array(
                    "valid_qty" => 0,
                    "sub_step_number" => $stepNum,
                    "sub_step_current" => $stepNum,
                    "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                    "next_substep_num" => $nextProp['num'],
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                );
                if ($cancel_qty > 0) {
                    $arrUpdateITems['cancel_qty'] = $cancel_qty;
                    $arrUpdateITems['cancel_id'] = my_id();
                    $arrUpdateITems['cancel_name'] = my_name();
                    $arrUpdateITems['batal_dtime'] = date("Y-m-d H:i:s");
                }
                $tr->setFilters(array());
                $tr->setTableName($tru->getTableNames()["sub_detail"]);
                $tr->updateData(array(
//                        "transaksi_id" => $top_id,
                    "id" => $trSpec->id,
                ), $arrUpdateITems) or die("Failed to update previous detail entries!");
                cekUngu($this->db->last_query());
            }
        }

        // endregion udpate subdetail SO


        // region sub item3 SO
        $tr->setFilters(array());
        $tr->setTableName($tru->getTableNames()["items3_sum"]);
        $tr->addFilter("transaksi_id='$top_id'");
        $trTmp = $tr->lookupAll()->result();
        if (sizeof($trTmp) > 0) {
            foreach ($trTmp as $trSpec) {
                $valid_qty = $trSpec->valid_qty;
                $cancel_qty = $trSpec->valid_qty;
                $arrUpdateITems = array(
                    "valid_qty" => 0,
                    "sub_step_number" => $stepNum,
                    "sub_step_current" => $stepNum,
                    "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                    "next_substep_num" => $nextProp['num'],
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                );
                if ($cancel_qty > 0) {
                    $arrUpdateITems['cancel_qty'] = $cancel_qty;
                    $arrUpdateITems['cancel_id'] = my_id();
                    $arrUpdateITems['cancel_name'] = my_name();
                    $arrUpdateITems['batal_dtime'] = date("Y-m-d H:i:s");
                }
                $tr->setFilters(array());
                $tr->setTableName($tru->getTableNames()["items3_sum"]);
                $tr->updateData(array(
//                    "transaksi_id" => $top_id,
                    "id" => $trSpec->id,
                ), $arrUpdateITems) or die("Failed to update previous detail entries!");
                cekOrange($this->db->last_query());
            }
        }
        else {
            cekMerah("TIDAK ADA sisa service jasa project");
        }
        // endregion sub item3 SO
//mati_disini();

        //-------------------------------------------------
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $top_id), array(
            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$trID"),
            "value" => array(
                "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
            ),
        );

        // matiHEre(__LINE__);
        //mati_disini("==== ==== ====");
        //endregion


        //==prepare kloningan
        $tCode = $this->configUi[$origJenis]['steps'][$stepNum]['target'];
        $tCodeName = $this->configUi[$origJenis]['steps'][$stepNum]['label'];
        $masterReplacers = array(
            //            "referensi_id" => $masterID, (dimatikan)
            //            "id_master"       => $masterID,
            //            "id_top"          => $topID,
            "inv" => $tmpNomorNota,
            //            "jenis_top"           => $tCode,
            "jenis" => $tCode,
            "jenis_label" => $tCodeName,
            "transaksi_jenis" => $tCode,
            "cabang_id" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangID'] : $this->session->login['cabang_id'],
            "cabang_nama" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangName'] : $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "step_current" => "0",
            "step_number" => $stepNum,
            //            "next_step_code"      => "",
            //            "next_step_label"     => "",
            //            "next_group_code"     => "",
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            //===references
            "id_master" => $masterID,
            "id_top" => $top_id,
            "ids_prev" => base64_encode(serialize($prevIDs)),
            "ids_prev_intext" => print_r($prevIDs, true),
            "nomer_top2" => isset($_SESSION[$cCode]['main']['nomer_top2']) ? $_SESSION[$cCode]['main']['nomer_top2'] : "",
            "nomer_top" => $_SESSION[$cCode]['tableIn_master']['nomer_top'],
            "nomers_prev" => base64_encode(serialize($prevNos)),
            "nomers_prev_intext" => print_r($prevNos, true),
            //            "jenis_top"           => $this->jenisTr,
            "jenises_prev" => base64_encode(serialize(array($prevProp['jenis']))),
            "jenises_prev_intext" => print_r(array($prevProp['jenis']), true),
            "tail_number" => $stepNum,
            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
        );

        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $childTableRepaclers = array(
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );

        if(isset($_SESSION[$cCode]['tableIn_detail'])){
        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
            }
        }
        }

        if(isset($_SESSION[$cCode]['tableIn_sub_detail'])){
        foreach ($_SESSION[$cCode]['tableIn_sub_detail'] as $idd => $deSpec) {
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_sub_detail'][$idd][$key] = $val;
            }
        }
        }

        if(isset($_SESSION[$cCode]['tableIn_sub_detail_items'])){
        foreach ($_SESSION[$cCode]['tableIn_sub_detail_items'] as $idd => $deSpec) {
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_sub_detail_items'][$idd][$key] = $val;
            }
        }
        }

        // arrPrint($_SESSION[$cCode]['tableIn_sub_detail']);
        // matiHEre(__LINE__);

        $masterReplacersO = array(

            "jenisTr" => $tCode,
            "jenisTrName" => $tCodeName,
            "olehID" => $this->session->login['id'],
            "olehName" => $this->session->login['nama'],
            "stepNumber" => $stepNum,
            "stepCode" => $tCode,
        );
        foreach ($masterReplacersO as $key => $val) {
            $_SESSION[$cCode]['main'][$key] = $val;
        }

        //region menimbulkan nilai tagihan
        $unpaidList = null != $this->config->item('tr_unpaidList') ? $this->config->item('tr_unpaidList') : array();
        //        arrprint($_SESSION[$cCode]['tableIn_master']);
        if (in_array($tCode, $unpaidList)) {
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_tagihan"] = $_SESSION[$cCode]['tableIn_master']['transaksi_nilai'];
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_terbayar"] = 0;
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_sisa"] = ($_SESSION[$cCode]['tableIn_master']['transaksi_nilai_tagihan'] - $_SESSION[$cCode]['tableIn_master']['transaksi_nilai_terbayar']);
            //cekMerah("NULIS TAGIHANN");
        }
        else {
            //cekMerah("TIDAK NULIS TAGIHANN");
        }
        //endregion


        //region penomoran receipt #1

        $this->load->model("CustomCounter");
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);

        $counterForNumber = array($this->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

        foreach ($counterForNumber as $i => $cRawParams) {
            $cParams = explode("|", $cRawParams);
            $cValues = array();
            foreach ($cParams as $param) {
                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
            }
            $cRawValues = implode("|", $cValues[$i]);
            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
        }
        $tmpNomorNota2 = $paramSpec['paramString'];
        $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);

        //endregion

        //region dynamic counters #1
        echo "<script>top.writeProgress('sedang membuat penomoran');</script>";
        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);
        $configCustomParams = $this->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                switch ($paramSpec['id']) {
                    case 0: //===counter type is new
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                        break;
                    default: //===counter to be updated
                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                        break;
                }
                //echo "<hr>";
            }
        }
        $appliedCounters2 = base64_encode(serialize($cContent));
        $appliedCounters_inText2 = print_r($cContent, true);


        $masterReplacers = array(
            "nomer" => $tmpNomorNota2,
            "nomer2" => $tmpNomorNota2Alias,
            "counters" => $appliedCounters2,
            "counters_intext" => $appliedCounters_inText2,
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $addValues = array(
            'counters' => $appliedCounters2,
            'counters_intext' => $appliedCounters_inText2,
            'nomer' => $tmpNomorNota2,
            'nomer2' => $tmpNomorNota2Alias,
            'dtime' => date("Y-m-d H:i:s"),
            'fulldate' => date("Y-m-d"),
        );
        foreach ($addValues as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        // </editor-fold>
        //endregion

        //region numbering tambahan
        $this->load->library("CounterNumber");
        $ccn = new CounterNumber();
        $ccn->setCCode($this->cCode);
        $ccn->setJenisTr($this->jenisTr);
        $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
        $ccn->setMainGate($_SESSION[$cCode]['main']);
        $ccn->setItemsGate($_SESSION[$cCode]['items']);
        $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
        $new_counter = $ccn->getCounterNumber();
        cekHitam("jenistr yang disett dari create " . $this->jenisTr);

        if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
            foreach ($new_counter['main'] as $ckey => $cval) {
                $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                $_SESSION[$cCode]['main'][$ckey] = $cval;
            }
        }
        if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
            foreach ($new_counter['items'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                }
            }
        }
        if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
            foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                }
            }
        }
        //endregion
        //==tulis kloningan transaksi
        //region write entries
        if (sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 0;
            $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
            $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];

            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
            $mongoList['main'] = array($insertID, $epID);
            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }


            if (isset($_SESSION[$cCode]['tableIn_master']['ids_his'])) {
                $idHis_decode = blobDecode($_SESSION[$cCode]['tableIn_master']['ids_his']);
                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;


                $tr = new MdlTransaksi();
                $dup = $tr->updateData(array("id" => $insertID), array(
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekUngu($this->db->last_query());
            }


            cekUngu(":: insertID => $insertID ::");
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                $mongoList['mainValues'] = array();
                foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $inserMainValues[] = $dd;
                    $mongoList['mainValues'][] = $dd;
                }
                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }


            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                //                cekMerah("ada mainElements $cCode");
                //                arrprint($_SESSION[$cCode]['main_elements']);die();
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? print_r($aSpec['contents_intext'], true) : "",

                    ));
                }
            }
            else {
                //                cekMerah("TAK ada mainElements");
            }

            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }

                    }
                }
                if (sizeof($insertIDs) > 0) {
                    $arrBlob = blobEncode($insertIDs);
                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }


            //region update validQty pada step sebelumnya yang di-refer
            echo "<script>top.writeProgress('EXTRACT ITEMS...','head');</script>";
            $seluruhnya = true;
            $prevTrID = 0;
            $arrvalidQtySisa = array();
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $closedRequest = isset($this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled']) ? $this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled'] : false;
                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $iID => $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($insertDetailID < 1) {
                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                    else {
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;

                    }

                    if ($epID != 999) {
                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                        if ($insertEpID < 1) {
                            die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertEpID;
                            $insertDeIDs[$epID][] = $insertEpID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                    }

                    cekHitam("EXTRACTED ITEMS... [$iID]");
                    echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                    $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $gate_update => $tbl_detail) {
                            if (isset($_SESSION[$cCode][$gate_update])) {

                                if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                    $itemFulfilledJml = 0;
                                    foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                        $prevTrID = $triSpec['transaksi_id'];
                                        $tru = new MdlTransaksi();
                                        $tru->setFilters(array());
                                        $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                        //----------------------------------------------------------
                                        if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                            $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                            //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                        }
                                        else {
                                            $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                            //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                        }
                                        //----------------------------------------------------------
                                        $newValidQtyNotApprove = 0;
                                        if ($closedRequest == true) {
                                            cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = 0;
                                                $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                            }
                                            cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                        }
                                        //----------------------------------------------------------


                                        $itemFulfilledJml += $newValidQty;
                                        $updateContents = array(
                                            "valid_qty" => $newValidQty,
                                            "valid_qty_no_approve" => $newValidQtyNotApprove,
                                        );
                                        if ($newValidQty < 1) {
                                            $childPrevRepaclers = array(
                                                "next_substep_code" => "",
                                                "next_substep_label" => "",
                                                "next_subgroup_code" => "",
                                                "sub_tail_number" => $stepNum,
                                                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                            );
                                            foreach ($childPrevRepaclers as $key => $val) {
                                                $updateContents[$key] = $val;
                                            }
                                        }
                                        else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                            $seluruhnya = false;
                                            $arrvalidQtySisa[$iID] = $newValidQty;
                                        }
                                        $dupState = $tru->updateData(array(
                                            "produk_id" => $iID,
                                            "id" => $triID,
                                            "transaksi_id" => $triSpec['transaksi_id'],
                                        ), $updateContents) or die("Failed to update previous detail entries!");
                                        cekHijau($this->db->last_query());

                                        $mongUpdateList['update'][$tbl_detail][] = array(
                                            "where" => array(
                                                //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                "id" => "$triID",
                                                //                                        "produk_id" => $iID,
                                            ),
                                            "value" => $updateContents,
                                        );
                                        unset($tru);
                                    }
                                }
                            }
                        }
                    }

                    // matiHEre("oo");
                    // arrPrint($iterator);
                    // matiHEre($jenisTrTarget);
                }

                if ($closedRequest == true) {
                    if (isset($_SESSION[$cCode]['extractedItems'])) {
                        foreach ($_SESSION[$cCode]['extractedItems'] as $iIDex => $exSpec) {
                            if (!array_key_exists($iIDex, $_SESSION[$cCode]['tableIn_detail'])) {
                                foreach ($exSpec as $trDataID => $trdSpec) {
                                    $tru = new MdlTransaksi();
                                    $tru->setFilters(array());
                                    $tru->setTableName($tru->getTableNames()['detail']);
                                    $updateContents = array(
                                        "valid_qty" => 0,
                                        "valid_qty_no_approve" => $trdSpec['qty'],
                                    );
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                    $dupState = $tru->updateData(array(
                                        "produk_id" => $iIDex,
                                        "id" => $trDataID,
                                        "transaksi_id" => $trdSpec['transaksi_id'],
                                    ), $updateContents) or die("Failed to update previous detail entries!");
                                    //                                    cekHijau($this->db->last_query());
                                    $mongUpdateList['update']['detail'][] = array(
                                        "where" => array(
                                            //                                            "transaksi_id" => $trdSpec['transaksi_id'],
                                            "id" => "$trDataID",
                                            //                                            "produk_id" => $iIDex,
                                        ),
                                        "value" => $updateContents,
                                    );
                                    unset($tru);
                                }
                            }
                        }
                    }
                }

                if (sizeof($insertIDs) == 0) {
                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                else {
                    $indexing_details = array();
                    foreach ($insertDeIDs as $key => $numb) {
                        $indexing_details[$key] = $numb;
                    }
                    foreach ($indexing_details as $k => $arrID) {
                        arrPrint($arrID);
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }

                //-------------
                $lastStepPartialApprove = isset($this->configUi[$this->jenisTr]['lastStepPartialApprove']) ? $this->configUi[$this->jenisTr]['lastStepPartialApprove'] : false;
                if ($lastStepPartialApprove == true) {
                    cekKuning(__LINE__ . " $lastStepPartialApprove :: $totalSteps");
                    if ($totalSteps == 2) {
                        if (sizeof($arrvalidQtySisa) > 0) {
                            cekPink("ada valid qty yang tersisa");
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $top_id), $stepNowParameter) or die("Failed to update tr next-state!");
                            cekHitam(__LINE__ . " ## 2 step, dan step akhir partial, YESS...");
                            showLast_query("orange");
                        }
                    }
                }
            }
            else {
                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
            }

            if ($seluruhnya) {
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $prevTrID), array(
                    "tail_number" => $stepNum,
                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                    "status_4" => $_SESSION[$cCode]['main']['status_4'],
                    "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                )) or die("Failed to update tr next-state!");
                cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                $mongUpdateList['update']['main'][] = array(
                    "where" => array(
                        "id" => "$prevTrID",
                    ),
                    "value" => array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    ),
                );
                cekHijau($this->db->last_query());
            }
            //endregion


            //region cloner items to item_child
            if (sizeof($additionalData) > 0) {
                echo "<script>top.writeProgress('CLONING ITEMS TO ITEM CHILD...','head');</script>";
                cekHitam("ini data");
                $dataMdl = $additionalData["mdlName"];
                $this->load->model("Mdls/" . $dataMdl);
                $da = new $dataMdl();
                $arrColl = $da->getFields();
                $selectedCol = array();
                foreach ($arrColl as $colSpec) {
                    $selectedCol[] = $colSpec['kolom'];
                }

                if (isset($_SESSION[$cCode]['items_child']) && sizeof($_SESSION[$cCode]['items_child'])) {
                    $gateData = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate']) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['gate'] : "detail";

                    $arrBlacklist = array(
                        "jml", "max_jml", "qty",
                    );
                    if (isset($_SESSION[$cCode]["items2_sum"])) {
                        unset($_SESSION[$cCode]["items2_sum"]);
                        unset($_SESSION[$cCode]["items2"]);
                        unset($_SESSION[$cCode]["tableIn_detail_values2_sum"]);
                    }
                    foreach ($_SESSION[$cCode]['items_child'] as $mainProdsID => $defData) {
                        if ($gateData == "detail") {
                            $itemsMain = isset($_SESSION[$cCode]['items'][$mainProdsID]) ? $_SESSION[$cCode]['items'][$mainProdsID] : array();
                        }
                        else {
                            $forceMainToItems = isset($this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData]) ? $this->configUi[$this->jenisTr]['shopingCartDetailFields'][$stepNum]['changeToItems'][$gateData] : array();
                            if (sizeof($forceMainToItems) > 0) {
                                foreach ($forceMainToItems as $key1 => $key2) {
                                    $keyForce = strlen($key2) > 2 ? $key2 : $key1;
                                    $itemsMain[$key1] = isset($_SESSION[$cCode]['main'][$keyForce]) ? $_SESSION[$cCode]['main'][$keyForce] : "";
                                }
                                $itemsMain["jml"] = "1";
                                $itemsMain["qty"] = "1";
                                $itemsMain["max_jml"] = "1";

                            }
                            else {
                                matiHEre("detil aset gagal di tulis!");
                            }
                            //                            arrPrint($forceMainToItems);
                        }

                        $arrChilds = array_diff_key($itemsMain, array_flip($arrBlacklist));
                        //                        arrPrint($itemsMain);
                        //                        matiHEre();
                        //
                        //arrPrint($arrChilds);
                        cekLime("ini brooo " . $gateData);

                        $arrNew = array();
                        if (sizeof($itemsMain) > 0) {
                            foreach ($defData as $inID => $detil_child) {
                                //                        $arrNewChild = array_diff($itemsMain,$detil_child);

                                $paramDetil = array_replace($arrChilds, $detil_child);
                                if (array_key_exists("id", $paramDetil)) {

                                    $paramDetil["parent_id"] = $paramDetil["id"];
                                    if (!isset($paramDetil["folders"]) || $paramDetil["folders"] == 0) {
                                        $paramDetil["folders"] = $paramDetil["pihakMainId"];
                                        $paramDetil["keterangan"] = $paramDetil["pihakMainName"];
                                    }
                                    unset($paramDetil["id"]);
                                }
                                $tmpData = array();
                                foreach ($selectedCol as $i => $coloum) {
                                    if (isset($paramDetil[$coloum])) {
                                        $tmpData[$coloum] = $paramDetil[$coloum];
                                    }
                                }
                                //                                arrPrint($paramDetil);
                                if (isset($paramDetil["subtotal"])) {
                                    $paramDetil["subtotal"] = $paramDetil["jml"] * $paramDetil["harga"];
                                }

                                $insertDataID = $da->addData($tmpData, $da->getTableName()) or die(lgShowError("Gagal menulis pengajuan data", __FILE__));
                                cekHere($this->db->last_query());
                                $paramDetil["id"] = $insertDataID;
                                echo "<script>top.writeProgress('PENGAJUAN DATA (TRID:$insertDataID)');</script>";
                                $_SESSION[$cCode]["items2_sum"][$insertDataID] = $paramDetil;
                                $_SESSION[$cCode]["items2"][$mainProdsID][$insertDataID] = $paramDetil;
                                //                            $arrNew

                            }
                        }


                        //                        arrPrint($arrNew);
                        //


                        //                  arrPrint($itemsMain);
                    }

                }
            }

            //endregion

            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                    cekUngu($this->db->last_query());
                }
            }
            //region tulis sub transaksi data
            if (isset($this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget]) && $this->configCore[$this->jenisTr]['writeSubDetail'][$jenisTrTarget] == true) {
                $seluruhnya = true;
                $prevTrID = 0;
                $arrvalidQtySisa = array();
                if (isset($_SESSION[$cCode]['tableIn_sub_detail']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail']) > 0) {

                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_sub_detail'] as $iID => $dSpec) {
                        $insertDetailID = $tr->writeDetailSubEntries($insertID, $dSpec);
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailSubEntries($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                // $mongoList['detail'][] = $insertEpID;
                            }
                        }

                        cekUngu($this->db->last_query());
                        cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                        echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                        $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $gate_update => $tbl_detail) {
                                if (isset($_SESSION[$cCode][$gate_update])) {
                                    if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                        $itemFulfilledJml = 0;
                                        foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                            $prevTrID = $triSpec['transaksi_id'];
                                            $tru = new MdlTransaksi();
                                            $tru->setFilters(array());
                                            $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                            //----------------------------------------------------------
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                                //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                            }
                                            else {
                                                $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                                //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                            }
                                            //----------------------------------------------------------
                                            $newValidQtyNotApprove = 0;
                                            if ($closedRequest == true) {
                                                cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = 0;
                                                    $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                }
                                                cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                            }
                                            //----------------------------------------------------------
                                            $itemFulfilledJml += $newValidQty;
                                            $updateContents = array(
                                                "valid_qty" => $newValidQty,
                                                "valid_qty_no_approve" => $newValidQtyNotApprove,
                                            );
                                            if ($newValidQty < 1) {
                                                $childPrevRepaclers = array(
                                                    "next_substep_code" => "",
                                                    "next_substep_label" => "",
                                                    "next_subgroup_code" => "",
                                                    "sub_tail_number" => $stepNum,
                                                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                );
                                                foreach ($childPrevRepaclers as $key => $val) {
                                                    $updateContents[$key] = $val;
                                                }
                                            }
                                            else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                $seluruhnya = false;
                                                $arrvalidQtySisa[$iID] = $newValidQty;
                                            }
                                            $dupState = $tru->updateData(array(
                                                "produk_id" => $iID,
                                                "id" => $triID,
                                                "transaksi_id" => $triSpec['transaksi_id'],
                                            ), $updateContents) or die("Failed to update previous detail entries!");
                                            cekHijau($this->db->last_query());

                                            $mongUpdateList['update'][$tbl_detail][] = array(
                                                "where" => array(
                                                    //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                    "id" => "$triID",
                                                    //                                        "produk_id" => $iID,
                                                ),
                                                "value" => $updateContents,
                                            );
                                            unset($tru);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_sub_details = '$arrBlob' WHERE id=$k");
                            cekOrange($this->db->last_query());
                        }
                    }
                }
                else {
                    // matiHere("update subdetil biaya pos ervice");
                    //dimatiin karena bisa tanpa sub detail item
                    // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }


                if ($seluruhnya) {
                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array("id" => $prevTrID), array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    )) or die("Failed to update tr next-state!");
                    cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array(
                            "id" => "$prevTrID",
                        ),
                        "value" => array(
                            "tail_number" => $stepNum,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                            "status_4" => $_SESSION[$cCode]['main']['status_4'],
                            "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                        ),
                    );
                    cekHijau($this->db->last_query());
                }
                // matiHEre("tulis subdetail broo");
                // matiHere();
                //region tulis sub transaksi_data_items3_sum / biaya
                $seluruhnya = true;
                $prevTrID = 0;
                $arrvalidQtySisa = array();
                if (isset($_SESSION[$cCode]['tableIn_sub_detail_items']) && sizeof($_SESSION[$cCode]['tableIn_sub_detail_items']) > 0) {
                    // matiHere(__LINE__);
                    $insertIDs = array();
                    $insertDeIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_sub_detail_items'] as $iID => $dSpec) {
                        $insertDetailID = $tr->writeDetailSubEntries_items($insertID, $dSpec);
                        cekHitam($this->db->last_query());
                        // matiHere($this->db->last_query());
                        if ($insertDetailID < 1) {
                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertDetailID;
                            $insertDeIDs[$insertID][] = $insertDetailID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                        if ($epID != 999) {
                            $insertEpID = $tr->writeDetailSubEntries($epID, $dSpec);
                            if ($insertEpID < 1) {
                                die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                            }
                            else {
                                $insertIDs[] = $insertEpID;
                                $insertDeIDs[$epID][] = $insertEpID;
                                // $mongoList['detail'][] = $insertEpID;
                            }
                        }

                        cekUngu($this->db->last_query());
                        cekHitam("EXTRACTED SUB ITEMS... [$iID]");
                        echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";

                        $iterator = isset($this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postUpdateItems'][$jenisTrTarget] : array();

                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $gate_update => $tbl_detail) {
                                if (isset($_SESSION[$cCode][$gate_update])) {
                                    cekPink($gate_update);
                                    if (array_key_exists($iID, $_SESSION[$cCode][$gate_update])) {
                                        $itemFulfilledJml = 0;
                                        foreach ($_SESSION[$cCode][$gate_update][$iID] as $triID => $triSpec) {
                                            $prevTrID = $triSpec['transaksi_id'];
                                            $tru = new MdlTransaksi();
                                            $tru->setFilters(array());
                                            $tru->setTableName($tru->getTableNames()[$tbl_detail]);
                                            //----------------------------------------------------------
                                            if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                                //                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                            }
                                            else {
                                                $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                                //                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                            }
                                            // matiHEre(" ".$triSpec['valid_qty'] ." -". $dSpec['produk_ord_jml']);
                                            //----------------------------------------------------------
                                            $newValidQtyNotApprove = 0;
                                            if ($closedRequest == true) {
                                                cekPink2("closed Request enabled, request: " . $triSpec['valid_qty'] . ", approve: " . $dSpec['produk_ord_jml'] . ", newValidQty: " . $newValidQty);
                                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                                    $newValidQty = 0;
                                                    $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);

                                                }
                                                cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                            }
                                            //----------------------------------------------------------
                                            $itemFulfilledJml += $newValidQty;
                                            $updateContents = array(
                                                "valid_qty" => $newValidQty,
                                                "valid_qty_no_approve" => $newValidQtyNotApprove,
                                            );
                                            if ($newValidQty < 1) {
                                                $childPrevRepaclers = array(
                                                    "next_substep_code" => "",
                                                    "next_substep_label" => "",
                                                    "next_subgroup_code" => "",
                                                    "sub_tail_number" => $stepNum,
                                                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                                );
                                                foreach ($childPrevRepaclers as $key => $val) {
                                                    $updateContents[$key] = $val;
                                                }
                                            }
                                            else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                                $seluruhnya = false;
                                                $arrvalidQtySisa[$iID] = $newValidQty;
                                            }
                                            $dupState = $tru->updateData(array(
                                                "produk_id" => $iID,
                                                "id" => $triID,
                                                "transaksi_id" => $triSpec['transaksi_id'],
                                            ), $updateContents) or die("Failed to update previous detail entries!");
                                            cekHijau($this->db->last_query());
                                            // matiHEre();
                                            $mongUpdateList['update'][$tbl_detail][] = array(
                                                "where" => array(
                                                    //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                                    "id" => "$triID",
                                                    //                                        "produk_id" => $iID,
                                                ),
                                                "value" => $updateContents,
                                            );
                                            unset($tru);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (sizeof($insertIDs) == 0) {
                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong. <br> ERROR CODE " . __LINE__));
                    }
                    else {
                        $indexing_details = array();
                        foreach ($insertDeIDs as $key => $numb) {
                            $indexing_details[$key] = $numb;
                        }

                        foreach ($indexing_details as $k => $arrID) {
                            $arrBlob = blobEncode($arrID);
                            $this->db->query("UPDATE transaksi SET indexing_items3_sum = '$arrBlob' WHERE id=$k");
                            cekHitam($this->db->last_query());
                        }
                    }
                }
                else {
                    // matiHere("update subdetil biaya pos ervice");
                    //dimatiin karena bisa tanpa sub detail item
                    // die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                //endregion
            }
            else {
                cekMerah("tidak tulis subdetail broo");
            }
            // matiHEre("tulis subdetail broo ".__LINE__);
            //endregion

            if (isset($this->configUi[$this->jenisTr]['updateDueDate'][$stepNum])) {
                $dueDateConf = $this->configUi[$this->jenisTr]['updateDueDate'][$stepNum];
                $sourceDue = $dueDateConf['source'];
                $targetDue = $dueDateConf['target'];
                $datenow = date("Y-m-d");
                foreach ($sourceDue as $key => $val) {
                    $indexVal = isset($_SESSION[$cCode]['main_elements'][$key][$val]) ? $_SESSION[$cCode]['main_elements'][$key][$val] : 14;
                    $dueDate = dueDate($datenow, $indexVal);
                }
                $fieldDue = $tr->getFields()["dueDate"];
                $dataDue = array();
                foreach ($fieldDue as $kol) {
                    if (isset($_SESSION[$cCode]['tableIn_master'][$kol])) {
                        $dataDue[$kol] = $_SESSION[$cCode]['tableIn_master'][$kol];
                    }
                }
                $dataDue['due_date'] = $dueDate;
                $validateDue = validateDueDate($_SESSION[$cCode]['main']['customerID'], $_SESSION[$cCode]['main']['dtime']);

                arrPrint($validateDue);
                if ($validateDue['allow_create'] == "true") {
                    if (isset($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']) && $_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen'] > 0) {
                        cekBiru($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']);

                        $tr->writeDueDate($insertID, $dataDue);
                    }
                }
                else {
                    $allowedOver = validateOverDue($_SESSION[$cCode]['main']['customerID']);
                    if ($allowedOver['status'] == "allowed") {

                    }
                    else {
                        //                        matiHere($validateDue['error']);//matiin transaksi sudah over due
                    }
                    //                    arrPrint()
                    //                    matiHere($validateDue['error']);//matiin transaksi sudah over due
                }
                //                matiHere();
                //update main elementnya
                foreach ($targetDue as $keyTarget => $valTarget) {
                    $_SESSION[$cCode]['main_elements'][$keyTarget][$valTarget] = $dueDate;
                    $_SESSION[$cCode]['main']['dueDate'] = $dueDate;
                }
            }


            $baseRegistries = array(
                'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                'rsltItems3_sub' => isset($_SESSION[$cCode]['rsltItems3_sub']) ? $_SESSION[$cCode]['rsltItems3_sub'] : array(),

                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum] : array(),
                "jurnal_index" => isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
            );
            // arrPrint($baseRegistries);
            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            // matiHEre();
            echo "<script>top.writeProgress('MENULIS KE-REGISTRY.... LINE: ".__LINE__."');</script>";
        }
        else {
            die(lgShowAlert("Transaksi gagal disimpan, silahkan cek kembali transaksi ini."));
        }
        //endregion


        //region processing sub-post-processors, always
        //<editor-fold desc="----------sub postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, initializing values <br>";
                echo "<script>top.writeProgress('MENYIAPKAN DATA SUB-PROCESSORS UNTUK DIKIRIM...', 'head');</script>";

                $tmpOutParams[$cCtr] = array();
                if (isset($_SESSION[$cCode][$srcGateName]) && sizeof($_SESSION[$cCode][$srcGateName]) > 0) {
                    foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                $subParams['loop'][$key] = $realValue;

                            }
                        }
                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                $subParams['static'][$key] = $realValue;
                                cekBiru("$key diisi dengan $realValue");

                            }

                            if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                                foreach ($paramPatchers[$comName] as $k => $v) {
                                    if (!isset($subParams['static'][$k])) {
                                        $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    }
                                }
                            }
                            if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                                $jenis = $_SESSION[$cCode]['main']['jenis'];
                                foreach ($paramForceFillers[$comName] as $k => $v) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    cekorange(":: $k diisikan dengan " . $subParams['static'][$k]);
                                }
                            }

                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }
                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr][] = $subParams;
                        }
                        echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
                    }
                }

            }
            // matiHEre();

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                if (isset($_SESSION[$cCode][$srcGateName]) && sizeof($_SESSION[$cCode][$srcGateName]) > 0) {
                    $mdlName = "Com" . ucfirst($comName);
                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();
                    // matiHEre(__LINE__." $mdlName");
                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    cekBiru($this->db->last_query());
                }
                else {
                    ceklIme("skipping Com" . $comName);
                }

            }
        }

        //endregion
        // matiHEre(__LINE__);
        //
        //region processing main-post-processors, always
        //<editor-fold desc="----------postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('MEMPROSES MAIN-PROCESSORS...', 'head');</script>";
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //                cekBiru("kiriman komponem $comName");
                //                                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }


        //</editor-fold>
        //endregion

        //region postUpdaterMisc-master untuk
        cekHitam($jenisTrTarget);
        $iterator = isset($this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('MEMPROSES MAIN-PROCESSORS...', 'head');</script>";
            // matiHEre(__LINE__);
            foreach ($iterator as $cCtr => $tComSpec) {

                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //                cekBiru("kiriman komponem $comName");
                //                                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }

        $iterator = isset($this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postUpdaterMisc'][$jenisTrTarget]['detail'] : array();
        cekHitam("post procMisc pakai config core");
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "[$cCtr] sub-postProcessor: $comName, gate: $srcGateName, initializing values <br>";
                $tmpOutParams[$cCtr] = array();
                if (isset($_SESSION[$cCode][$srcGateName]) && (sizeof($_SESSION[$cCode][$srcGateName]) > 0)) {
                    arrPrint($_SESSION[$cCode][$srcGateName]);
                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        //                            $id = $dSpec['id'];
                        $id = $xid;
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['loop'][$key] = $realValue;

                            }
                        }
                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {
                                cekHitam("gate: $srcGateName, dengan key $id");
                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['static'][$key] = $realValue;

                            }
                            if (!isset($subParams['static']["transaksi_id"])) {
                                $subParams['static']["transaksi_id"] = $insertID;
                            }
                            if (!isset($subParams['static']["transaksi_no"])) {
                                $subParams['static']["transaksi_no"] = $insertNum;
                            }
                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            if (isset($_SESSION[$cCode]['revert']['postProc']['detail'])) {
                                $subParams['static']["reverted_target"] = $_SESSION[$cCode]['main']['pihakExternID'];
                            }

                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }

                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr][] = $subParams;
                        }
                    }
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                if (isset($_SESSION[$cCode][$srcGateName])) {
                    echo "[$cCtr] sub-postProcessor: $comName, sending values <br>";

                    $mdlName = "Com" . ucfirst($comName);
                    $this->load->model("Coms/" . $mdlName);
                    //arrPrint($tmpOutParams[$cCtr]);
                    $m = new $mdlName();
                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    cekPink($this->db->last_query());
                }

            }
        }

        //endregion


        //
        //region ----------subcomponents GESER KE CLI

        //        $componentGate['detail'] = array();
        //        //arrPrint($paramForceFillers);
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        $componentConfig['detail'] = $iterator;
        //        if (sizeof($iterator) > 0) {
        //            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
        //            $filterNeeded = false;
        //            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                $filterNeeded = true;
        //            }
        //            foreach ($iterator as $cCtr => $tComSpec) {
        ////                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub-component: $comName, $srcGateName, initializing values <br>";
        //                $tmpOutParams[$cCtr] = array();
        //                foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
        //                    cekmerah("mengevaluasi $srcGateName..");
        //                    $comName = $tComSpec['comName'];
        //                    if (substr($comName, 0, 1) == "{") {
        //                        $comName = trim($comName, "{");
        //                        $comName = trim($comName, "}");
        //                        $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
        //                        $tComSpec['comName'] = $comName;
        //                        $iterator[$cCtr]['comName'] = $comName;
        //                    }
        //
        //                    $filterNeeded = false;
        //                    $mdlName = "Com" . ucfirst($comName);
        //                    if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                        $filterNeeded = true;
        //                    }
        //
        //
        //                    $subParams = array();
        //                    if (isset($tComSpec['loop'])) {
        //                        foreach ($tComSpec['loop'] as $key => $value) {
        //                            if (substr($key, 0, 1) == "{") {
        //                                $key = trim($key, "{");
        //                                $key = trim($key, "}");
        //                                $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$id][$key], $key);
        //                            }
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['loop'][$key] = $realValue;
        //                            cekKuning("LOOP: $key diisi dengan $realValue");
        //
        //                            if ($filterNeeded) {
        //                                if ($subParams['loop'][$key] == 0) {
        //                                    unset($subParams['loop'][$key]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (isset($tComSpec['static'])) {
        //                        foreach ($tComSpec['static'] as $key => $value) {
        //
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['static'][$key] = $realValue;
        //                            cekKuning("STATIC: $key diisi dengan $realValue");
        //
        //                        }
        //                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
        //                            foreach ($paramPatchers[$comName] as $k => $v) {
        //                                if (!isset($subParams['static'][$k])) {
        //                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                    cekOrange("fill :: $comName :: $k => " . $subParams['static'][$k]);
        //                                }
        //                            }
        //                        }
        //                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
        //                            //                            cekOrange("comName:: $comName");
        //                            $jenis = $_SESSION[$cCode]['main']['jenis'];
        //                            foreach ($paramForceFillers[$comName] as $k => $v) {
        //                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                cekOrange("fillforce :: $comName :: $k => " . $subParams['static'][$k]);
        //                            }
        //                        }
        //                        $subParams['static']["fulldate"] = date("Y-m-d");
        //                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
        //                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
        //                    }
        //                    cekHitam("cetak subParams");
        //                    arrPrint($subParams);
        //                    if (sizeof($subParams) > 0) {
        //                        if ($filterNeeded) {
        //                            if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
        //                                $tmpOutParams[$cCtr][] = $subParams;
        //                            }
        //                        }
        //                        else {
        //
        //                            $tmpOutParams[$cCtr][] = $subParams;
        //                        }
        //                    }
        //                }
        //
        //                $componentGate['detail'][$cCtr] = $subParams;
        //            }
        //
        //
        //            $it = 0;
        //            foreach ($iterator as $cCtr => $tComSpec) {
        //                $it++;
        //
        //
        //                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub component #$it: $comName, sending values <br>";
        //
        //                $mdlName = "Com" . ucfirst($comName);
        //                $this->load->model("Coms/" . $mdlName);
        //                $m = new $mdlName();
        //
        //
        //                if (sizeof($tmpOutParams[$cCtr]) > 0) {
        //                    $tobeExecuted = true;
        //                }
        //                else {
        //                    $tobeExecuted = false;
        //                }
        //
        //
        //                if ($tobeExecuted) {
        //                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                }
        //                else {
        //                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
        //                }
        //            }
        //        }
        //        else {
        //            //cekKuning("subcomponents is not set");
        //        }

        //endregion


        //region ----------components
        //<editor-fold desc="----------components">

        $componentGate['master'] = array();
        $componentConfig['master'] = array();
        if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
            $iterator = isset($_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master']) ? $_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master'] : array();
        }
        else {
            if (isset($_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'])) {
                $iterator = $_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'])) {
                $iterator = $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'];
            }
            else {
                $iterator = array();
            }
        }


        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('KOMPONEN...', 'head');</script>";
            $componentConfig['master'] = $iterator;

            $it = 0;
            //==filter nilai, jika NOL tidak dikirim, sesuai config==
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            foreach ($iterator as $cCtr => $tComSpec) {
                //                cekPink($tComSpec);
                //                mati_disini();
                $it++;
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "component #$it: $comName :: $srcGateName <br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            //                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                            $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$key], $key);
                        }
                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        if ($key != null) {
                            $tmpOutParams['loop'][$key] = $realValue;
                        }

                    }
                }
                //                cekBiru($tmpOutParams);
                //                mati_disini(__LINE__);
                if (isset($tComSpec['static'])) {
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;
                        cekHijau(":: NORMAL :: $key => $realValue ::");
                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        cekHijau(":: masuk ke PATCHER ::");
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            cekHijau(":: ada yang mau di-PATCHER ::");
                            arrPrint($tmpOutParams['static']);
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekHijau(":: PATCHER :: $key => $realValue ::");
                            }

                        }
                    }
                    else {
                        cekMerah(":: TIDAK TERMASUK PATCHER ::");
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            cekHijau(":: FORCEFILL :: $key => $realValue ::");
                        }
                    }
                    $tmpOutParams['static']["urut"] = $cCtr;
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //===filter value nol, jika harus difilter
                $tobeExecuted = true;

                if (in_array($mdlName, $compValidators)) {

                    $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                    if (sizeof($loopParams) > 0) {
                        foreach ($loopParams as $key => $val) {
                            cekmerah("$comName : $key = $val ");
                            if ($val == 0) {
                                unset($tmpOutParams['loop'][$key]);
                            }
                        }
                    }
                    if (sizeof($tmpOutParams['loop']) < 1) {
                        $tobeExecuted = false;
                    }

                }


                if ($tobeExecuted) {
                    cekBiru("kiriman komponen $comName");
                    arrPrint($tmpOutParams);
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("komponem $comName tidak memenuhi syarat untuk ditulis");
                }

                $componentGate['master'][$cCtr] = $tmpOutParams;
            }
        }
        else {
            //cekKuning("components is not set");
        }


        //endregion


        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    if (isset($paymentSrcConfig['model'])) {
                        $mdlName = $paymentSrcConfig['model'];
                        $this->load->model("Mdls/$mdlName");
                        $pMdl = New $mdlName();
                        $pTmpMdl = $pMdl->lookupAll()->result();
                        $pTmpMdlResult = array();
                        if (sizeof($pTmpMdl) > 0) {
                            foreach ($pTmpMdl as $pTmpMdlSpec) {
                                $pTmpMdlResult[$pTmpMdlSpec->id] = $pTmpMdlSpec;
                            }
                        }
                    }
                    else {
                        $pTmpMdlResult = array();
                    }

                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        if (isset($externSrc['extern_label2'])) {
                            //cek ada isinya atau kosong
                            $cek = strlen($_SESSION[$cCode]['main'][$externSrc['extern_label2']]) > 4 ? "" : matiHere("jenis biaya tidak dikenali " . __LINE__);//
                        }
                        $arrPymSrc = array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],

                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],

                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',

                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

                            //                            "extern_label2" => isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "",
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",

                            "ppn" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_approved" => (isset($externSrc['ppn_approved']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_approved']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_approved']] : 0,
                            "ppn_sisa" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_status" => (isset($externSrc['ppn_status'])) ? $externSrc['ppn_status'] : 0,
                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                            "extern_date2" => (isset($externSrc['extern_date2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_date2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_date2']] : "",
                            "pph_23" => (isset($externSrc['pph_23']) && ($_SESSION[$cCode]['main'][$externSrc['pph_23']])) ? $_SESSION[$cCode]['main'][$externSrc['pph_23']] : "",

                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : "",
                            "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : "",
                            "ppn_pph_faktor" => (isset($externSrc['ppn_pph_faktor']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']] : "",
                            "extern_jenis" => (isset($externSrc['extern_jenis']) && ($_SESSION[$cCode]['main'][$externSrc['extern_jenis']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_jenis']] : "",
                            "extern_nilai3" => (isset($externSrc['extern_nilai3']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai3']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai3']] : "",
                            "extern_nilai4" => (isset($externSrc['extern_nilai4']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai4']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai4']] : "",
                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            //                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : "",
                            "payment_locked" => (isset($externSrc['payment_locked']) && ($_SESSION[$cCode]['main'][$externSrc['payment_locked']])) ? $_SESSION[$cCode]['main'][$externSrc['payment_locked']] : 0,
                            "cash_account" => (isset($externSrc['cash_account']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account']] : 0,
                            "cash_account_nama" => (isset($externSrc['cash_account_nama']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account_nama']] : 0,
                        );
                        $tr->writePaymentSrc($insertID, $arrPymSrc);

                    }


                    cekMerah($this->db->last_query());
                }
            }

        }
        else {
            cekMerah("TIDAK nulis paymentSrc");
        }

        //matiHere("hoopppp");
        //cek additional step
        $addPaymentSource = isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService']) ? $this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService'] : array();
        //        arrPrint($addPaymentSource);
        //endregion


        //
        //region nulis paymentAntiSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_antiSource");
        if (array_key_exists($stepCode, $paymentSources)) {
            cekMerah(":: starting PAYMENT ANTI SOURCE");
            $payConfigs = $paymentSources[$stepCode];
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    $tr->writePaymentAntiSrc($insertID, array(
                        "jenis" => $stepCode,
                        "target_jenis" => $paymentSrcConfig['jenisTarget'],
                        "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                        "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                        "nomer" => $tmpNomorNota2,
                        "label" => $paymentSrcConfig['label'],
                        "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                        "terbayar" => 0,
                        "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                        "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                        "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "dtime" => date("Y-m-d H:i:s"),
                        "fulldate" => date("Y-m-d"),
                    ));
                    //cekMerah($this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }
        //endregion

        //region nulis uangMukaSource
        /*dimatiin geser ke ComUangmukaSourceDetail karena ada di items.
        /*revisi tanggal 27 mei 2020 subject digeser ke vendor dari jenis transaksi misal uangmuka asuransi,uang muka pembelian ->uang muka.
         *
         */
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $uangMukaSources = $this->config->item("uang_muka");

        if (array_key_exists($stepCode, $uangMukaSources)) {
            cekMerah(":: starting UANG MUKA  SOURCE");
            //            matiHere();
            $uangMukaConfigs = isset($uangMukaSources[$stepCode][$stepNum]) ? $uangMukaSources[$stepCode][$stepNum] : array();
            if (sizeof($uangMukaConfigs) > 0) {
                $cekPreValue = "";
                $this->load->model("Mdls/MdlPaymentUangMuka");
                $l = new MdlPaymentUangMuka();
                foreach ($uangMukaConfigs as $uangMukaSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    //                    arrPrint($uangMukaSrcConfig);
                    $valueSrc = $uangMukaSrcConfig['valueSrc'];
                    $externSrc = $uangMukaSrcConfig['externSrc'];
                    $l->addFilter("extern_id='" . $_SESSION[$cCode]['main'][$externSrc['id']] . "'");
                    $l->addFilter("extern_label2='" . $externSrc['extLabel'] . "'");
                    $tmpUm = $l->lookupAll()->result();
                    //                    arrPrint($tmpUm);
                    if (sizeof($tmpUm) > 0) {
                        //update here broo
                        $preTagihan = $tmpUm[0]->tagihan;
                        $preSisa = $tmpUm[0]->sisa;

                        $newTahigan = $preTagihan + $_SESSION[$cCode]['main'][$valueSrc];
                        $newsisa = $preSisa + $_SESSION[$cCode]['main'][$valueSrc];
                        $update = array(
                            "tagihan" => $newTahigan,
                            "sisa" => $newsisa,
                        );
                        $where = array(
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        );
                        $tr->updateUangMukaSrc($where, $update);
                        cekHitam($this->db->last_query());
                    }
                    else {
                        //insertbaru brooo
                        $tr->writeUangMukaSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $uangMukaSrcConfig['jenisTarget'],
                            "reference_jenis" => $uangMukaSrcConfig['jenisSrc'],
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                            "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                            "nomer" => "",
                            "note" => "",
                            "label" => $uangMukaSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "extern_label2" => $externSrc['extLabel'],
                        ));
                    }
                    cekMerah($this->db->last_query());
                }
            }
            else {
                cekLime("not write uang muka");
            }

        }
        else {
            cekMerah("not write uang muka");
        }
        //endregion

        cekMerah("MULAI LAST_VALIDATE");
        $va->setJenisTr($this->jenisTr);
        $va->lastValidate($insertID);
        //        mati_disini("setelah lastValidate");


        cekKuning(":: mulai cek rek besar dan rek pembantu");
        $cabangID_validate = $this->session->login['cabang_id'];


        validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota2);
        validateJurnal($insertID, $componentConfig);
        validateAllBalances();


        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, $insertID);
        //==================================================================================================

        //==tampilkan receipt
        cekOrange("-- DONE --");

        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion


        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;

        // mati_disini(__FUNCTION__ . "  TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }

        if (isset($_SESSION["_TR_" . $origJenis])) {
            unset($_SESSION["_TR_" . $origJenis]);
        }

        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }

        //region feedback msg
        $this->session->errMsg = "transaction entry has been saved<br>";
        $nextNum = $nextProp["num"];
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextNum])) {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $this->session->errMsg .= "This entry needs to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['userGroup'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewIncomplete/" . $this->jenisTr;

        }
        else {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

        }
        $trBackClick = "location.href='$trBackLink'";
        //        $this->session->errMsg .= "<br><a href='javascript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
        //endregion

        if (isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum])) {
            $printLocation = $this->configLayout[$this->jenisTr]['printLocation'];
            $printException = isset($this->configLayout[$this->jenisTr]['printException'][$stepNum]) ? "/" . $this->configLayout[$this->jenisTr]['printException'][$stepNum] : "";
            $printSettings = isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum]) ? $this->configLayout[$this->jenisTr]['allowPrint'][$stepNum] : array();
            if (isset($printSettings['size'])) {
                switch ($printSettings['size']) {
                    case "normal":
                        //                        cekkuning("size: NORMAL");
                        echo "<script>";
                        echo "top.popBig('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/" . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    case "small":
                        //                        cekkuning("size: SMALL");
                        echo "<script>";
                        echo "top.popSmall('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/" . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    default:
                        //                        cekkuning("size: UNKNOWN");
                        break;
                }
            }
            else {
                $arrAlert = array(
                    "type" => "success",
                    "title" => "Transaction saved",
                    //                        "html" => "your order has been saved and ready to process",
                    "html" => $this->session->errMsg,
                    "timer" => "1500",
                    "showConfirmButton" => false,
                    "allowOutsideClick" => false,
                );
                echo swalAlert($arrAlert);
                echo "<script>topReload(1500)</script>";
                echo topReload();
                echo "</script>";
                unset($this->session->errMsg);
            }

        }
        else {
            $arrAlert = array(
                "type" => "success",
                "title" => "Transaction saved",
                //                        "html" => "your order has been saved and ready to process",
                "html" => $this->session->errMsg,
                "timer" => "1500",
                "showConfirmButton" => false,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            echo "<script>topReload(1500)</script>";
            echo topReload();
            echo "</script>";
            unset($this->session->errMsg);
        }

    }

    public function doRevert()
    {
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }


        $transaksiID_reference = $no = $this->uri->segment(5);
        $jenisTr_con = $jenisTr = $this->uri->segment(4);
        $masterTargetStepNum_con = $masterTargetStepNum = $this->uri->segment(6);
        $childTargetStepNum_con = $childTargetStepNum = $this->uri->segment(7);
        $stepNumCurrent_son = $stepNumCurrent = $this->uri->segment(8);
        $jenisTarget = $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent_son]["target"];
        // matiHEre($jenisTarget);
        $cCode = "_TR_" . $jenisTr;

        $rejectException = $this->config->item('heTransaksi_rejectException') != NULL ? $this->config->item('heTransaksi_rejectException') : array();
        $referenceRevertConfigs = isset($this->configUi[$jenisTr]['referenceRevert']) ? $this->configUi[$jenisTr]['referenceRevert'] : array();
        $prepConfigs = null != $this->config->item('hePreProcessors') ? $this->config->item('hePreProcessors') : array();
        $postConfigs = null != $this->config->item('hePostProcessors') ? $this->config->item('hePostProcessors') : array();

        //region swap from registry, transaksi yang dibuka saat ini
        $tr = new MdlTransaksi();
        $tmpReg = $tr->lookupDataRegistriesByMasterID($no)->result();
        cekmerah($this->db->last_query());
        if (sizeof($tmpReg) > 0) {
            foreach ($tmpReg as $row) {
                foreach ($row as $key_reg => $val_reg) {
                    if ($key_reg != "transaksi_id") {
                        $var = $key_reg;
                        $$var = unserialize(base64_decode($val_reg));
                    }
                }
            }
        }
        //endregion

        //region swap from main transaksi, transaksi yang dibuka saat ini
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("id='$no'");
        $tmpTr = $tr->lookupMainTransaksi()->result();
        cekOrange($this->db->last_query());
        $currentInsertID = $insertID = $tmpTr[0]->id;
        $currentMasterID = $tmpTr[0]->id_master;
        $transaksiNomer_reference = $currentNomer = $insertNum = $tmpTr[0]->nomer;
        $thisStepNumber = $tmpTr[0]->step_number;
        //endregion


        echo "no saat ini : $no<br>";
        echo "no reference : " . $tmpTr[0]->id_top . "<br>";
        echo "nomer reference : " . $tmpTr[0]->nomer . "<br>";
        echo "masterTargetStepNum: $masterTargetStepNum<br>";
        echo "childTargetStepNum: $childTargetStepNum<br>";
        echo "stepNumCurrent: $stepNumCurrent<br>";


        $this->db->trans_start();
        //
        // jika ada connecting antar-cabang...
        cekHitam("jenisTr -> $jenisTr");
        cekhitam("checking dulu connecting antar cabang... (connecto transaksi_ui)");
        $connector = isset($this->configUi[$jenisTr]['connectTo']) ? $this->configUi[$jenisTr]['connectTo'] : "";
        $mongListUpadte = array();
        $mongoList = array();
        if (strlen($connector) > 0) {
            cekUngu(":: ADA CONNECTING :: connector-> $connector ::");
            cekBiru("bila ada normal, yang membatalkan pihak source/sumber/asal...");


            //region update step2an di masternya
            $nextMasterStep = $stepNumCurrent;
            $nextProp = array(
                "num" => $nextMasterStep,
                "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
            );
            echo "nextMasterStep: $nextMasterStep<br>";
            arrPrint($nextProp);

            //update masternya, transaksi TOP
            if ($tmpTr[0]->id_top != $no) {
                $arrData = array(
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "next_step_num" => $nextProp['num'],
                    "step_current" => $masterTargetStepNum,
                    "step_number" => $masterTargetStepNum,
                );
                $arrData_detail = array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    "sub_step_current" => $masterTargetStepNum,
                    "sub_step_number" => $masterTargetStepNum,
                    //                "valid_qty" => $new_valid_qty,
                );
            }
            else {
                $arrData = array(
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "next_step_num" => $nextProp['num'],
                    "step_current" => $masterTargetStepNum,
                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['id'],
                    "cancel_id" => $this->session->login['nama'],
                );
                $arrData_detail = array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                );
            }
            $tr = new MdlTransaksi();
            $dupState = $tr->updateData(array(
                //                "id" => $no,
                "id" => $tmpTr[0]->id_top,
            ), $arrData) or die("Failed to update tr next-state!");

            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "id" => $tmpTr[0]->id_top,
                ),
                "value" => $arrData,
            );
            cekHijau("UPDATE transaksi step sebelumnya...");
            cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion

            //region update step transaksi 1 step sebelumnya (detail)
            if (sizeof($tmpTr) > 0) {
                $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                arrPrint($arrPrevID);
                foreach ($arrPrevID as $prevID) {
                    $tb = new MdlTransaksi();
                    $tb->setFilters(array());
                    $dupState = $tb->updateData(array(
                        "id" => $prevID,
                    ), array(
                        "status_4" => "11",
                    )) or die("Failed to update tr next-state!");

                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $prevID,
                        ),
                        "value" => array("status_4" => "11",),
                    );
                    cekKuning("UPDATE transaksi 1 step sebelumnya...");
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($prevID)->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $items)) {
                                $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                    $new_valid_qty = $rsltSpec->valid_qty;
                                    //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                }
                                else {
                                    $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                }
                                //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                $arrData_detail["valid_qty"] = $new_valid_qty;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $prevID,
                                    "produk_id" => $rsltSpec->produk_id,
                                ), $arrData_detail) or die("Failed to update tr next-state!");
                                $mongListUpadte['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $prevID,
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                                cekKuning("UPDATE transaksi data...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            }
                        }
                    }

                }
            }
            //endregion

            //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
            // cekUngu($tmpTr[0]->id_top);
            // cekUngu("$no");
            // if ($tmpTr[0]->id_top != $no) {
            $tp = new MdlTransaksi();
            $dupState = $tp->updateData(array(
                "id" => $no,
                "step_number" => $stepNumCurrent,
            ), array(
                "step_number" => $childTargetStepNum,
                "trash_4" => "1",
                "cancel_dtime" => date("Y-m-d H:i:s"),
                "cancel_name" => $this->session->login['nama'],
                "cancel_id" => $this->session->login['id'],

            )) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "id" => $no,
                    "step_number" => $stepNumCurrent,
                ),
                "value" => array(
                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['nama'],
                    "cancel_id" => $this->session->login['id']),
            );
            cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            $to = new MdlTransaksi();
            $to->setFilters(array());
            $to->setTableName($to->getTableNames()['detail']);
            $dupState = $to->updateData(array(
                "transaksi_id" => $no,
            ), array(
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "next_substep_num" => $nextProp['num'],
                //            "sub_step_current" => 0,
                "sub_step_number" => 0,
            )) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "transaksi_id" => $no,
                ),
                "value" => array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                ),
            );
            cekLime("UPDATE transaksi data...");
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            // }
            //endregion

            //region sesuaikan signature untuk cloningan, ikut minus
            //        $dwsign = $tr->writeSignature($no, array(
            $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                "prev_id" => $no,
                "nomer" => "rejection",
                "step_number" => $childTargetStepNum, // ini minus step number
                "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                "oleh_id" => $this->session->login['id'],
                "oleh_nama" => $this->session->login['nama'],
                "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                //            "transaksi_id" => $no,
            )) or die("Failed to write signature");
            $mongoList['sign'][] = $dwsign;
            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion

            // region netralisasi payment source
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $tr->addFilter("sisa>0");
            $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
            cekBiru($this->db->last_query());
            if (sizeof($paymentSrc) > 0) {
                //            arrPrint($paymentSrc);
                foreach ($paymentSrc as $pSpec) {
                    if ($pSpec->terbayar == 0) {
                        $where = array(
                            "id" => $pSpec->id,
                            "transaksi_id" => $pSpec->transaksi_id,
                        );
                        $data = array(
                            "sisa" => 0,
                            "returned" => $pSpec->sisa,
                            "sisa_valas" => 0,
                            "returned_valas" => $pSpec->sisa_valas,
                        );

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->updatePaymentSrc($where, $data);
                        cekUngu(":: mereject payment source bila ada...");
                        cekUngu($this->db->last_query());
                    }
                    else {
                        mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                    }
                }
            }
            else {
                cekBiru(":: tidak ada payment source... ::");
            }
            // endregion netralisasi payment source

            // region netralisasi extended step
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $exTmp = $tr->lookupExtStepByTrID($no);
            if (sizeof($exTmp) > 0) {
                foreach ($exTmp as $exSpec) {

                    $tra = New MdlTransaksi();
                    $tra->setFilters(array());
                    $tra->rejectExtStepByID($exSpec['id']);
                    $mongListUpadte['update']['extra'][] = array(
                        "where" => array(
                            "id" => $exSpec['id'],
                        ),
                        "value" => array(
                            "state" => "-1",
                        ),
                    );
                    cekUngu(":: mereject extended step bila ada...");
                    cekUngu($this->db->last_query());
                }
            }
            else {
                cekBiru(":: tidak ada extended step... ::");
            }

            // endregion netralisasi extended step

            //==entry point
            if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {

                if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                    if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                        $masterID = $currentMasterID;
                        $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        $tCodeTargetJenisTransaksi = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        $modul_transaksi = $this->modul;
                        cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                        if ($connecTo == NULL) {
                            mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                        }
                        $oldCode = $cCode;
                        $cCode = "_TR_" . $connecTo;
                        $_SESSION[$cCode] = array(
                            'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                            'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                            'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                        );
                        // masuk ke gerbang TableInMaster, tabel transaksi
                        $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "trash_4" => 1,
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                            "deskripsi" => "rejection",

                        );
                        // masuk ke gerbang main
                        $masterReplacersO = array(
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                        );
                        foreach ($masterReplacersO as $key => $val) {
                            $_SESSION[$cCode]['main'][$key] = $val;
                        }
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }

                        //region penomoran receipt
                        $this->load->model("CustomCounter");
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $cn->setModul($modul_transaksi);
                        $cn->setStepCode($tCodeTargetJenisTransaksi);
                        $counterForNumber = array($this->configCore[$this->jenisTr]['formatNotaEdit']);
                        if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['countersEdit'])) {
                            die(__LINE__ . " Used number should be registered in 'counters' config as well");
                        }
                        echo "<div style='background:#ff7766;'>";
                        foreach ($counterForNumber as $i => $cRawParams) {
                            $cParams = explode("|", $cRawParams);
                            $cValues = array();
                            foreach ($cParams as $param) {
                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            }
                            $cRawValues = implode("|", $cValues[$i]);
                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                        }
                        echo "</div style='background:#ff7766;'>";

                        $stepNumber = 1;
                        $tmpNomorNota = $paramSpec['paramString'];
                        $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                        $nextProp = array(
                            "num" => 0,
                            "code" => "",
                            "label" => "",
                            "groupID" => "",
                        );
                        //endregion

                        //region dynamic counters
                        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $cn->setModul($modul_transaksi);
                        $cn->setStepCode($tCodeTargetJenisTransaksi);
                        $configCustomParams = $this->configCore[$this->jenisTr]['countersEdit'];
                        arrPrintHijau($configCustomParams);
                        $configCustomParams[] = "stepCode";
                        //arrPrint($configCustomParams);
                        if (sizeof($configCustomParams) > 0) {
                            $cContent = array();
                            foreach ($configCustomParams as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                switch ($paramSpec['id']) {
                                    case 0: //===counter type is new
                                        $paramKeyRaw = print_r($cParams, true);
                                        $paramValuesRaw = print_r($cValues[$i], true);
                                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                        break;
                                    default: //===counter to be updated
                                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                        break;
                                }
                                //echo "<hr>";
                            }
                        }
                        $appliedCounters = base64_encode(serialize($cContent));
                        $appliedCounters_inText = print_r($cContent, true);
                        //mati_disini();
//arrPrintPink($cContent);
                        //
                        //region addition on master


                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                            "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "step_number" => 1,
                            "step_current" => 1,
                            "next_step_num" => $nextProp['num'],
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "tail_number" => 1,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        //endregion

                        //
                        //region addition on detail
                        $addSubValues = array(
                            "sub_step_number" => 1,
                            "sub_step_current" => 1,
                            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "next_substep_num" => $nextProp['num'],
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "sub_tail_number" => 1,
                            "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                            foreach ($addSubValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                            }
                        }
                        //endregion
                        // </editor-fold>
                        //endregion

                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $masterReplacers = array(
                            "nomer" => $tmpNomorNota,
                            "nomer2" => $tmpNomorNotaAlias,
                            "counters" => $appliedCounters,
                            "counters_intext" => $appliedCounters_inText,
                        );
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $detailReplacers = array(
                            "sub_step_avail" => 1,
                            "sub_step_current" => 1,
                            "sub_step_number" => 1,
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                }
                            }
                        }
                        $itemsReplacers = array(
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                            foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                }
                            }
                        }

                        //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                        if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;
                            $_SESSION[$cCode]['tableIn_master']['cli'] = 1;
                            $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                            $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                            $tr = new MdlTransaksi();
                            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                            cekHitam("[$insertID] :: " . $this->db->last_query());
                            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                            if ($insertID < 1) {
                                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            $mongoList['main'] = array($insertID, $epID);
                            //==transaksi_id dan nomor nota diinject kan ke gate utama
                            $injectors = array(
                                "transaksi_id" => $insertID,
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                            );
                            $arrInjectorsTarget = array(
                                "items",
                                "items2_sum",
                                "rsltItems",
                            );
                            foreach ($injectors as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                                foreach ($arrInjectorsTarget as $target) {
                                    if (isset($_SESSION[$cCode][$target])) {
                                        foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                            $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                            if (isset($_SESSION[$cCode][$target][$id])) {
                                                $_SESSION[$cCode][$target][$id][$key] = $val;
                                            }
                                        }
                                    }
                                }
                            }

                            //===signature
                            $dwsign = $tr->writeSignature($insertID, array(
                                "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                "step_number" => 1,
                                "step_code" => $connecTo,
                                "step_name" => $this->configUiJenis["connectToReject"][1]["label"],
                                "group_code" => "",
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                "transaksi_id" => $masterID,
                                "deskripsi" => "edit transaksi",
                                "cabang_id" => $this->session->login['cabang_id'],
                                "cabang_nama" => $this->session->login['cabang_nama'],
                                "current_transaksi_id" => $masterID,
                                "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                            )) or die("Failed to write signature");
                            showLast_query("kuning");
                            $mongoList['sign'][] = $dwsign;
                            $idHis = array(
                                $stepNumber => array(
                                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                    "step" => $stepNumber,
                                    "trID" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                    "counters" => $appliedCounters,
                                    "counters_intext" => $appliedCounters_inText,
                                ),
                            );
                            $idHis_blob = blobEncode($idHis);
                            $idHis_intext = print_r($idHis, true);
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $insertID), array(
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],

                                //===references
//                            "id_master" => $insertID,
                                "id_master" => $masterID,// milik transkasiID yang diedit
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,

                            )) or die("Failed to update tr next-state!");
                            cekHijau($this->db->last_query());

                            $addValues = array(
                                //===references
                                "id_master" => $insertID,
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                            $inserMainValues = array();
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                //matiHEre("hooppp");
                                $inserMainValues = array();
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                    if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                        $dd = $tr->writeMainValues($insertID, array(
                                            "key" => $key,
                                            "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                        ));

                                        $inserMainValues[] = $dd;
                                        $mongoList['mainValues'][] = $dd;
                                    }
                                }
                            }

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }

                        }
                        if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                            $inserMainValues = array();
                            foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                                $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                $inserMainValues[] = $dd;
                                $mongoList['mainValues'][] = $dd;
                            }

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                            foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                //                    cekkuning("making a clone for input key $key / $val");
                                //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                //                    $replacers=array(
                                //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                //                    );
                                //                    foreach($replacers as $key=>$val){
                                //                        $tmpTableIn[$key]=$val;
                                //                    }
                                //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                            foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                            foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                $tr->writeMainApplets($insertID, array(
                                    "mdl_name" => $amdl,
                                    "key" => $aSpec['key'],
                                    "label" => $aSpec['labelValue'],
                                    "description" => $aSpec['description'],
                                ));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                            foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                $tr->writeMainElements($insertID, array(
                                    "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                    "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                    "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                    "name" => $aSpec['name'],
                                    "label" => $aSpec['label'],
                                    "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                    "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                ));
                                //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

                            $insertIDs = array();
                            $insertDeIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                if ($insertDetailID < 1) {
                                    die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                                }
                                else {
                                    $insertIDs[] = $insertDetailID;
                                    $insertDeIDs[$insertID][] = $insertDetailID;
                                    $mongoList['detail'][] = $insertDetailID;
                                }
                                if ($epID != 999) {
                                    $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                                    if ($insertEpID < 1) {
                                        die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                                    }
                                    else {
                                        $insertIDs[] = $insertEpID;
                                        $insertDeIDs[$epID][] = $insertEpID;
                                        $mongoList['detail'][] = $insertEpID;
                                    }
                                }
                                cekUngu($this->db->last_query());
                            }


                            if (sizeof($insertIDs) == 0) {
                                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                            }
                            else {
                                $indexing_details = array();
                                foreach ($insertDeIDs as $key => $numb) {
                                    $indexing_details[$key] = $numb;
                                }

                                foreach ($indexing_details as $k => $arrID) {
                                    $arrBlob = blobEncode($arrID);
                                    $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                    cekOrange($this->db->last_query());
                                }
                            }
                        }
                        else {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                                if ($epID != 999) {
                                    $dd = $tr->writeDetailEntries($epID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detail'][] = $dd;
                                }
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $dd;
                                $mongoList['detil'][] = $dd;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detil'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                        if (isset($_SESSION[$cCode]['tableIn_detail'][$pID])) {
                                            $dd = $tr->writeDetailValues($insertID, array(
                                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                                "produk_id" => $pID,
                                                "key" => $key,
                                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : "0",
                                            ));
                                            $insertIDs[$pID][] = $dd;
                                            $mongoList['detailValues'][] = $dd;

                                        }
                                    }
                                }
                            }

                            if (sizeof($insertIDs) > 0) {
                                $arrBlob = blobEncode($insertIDs);
                                $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                                    $insertIDs = array();
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                        $dd = $tr->writeDetailValues($insertID, array(
                                            "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                            "produk_id" => $pID,
                                            "key" => $key,
                                            "value" => $dSpec[$src],
                                        ));
                                        $insertIDs[] = $dd;
                                        $mongoList['detailValues'][] = $dd;
                                    }
                                }
                            }
                        }
                        //endregion

                        $baseRegistries = array(
                            'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                            'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                            'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                            'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                            'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                            'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                            //----
                            'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                            'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                            //----
                        );
                        $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                        showLast_query("hijau");
                        cekHijau("SELESAI menjalankan EDITOR...");
                    }
                }
                else {
                    $tableIn_master['trash_4'] = 1;
                    $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                    $tableIn_master['cancel_name'] = $this->session->login['nama'];
                    $tableIn_master['cancel_id'] = $this->session->login['id'];
                    $tableIn_master['deskripsi'] = "rejection";
                    $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                    $mongoList['main'][] = $epID;
                    if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                        $insertIDs = array();
                        foreach ($tableIn_detail as $dSpec) {
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                            }
                        }
                    }
                }

            }
//            mati_disini(__LINE__);
            $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

            //===if rollback is needed
            //rollback preproc, master
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                //            cekbiru("ada config pre-proc master $stepNumCurrent");
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                //            arrprint($iterator);
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    cekbiru("ada iterator pre-proc master");
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                        echo "reverse master-preproc: $comName, initializing values <br>";
                        $tmpOutParams[$cCtr] = array();


                        $subParams = array();

                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                $subParams['static'][$key] = $realValue;

                            }

                            if (array_key_exists($oriComName, $prepConfigs)) {
                                if (sizeof($prepConfigs[$oriComName]) > 0) {
                                    foreach ($prepConfigs[$oriComName] as $key => $src) {
                                        $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                    }
                                }
                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                $subParams['static']["transaksi_id"] = $no;
                            }


                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                        }
                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr] = $subParams;
                        }


                        $mdlName = "Pre" . ucfirst($comName);
                        $this->load->model("Preprocs/" . $mdlName);
                        $m = new $mdlName($resultParams);


                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                            $tobeExecuted = true;
                        }
                        else {
                            $tobeExecuted = false;
                        }

                        if ($tobeExecuted) {
                            arrprint($tmpOutParams[$cCtr]);
                            $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();


                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
            }
            //rollback preproc, detail
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                //            arrprint($iterator);
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        echo "reverse preproc (detail): $comName, initializing values <br>";
                        foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                            $tmpOutParams[$cCtr] = array();
                            //                        $id = $dSpec['id'];
                            $id = $xid;
                            $subParams = array();

                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                    $subParams['static'][$key] = $realValue;

                                }

                                if (array_key_exists($oriComName, $prepConfigs)) {
                                    cekhitam("terdapat di dalam prepConfig");
                                    if (sizeof($prepConfigs[$oriComName]) > 0) {
                                        foreach ($prepConfigs[$oriComName] as $key => $src) {
                                            $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                        }
                                    }
                                }
                                else {
                                    cekhitam("TIDAK terdapat di dalam prepConfig");
                                }
                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $no;
                                }


                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                            }

                            if (sizeof($subParams) > 0) {

                                $tmpOutParams[$cCtr][] = $subParams;
                            }


                            $comName = $tComSpec['comName'] . "_reverse";
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                            echo "sub preproc #$it: $comName, sending values <br>";

                            $mdlName = "Pre" . ucfirst($comName);
                            $this->load->model("Preprocs/" . $mdlName);
                            $m = new $mdlName($resultParams);


                            if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                $tobeExecuted = true;
                            }
                            else {
                                $tobeExecuted = false;
                            }

                            if ($tobeExecuted) {

                                //                            arrprint($tmpOutParams[$cCtr]);

                                $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $gotParams = $m->exec();

                                //                            cekbiru("gotparams");
                                //                            arrprint($gotParams);

                            }
                            else {
                                cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                            }

                        }
                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
            }
            //rollback postproc, master
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                //            cekbiru("ada config pre-proc master $stepNumCurrent");
                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        echo "rollback main post-processor: $comName<br>";

                        $dSpec = $_SESSION[$cCode][$srcGateName];
                        $tmpOutParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                $tmpOutParams['loop'][$key] = $realValue;

                            }
                        }
                        if (isset($tComSpec['static'])) {
                            //cekHere("DISINI OIII");
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                $tmpOutParams['static'][$key] = $realValue;

                            }
                            if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                $tmpOutParams['static']["transaksi_id"] = $insertID;
                            }
                            if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                $tmpOutParams['static']["transaksi_no"] = $insertNum;
                            }

                            $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                            $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];


                        }
                        if (isset($tComSpec['static2'])) {
                            //cekHere("DISINI OIII");
                            foreach ($tComSpec['static2'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                $tmpOutParams['static2'][$key] = $realValue;

                            }
                            if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                $tmpOutParams['static2']["transaksi_id"] = $insertID;
                            }
                            if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                            }

                            $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                            $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                            $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                        }


                        if (array_key_exists($oriComName, $postConfigs)) {
                            if (sizeof($postConfigs[$oriComName]) > 0) {
                                foreach ($postConfigs[$oriComName] as $key) {
                                    $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                    cekbiru("oldVal: $oldVal");
                                    $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                    cekHijau("newVal: $newVal");
                                    //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                    $tmpOutParams['static'][$key] = $newVal;
                                }
                            }
                        }

                        //lgShowError("Ada kesalahan",);
                        $mdlName = "Com" . ucfirst($comName);
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();

                        cekBiru("kiriman rollback main-postproc $comName");
                        arrPrint($tmpOutParams);
                        $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
            }
            //rollback postproc, detail
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                //------
                cekHitam(":: tambahan bila reject step 1 ::");
                if (isset($this->configUi[$jenisTr]["lockerCheck"]) && ($this->configUi[$jenisTr]["lockerCheck"] == true) && ($stepNumCurrent == 1)) {
                    cekHitam(":: kembalikan locker stok ke active ::");
                    //                    $iterator[98] = array(
                    //                        "comName" => "LockerStock",
                    //                        "loop" => array(),
                    //                        "static" => array
                    //                        (
                    //                            "cabang_id" => "placeID",
                    //                            "jenis" => ".produk",
                    //                            "state" => ".hold",
                    //                            "jumlah" => "qty",
                    //                            "produk_id" => "id",
                    //                            "nama" => "name",
                    //                            "satuan" => "satuan",
                    //                            "oleh_id" => "olehID",
                    //                            "oleh_nama" => "olehName",
                    //                            "transaksi_id" => ".0",
                    //                            "nomer" => ".0",
                    //                            "gudang_id" => "gudangID",
                    //                        ),
                    //                        "reversable" => 1,
                    //                        "srcGateName" => "items",
                    //                        "srcRawGateName" => "items",
                    //                    );
                    //                    $iterator[99] = array(
                    //                        "comName" => "LockerStock",
                    //                        "loop" => array(),
                    //                        "static" => array
                    //                        (
                    //                            "cabang_id" => "placeID",
                    //                            "jenis" => ".produk",
                    //                            "state" => ".active",
                    //                            "jumlah" => "-qty",
                    //                            "produk_id" => "id",
                    //                            "nama" => "name",
                    //                            "satuan" => "satuan",
                    //                            "oleh_id" => ".0",
                    //                            "oleh_nama" => ".0",
                    //                            "transaksi_id" => ".0",
                    //                            "nomer" => ".0",
                    //                            "gudang_id" => "gudangID",
                    //                        ),
                    //                        "reversable" => 1,
                    //                        "srcGateName" => "items",
                    //                        "srcRawGateName" => "items",
                    //                    );
                    $iteratorAdd = array();
                    foreach ($iterator as $cCtr => $tComSpec) {
                        if (isset($tComSpec['static']['state']) && ($tComSpec['static']['state'] == '.hold')) {
                            if (isset($tComSpec['static']['oleh_id']) && ($tComSpec['static']['oleh_id'] != '.0')) {
                                // bila state == .hold dan oleh_id != .0, maka dibuatkan ::
                                // HOLD, +QTY, oleh_id dan ACTIVE, -QTY
                                $tComSpecAddHold = $tComSpec;
                                $tComSpecAddActive = $tComSpec;
                                $staticReplaceHold = array(
                                    "jumlah" => "qty",
                                    "transaksi_no" => ".0",
                                );
                                $staticReplaceActive = array(
                                    "jumlah" => "-qty",
                                    "transaksi_id" => ".0",
                                    "nomer" => ".0",
                                    "state" => ".active",
                                    "oleh_id" => ".0",
                                    "oleh_nama" => "",
                                    "transaksi_no" => ".0",
                                );
                                foreach ($staticReplaceHold as $k_rpc => $v_rpc) {
                                    $tComSpecAddHold['static'][$k_rpc] = $v_rpc;
                                }
                                foreach ($staticReplaceActive as $k_rpc => $v_rpc) {
                                    $tComSpecAddActive['static'][$k_rpc] = $v_rpc;
                                }

                                $iteratorAdd[101] = $tComSpecAddHold; // postprocc hold by orang, no trID
                                $iteratorAdd[102] = $tComSpecAddActive; // postprocc active, no orang, no trID
                            }
                        }
                        // if (isset($tComSpec['static']['state']) && ($tComSpec['static']['state'] == '.hold')) {
                        //     // if (isset($tComSpec['static']['transaksi_id']) && ($tComSpec['static']['transaksi_id'] != $transaksiID_reference)) {
                        //     //     // bila state == .hold dan oleh_id != .0, maka dibuatkan ::
                        //     //     // HOLD, +QTY, oleh_id dan ACTIVE, -QTY
                        //     //     $tComSpecAddHold = $tComSpec;
                        //     //     $tComSpecAddActive = $tComSpec;
                        //     //     $staticReplaceHold = array(
                        //     //         "jumlah" => "-qty",
                        //     //         "transaksi_no" => "$transaksiID_reference",
                        //     //         "transaksi_id" => "$transaksiID_reference",
                        //     //     );
                        //     //     // $staticReplaceActive = array(
                        //     //     //     "jumlah" => "-qty",
                        //     //     //     "transaksi_id" => ".0",
                        //     //     //     "nomer" => ".0",
                        //     //     //     "state" => ".active",
                        //     //     //     "oleh_id" => ".0",
                        //     //     //     "oleh_nama" => "",
                        //     //     //     "transaksi_no" => ".0",
                        //     //     // );
                        //     //     foreach ($staticReplaceHold as $k_rpc => $v_rpc) {
                        //     //         $tComSpecAddHold['static'][$k_rpc] = $v_rpc;
                        //     //     }
                        //     //     // foreach ($staticReplaceActive as $k_rpc => $v_rpc) {
                        //     //     //     $tComSpecAddActive['static'][$k_rpc] = $v_rpc;
                        //     //     // }
                        //     //
                        //     //     $iteratorAdd[103] = $tComSpecAddHold; // postprocc hold by orang, no trID
                        //     //     // $iteratorAdd[102] = $tComSpecAddActive; // postprocc active, no orang, no trID
                        //     // }
                        // }
                    }
                    if (sizeof($iteratorAdd) > 0) {
                        foreach ($iteratorAdd as $ii => $spec) {
                            $iterator[$ii] = $spec;
                        }
                    }
                }
                //------
                arrPrintPink($iterator);
//                                mati_disini(__LINE__);
                $tmpOutParams = array();
                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        echo "rollback sub-postProcessor: $comName, initializing values <br>";
//                        arrPrintWebs($_SESSION[$cCode][$srcGateName]);
                        $tmpOutParams[$cCtr] = array();
                        foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                            $subParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                    $subParams['loop'][$key] = $realValue;

                                }
                            }
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {
//                                    if ($key == "transaksi_id" && $value == ".0") {
////                                        matiHEre("$key || $value");
//                                    }
//
                                    if ($key == "transaksi_id" && $value == "transaksi_id") {
//                                        cekUngu(":: $key => $value ::");
                                        $value = "." . $transaksiID_reference;
                                    }
                                    if ($key == "nomer" && $value == "nomer") {
//                                        cekUngu(":: $key => $value ::");
                                        $value = "." . $transaksiNomer_reference;
                                    }

                                    // matiHere();
                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                    $subParams['static'][$key] = $realValue;
                                    //                                cekBiru("$key diisi dengan $realValue");

                                }

                                if (array_key_exists($oriComName, $postConfigs)) {
                                    //                                cekhitam("terdapat di dalam postConfig");
                                    if (sizeof($postConfigs[$oriComName]) > 0) {
                                        foreach ($postConfigs[$oriComName] as $key) {
                                            //                                        $replVal=makeValue($src,$_SESSION[$cCode][$srcGateName][$cnt],$_SESSION[$cCode][$srcGateName][$cnt],0);
                                            //                                        cekbiru("$key akan direplace dengan nilai $replVal");
                                            //                                        $subParams['static'][$key]=$replVal;

                                            $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                            cekbiru("$key oldVal2: $oldVal");
                                            $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                            cekHijau("$key newVal2: $newVal");
                                            $subParams['static'][$key] = $newVal;
                                            //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                            //                                        $tmpOutParams['static'][$key]=$newVal;
                                        }
                                    }
                                }
                                else {
                                    //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                }

                                //                            $subParams['static']["transaksi_id"] = $insertID;
//                                if ($subParams['static']["transaksi_id"] == ".0") {
//                                    if (!isset($subParams['static']["transaksi_id"])) {
//                                        $subParams['static']["transaksi_id"] = $no;
//                                    }
//                                    if (!isset($subParams['static']["transaksi_no"])) {
//                                        $subParams['static']["transaksi_no"] = $no;
//                                    }
//                                }
//                                else {
//                                    if (!isset($subParams['static']["transaksi_id"])) {
//                                        $subParams['static']["transaksi_id"] = $transaksiID_reference;
//                                    }
//                                    if (!isset($subParams['static']["transaksi_no"])) {
//                                        $subParams['static']["transaksi_no"] = $transaksiID_reference;
//                                    }
//                                }

                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = "rollback of $no";
                                $subParams['static']["rejection"] = true;
                            }


                            if (sizeof($subParams) > 0) {
                                $tmpOutParams[$cCtr][] = $subParams;
                            }
                        }
                    }
                    arrPrintKuning($tmpOutParams);
//                    arrPrintKuning($iterator);
//                    matiHEre();
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        echo "sub-postProcessor: $comName, sending values <br>";

                        $mdlName = "Com" . ucfirst($comName);
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();


                        // cekBiru("kiriman rollback detail-postproc $comName");
                        arrPrintWebs($tmpOutParams[$cCtr]);
                        $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        cekHitam($this->db->last_query());
                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
            }


            //region cancel transaksi yang stanby di pihak ke-2
            $tb = new MdlTransaksi();
            $tb->setFilters(array());
            $tb->addFilter("id_master='" . $tmpTr[0]->id_master . "'");
            $tb->addFilter("jenis_master='$connector'");
            $trTmp = $tb->lookupAll()->result();
            if (sizeof($trTmp) > 0) {

                $connectorID = $trTmp[0]->id;
                if ($connectorID > 0) {

                    $tb = new MdlTransaksi();
                    $tb->setFilters(array());
                    $dupState = $tb->updateData(array(
                        "id" => $connectorID,
                    ), array(
                        "status_4" => "11",
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i:s"),
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_id" => $this->session->login['id'],

                    )) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $connectorID,
                        ),
                        "value" => array(
                            "status_4" => "11",
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        ),
                    );
                    cekHitam("UPDATE transaksi connector -- selanjutnya yang digenerate by system");
                    cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    $to = new MdlTransaksi();
                    $to->setFilters(array());
                    $to->setTableName($to->getTableNames()['detail']);
                    $dupState = $to->updateData(array(
                        "transaksi_id" => $connectorID,
                    ), array(
                        "next_substep_code" => "",
                        "next_substep_label" => "",
                        "next_subgroup_code" => "",
                        "next_substep_num" => 0,
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    )) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['detail'][] = array(
                        "where" => array(
                            "transaksi_id" => $connectorID,
                        ),
                        "value" => array(
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                            "next_substep_num" => 0,
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        ),
                    );
                    cekHitam("UPDATE transaksi data connector -- selanjutnya yang digenerate by system");
                    cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                }
            }
            //endregion

        }
        else {
            cekUngu(":: CHECK CONNECTING MUNDUR :: $jenisTr ::");
//mati_disini("cek konekting mundur...");
//            $origTCode = heGetOriginTCode_orig($jenisTr); // mencari transaksi yang connecto 110
            $origTCode = heGetOriginTCode_orig_he_stepping($jenisTr, $this->configUi); // mencari transaksi yang connecto ke $jenisTr
            cekMerah(__LINE__ . " origTCode: $origTCode");

            if (strlen($origTCode) > 2) {
                cekMerah("origTCode: $origTCode, ADA CONNECTING MUNDUR...");
                cekBiru("bila tidak normal, yang membatalkan pihak target/tujuan...");
                cekBiru("dan ada connecting ke belakang...");
                cekKuning("[$origTCode] step transaksi ini " . $thisStepNumber);

                if ($thisStepNumber == 1) {

                    //region transaksi connector -> 583 / 759
                    $arrSteps = isset($this->configUi[$origTCode]['steps']) ? $this->configUi[$origTCode]['steps'] : "";
                    $lastCode = $origTCode;
                    if (sizeof($arrSteps) > 0) {
                        foreach ($arrSteps as $stSpec) {
                            $lastCode = $stSpec['target'];
                        }
                    }
                    if (sizeof($rejectException) > 0 && (!in_array($lastCode, $rejectException['code']))) {
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $tb->addFilter("id_master='" . $tmpTr[0]->id_master . "'");
                        $tb->addFilter("jenis_master='$origTCode'");
                        $tb->addFilter("jenis='$lastCode'");
                        $tb->setSortBy(array("kolom" => "id", "mode" => "DESC"));
                        $trTmp = $tb->lookupAll()->result();
                    }
                    else {
                        $trTmp = array();
                    }
                    cekHere($this->db->last_query() . " --> [" . count($trTmp) . "]");

                    if (sizeof($trTmp) > 0) {
                        cekHere(":: BENER BENER CONNECTING ANTAR INSTANSI - PUSAT -> CABANG ::");

                        $jenisTr = $origTCode;
                        $stepNumCurrent = $trTmp[0]->step_number;

                        cekHere("jenisTR $jenisTr, idTR " . $trTmp[0]->id);


                        //region swap from registry
                        $tr = new MdlTransaksi();
                        $tmpReg = $tr->lookupDataRegistriesByMasterID($trTmp[0]->id)->result();
                        cekmerah($this->db->last_query());
                        if (sizeof($tmpReg) > 0) {
                            foreach ($tmpReg as $row) {
                                foreach ($row as $key_reg => $val_reg) {
                                    if ($key_reg != "transaksi_id") {
                                        $var = $key_reg;
                                        $$var = unserialize(base64_decode($val_reg));
                                    }
                                }
                            }
                        }
                        //        arrPrint($items);
                        //endregion

                        $nextMasterStep = $stepNumCurrent;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );
                        echo __LINE__ . " :: nextMasterStep: $nextMasterStep<br>";
                        arrPrint($nextProp);

                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        );

                        //region update step transaksi connector dan TOP-nya
                        if (sizeof($trTmp) > 0) {
                            cekUngu(":: trID -> " . $trTmp[0]->id);

                            //region update transaksi connector-nya
                            $prevID = $trTmp[0]->id;
                            $tc = new MdlTransaksi();
                            $tc->setFilters(array());
                            $dupState = $tc->updateData(array(
                                "id" => $prevID,
                            ), $arrData) or die("Failed to update tr next-state!");
                            cekKuning("UPDATE transaksi connector...");
                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array(
                                    "id" => $prevID,
                                ),
                                "value" => $arrData,
                            );
                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }


                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $arrData_detail["sub_step_number"] = 0;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekKuning("UPDATE transaksi data...");
                                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }
                            //endregion


                            //region update transaksi ID TOP, transaksi induk-nya
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                //                            "step_current" => $masterTargetStepNum,
                                //                            "step_number" => $masterTargetStepNum,
                                //                            "trash_4" => "1",
                                "step_current" => $nextProp['num'] - 1,
                                "step_number" => $nextProp['num'] - 1,
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //                            "sub_step_current" => $masterTargetStepNum,
                                //                            "sub_step_number" => $masterTargetStepNum,
                                "sub_step_current" => $nextProp['num'] - 1,
                                "sub_step_number" => $nextProp['num'] - 1,
                            );
                            $prevID = $trTmp[0]->id_top;
                            $tc = new MdlTransaksi();
                            $tc->setFilters(array());
                            $dupState = $tc->updateData(array(
                                "id" => $prevID,
                            ), $arrData) or die("Failed to update tr next-state!");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array("id" => $prevID,),
                                "value" => $arrData,
                            );
                            cekLime("UPDATE transaksi 1 step sebelumnya...");
                            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }


                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekLime("UPDATE transaksi data...");
                                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }
                            //endregion


                        }

                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tb->writeSignature($trTmp[0]->id, array(
                            "prev_id" => $trTmp[0]->id,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        // region netralisasi payment source
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("sisa>0");
                        $paymentSrc = $tr->lookupPaymentSrcByTransID($trTmp[0]->id)->result();
                        cekBiru($this->db->last_query());
                        if (sizeof($paymentSrc) > 0) {
                            //            arrPrint($paymentSrc);
                            foreach ($paymentSrc as $pSpec) {
                                if ($pSpec->terbayar == 0) {
                                    $where = array(
                                        "id" => $pSpec->id,
                                        "transaksi_id" => $pSpec->transaksi_id,
                                    );
                                    $data = array(
                                        "sisa" => 0,
                                        "returned" => $pSpec->sisa,
                                        "sisa_valas" => 0,
                                        "returned_valas" => $pSpec->sisa_valas,
                                    );

                                    $tra = New MdlTransaksi();
                                    $tra->setFilters(array());
                                    $tra->updatePaymentSrc($where, $data);
                                    cekUngu(":: mereject payment source bila ada...");
                                    cekUngu($this->db->last_query());
                                }
                                else {
                                    mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                                }
                            }
                        }
                        else {
                            cekBiru(":: tidak ada payment source... ::");
                        }
                        // endregion netralisasi payment source

                        // region netralisasi extended step
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $exTmp = $tr->lookupExtStepByTrID($trTmp[0]->id);
                        if (sizeof($exTmp) > 0) {
                            foreach ($exTmp as $exSpec) {

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->rejectExtStepByID($exSpec['id']);
                                $mongListUpadte['update']['extra'][] = array(
                                    "where" => array(
                                        "id" => $exSpec['id'],
                                    ),
                                    "value" => array(
                                        "state" => "-1",
                                    ),
                                );
                                cekUngu(":: mereject extended step bila ada...");
                                cekUngu($this->db->last_query());
                            }
                        }
                        else {
                            cekBiru(":: tidak ada extended step... ::");
                        }

                        // endregion netralisasi extended step

                        //==entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($trTmp[0]->id, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;
                            if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                                $insertIDs = array();
                                foreach ($tableIn_detail as $dSpec) {
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detail'] = $insertIDs;

                                    }
                                }
                            }
                        }
                        cekKuning("stepNumCurrent -> $stepNumCurrent, jenisTR -> $jenisTr");
                        $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

                        //===if rollback is needed
                        //rollback preproc, master
                        if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                            $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                            if (sizeof($iterator) > 0) {
                                $it = 0;
                                cekbiru("ada iterator pre-proc master");
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $it++;
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'] . "_reverse";
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                                    echo "reverse master-preproc: $comName, initializing values <br>";
                                    $tmpOutParams[$cCtr] = array();


                                    $subParams = array();

                                    if (isset($tComSpec['static'])) {
                                        foreach ($tComSpec['static'] as $key => $value) {
                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $subParams['static'][$key] = $realValue;
                                        }

                                        if (array_key_exists($oriComName, $prepConfigs)) {
                                            if (sizeof($prepConfigs[$oriComName]) > 0) {
                                                foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                    $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                                }
                                            }
                                        }

                                        if (!isset($subParams['static']["transaksi_id"])) {
                                            $subParams['static']["transaksi_id"] = $no;
                                        }


                                        $subParams['static']["fulldate"] = date("Y-m-d");
                                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                    }
                                    if (sizeof($subParams) > 0) {
                                        $tmpOutParams[$cCtr] = $subParams;
                                    }


                                    $mdlName = "Pre" . ucfirst($comName);
                                    $this->load->model("Preprocs/" . $mdlName);
                                    $m = new $mdlName($resultParams);


                                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                        $tobeExecuted = true;
                                    }
                                    else {
                                        $tobeExecuted = false;
                                    }

                                    if ($tobeExecuted) {
                                        arrprint($tmpOutParams[$cCtr]);
                                        $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                        $gotParams = $m->exec();


                                    }
                                    else {
                                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                    }

                                }
                            }
                            else {
                                cekHitam(":: tidak ada config preproc master yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
                        }
                        //rollback preproc, detail
                        if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                            //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                            $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                            //            arrprint($iterator);
                            if (sizeof($iterator) > 0) {
                                $it = 0;
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $it++;
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'] . "_reverse";
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "reverse preproc (detail): $comName, initializing values <br>";
                                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                                        $tmpOutParams[$cCtr] = array();
                                        //                        $id = $dSpec['id'];
                                        $id = $xid;
                                        $subParams = array();

                                        if (isset($tComSpec['static'])) {
                                            foreach ($tComSpec['static'] as $key => $value) {

                                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                                $subParams['static'][$key] = $realValue;

                                            }

                                            if (array_key_exists($oriComName, $prepConfigs)) {
                                                cekhitam("terdapat di dalam prepConfig");
                                                if (sizeof($prepConfigs[$oriComName]) > 0) {
                                                    foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                        $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                                    }
                                                }
                                            }
                                            else {
                                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                            }
                                            if (!isset($subParams['static']["transaksi_id"])) {
                                                $subParams['static']["transaksi_id"] = $no;
                                            }


                                            $subParams['static']["fulldate"] = date("Y-m-d");
                                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                            $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                        }

                                        if (sizeof($subParams) > 0) {

                                            $tmpOutParams[$cCtr][] = $subParams;
                                        }


                                        $comName = $tComSpec['comName'] . "_reverse";
                                        $srcGateName = $tComSpec['srcGateName'];
                                        $srcRawGateName = $tComSpec['srcRawGateName'];
                                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                                        echo "sub preproc #$it: $comName, sending values <br>";

                                        $mdlName = "Pre" . ucfirst($comName);
                                        $this->load->model("Preprocs/" . $mdlName);
                                        $m = new $mdlName($resultParams);


                                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                            $tobeExecuted = true;
                                        }
                                        else {
                                            $tobeExecuted = false;
                                        }

                                        if ($tobeExecuted) {

                                            //                            arrprint($tmpOutParams[$cCtr]);

                                            $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                            $gotParams = $m->exec();

                                            //                            cekbiru("gotparams");
                                            //                            arrprint($gotParams);

                                        }
                                        else {
                                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                        }

                                    }
                                }
                            }
                            else {
                                cekHitam(":: tidak ada config preproc detail yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
                        }

                        //rollback postproc, master
                        if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                            $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback main post-processor: $comName [$srcGateName]<br>";

                                    $dSpec = $_SESSION[$cCode][$srcGateName];
                                    $tmpOutParams = array();
                                    if (isset($tComSpec['loop'])) {
                                        foreach ($tComSpec['loop'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['loop'][$key] = $realValue;
                                        }
                                    }
                                    if (isset($tComSpec['static'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['static'][$key] = $realValue;
                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                        }

                                        $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                        $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                    }
                                    if (isset($tComSpec['static2'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static2'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['static2'][$key] = $realValue;
                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                            $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                            $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                        }

                                        $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                                        $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                                        $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                                    }


                                    if (array_key_exists($oriComName, $postConfigs)) {
                                        if (sizeof($postConfigs[$oriComName]) > 0) {
                                            foreach ($postConfigs[$oriComName] as $key) {
                                                $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                                cekbiru("oldVal: $oldVal");
                                                $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                cekHijau("newVal: $newVal");

                                                $tmpOutParams['static'][$key] = $newVal;
                                            }
                                        }
                                    }

                                    //lgShowError("Ada kesalahan",);
                                    $mdlName = "Com" . ucfirst($comName);
                                    $this->load->model("Coms/" . $mdlName);
                                    $m = new $mdlName();

                                    cekBiru("kiriman rollback main-postproc $comName");
                                    arrPrint($tmpOutParams);
                                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


                                }
                            }
                            else {
                                cekHitam(":: tidak ada config postproc master yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
                        }
                        //rollback postproc, detail

                        if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                            $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback sub-postProcessor: $comName, initializing values <br>";

                                    $tmpOutParams[$cCtr] = array();
                                    foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                                        $subParams = array();
                                        if (isset($tComSpec['loop'])) {
                                            foreach ($tComSpec['loop'] as $key => $value) {
                                                $gateItems = $$srcGateName;
                                                //                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                                $subParams['loop'][$key] = $realValue;
                                            }
                                        }
                                        if (isset($tComSpec['static'])) {
                                            foreach ($tComSpec['static'] as $key => $value) {
                                                $gateItems = $$srcGateName;
                                                //                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                                $subParams['static'][$key] = $realValue;
                                            }

                                            if (array_key_exists($oriComName, $postConfigs)) {
                                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                                    foreach ($postConfigs[$oriComName] as $key) {
                                                        $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                        cekbiru("oldVal2: $oldVal");
                                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                        cekHijau("newVal2: $newVal");
                                                        $subParams['static'][$key] = $newVal;
                                                    }
                                                }
                                            }
                                            else {
                                                //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                            }

                                            //                            $subParams['static']["transaksi_id"] = $insertID;
                                            if (!isset($subParams['static']["transaksi_id"])) {
                                                $subParams['static']["transaksi_id"] = $no;
                                            }
                                            if (!isset($subParams['static']["transaksi_no"])) {
                                                $subParams['static']["transaksi_no"] = $no;
                                            }
                                            $subParams['static']["fulldate"] = date("Y-m-d");
                                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                            $subParams['static']["keterangan"] = "rollback of $no";
                                            $subParams['static']["rejection"] = true;
                                        }


                                        if (sizeof($subParams) > 0) {
                                            $tmpOutParams[$cCtr][] = $subParams;
                                        }
                                    }
                                }

                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "sub-postProcessor: $comName, sending values <br>";

                                    $mdlName = "Com" . ucfirst($comName);
                                    $this->load->model("Coms/" . $mdlName);
                                    $m = new $mdlName();


                                    cekBiru("kiriman rollback detail-postproc $comName");
                                    arrPrint($tmpOutParams[$cCtr]);
                                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                }
                            }
                            else {
                                cekHitam(":: tidak ada config postproc detail yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                        }


                        //region transaksi stanby di pihak tujuan...
                        $nextMasterStep = $stepNumCurrent_son;
                        $childTargetStepNum = $childTargetStepNum_con;
                        $jenisTr = $jenisTr_con;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );

                        //region swap from registry, transaksi yang dibuka saat ini
                        $tr = new MdlTransaksi();
                        $tmpReg = $tr->lookupDataRegistriesByMasterID($no)->result();
                        cekmerah($this->db->last_query());
                        if (sizeof($tmpReg) > 0) {
                            foreach ($tmpReg as $row) {
                                foreach ($row as $key_reg => $val_reg) {
                                    if ($key_reg != "transaksi_id") {
                                        $var = $key_reg;
                                        $$var = unserialize(base64_decode($val_reg));
                                    }
                                }
                            }
                        }
                        //endregion

                        //region swap from main transaksi, transaksi yang dibuka saat ini
                        $tr = new MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("id='$no'");
                        $tmpTr = $tr->lookupMainTransaksi()->result();
                        cekOrange($this->db->last_query());
                        //endregion

                        //region transaksi yang stanby di pihak ke-2
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $dupState = $tb->updateData(array(
                            "id" => $no,
                        ), array(
                            "status_4" => "11",
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],

                        )) or die("Failed to update tr next-state!");

                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $no,
                            ),
                            "value" => array(
                                "status_4" => "11",
                                "trash_4" => "1",
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                            ),
                        );
                        cekHitam("UPDATE transaksi yang stanby di pihak ke-2");
                        cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData(array(
                            "transaksi_id" => $no,
                        ), array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "transaksi_id" => $no,
                            ),
                            "value" => array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            ),
                        );
                        cekHitam("UPDATE transaksi data yang stanby di pihak ke-2");
                        cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tr->writeSignature($no, array(
                            "prev_id" => $no,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //==entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;

                            if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                                $insertIDs = array();
                                foreach ($tableIn_detail as $dSpec) {
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detail'] = $insertIDs;
                                    }
                                }
                            }
                        }

                        //endregion

                    }
                    else {
                        cekMerah(":: CONNECTING, SATU INSTANSI (PUSAT DOANG / CABANG DOANG)::");
                        cekHitam(":: jenisTR > $jenisTr, jenis_master > $jenisTr, id_master > " . $tmpTr[0]->id_master . " ::");
                        //                    mati_disini(":: transaksi gagal karena transaksi yang dimaksud tidak valid.");


                        //region :: update ID-nya sendiri...

                        //region update step2an di masternya
                        $nextMasterStep = $stepNumCurrent;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );
                        echo "nextMasterStep: $nextMasterStep<br>";
                        arrPrint($nextProp);
                        cekKuning($masterTargetStepNum);
                        //update masternya, transaksi TOP
                        if ($tmpTr[0]->id_top != $no) {
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                "step_current" => $masterTargetStepNum,
                                "step_number" => $masterTargetStepNum,
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                "sub_step_current" => $masterTargetStepNum,
                                "sub_step_number" => $masterTargetStepNum,
                                //                "valid_qty" => $new_valid_qty,
                            );
                        }
                        else {
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                "step_current" => $masterTargetStepNum,
                                "step_number" => $masterTargetStepNum,
                                //                        "step_number" => $childTargetStepNum,
                                "trash_4" => "1",
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            );
                        }
                        $tr = new MdlTransaksi();
                        $dupState = $tr->updateData(array(
                            //                "id" => $no,
                            "id" => $tmpTr[0]->id_top,
                        ), $arrData) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array("id" => $tmpTr[0]->id_top),
                            "value" => $arrData,
                        );
                        cekHijau("UPDATE transaksi step sebelumnya...");
                        cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //region update step transaksi 1 step sebelumnya (detail)
                        if (sizeof($tmpTr) > 0) {
                            $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                            arrPrint($arrPrevID);
                            foreach ($arrPrevID as $prevID) {
                                $tb = new MdlTransaksi();
                                $tb->setFilters(array());
                                $dupState = $tb->updateData(array(
                                    "id" => $prevID,
                                ), array(
                                    "status_4" => "11",
                                )) or die("Failed to update tr next-state!");
                                $mongListUpadte['update']['main'][] = array(
                                    "where" => array("id" => $prevID),
                                    "value" => $arrData,
                                );
                                cekKuning("UPDATE transaksi 1 step sebelumnya...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                                $td = new MdlTransaksi();
                                $td->setFilters(array());
                                $rslt = $td->lookupJoinedByID($prevID)->result();
                                if (sizeof($rslt) > 0) {
                                    foreach ($rslt as $rsltSpec) {
                                        if (array_key_exists($rsltSpec->produk_id, $items)) {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                            //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                            if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                                $new_valid_qty = $rsltSpec->valid_qty;
                                                //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                            }
                                            else {
                                                $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                            }
                                            //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                            $arrData_detail["valid_qty"] = $new_valid_qty;
                                            $tr = new MdlTransaksi();
                                            $tr->setFilters(array());
                                            $tr->setTableName($tr->getTableNames()['detail']);
                                            $dupState = $tr->updateData(array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ), $arrData_detail) or die("Failed to update tr next-state!");
                                            $mongListUpadte['update']['detail'][] = array(
                                                "where" => array(
                                                    "transaksi_id" => $prevID,
                                                    "produk_id" => $rsltSpec->produk_id,
                                                ),
                                                "value" => $arrData_detail,
                                            );
                                            cekKuning("UPDATE transaksi data...");
                                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                        }
                                    }
                                }

                            }
                        }
                        //endregion

                        //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                        // cekUngu($tmpTr[0]->id_top);
                        // cekUngu("$no");
                        // if ($tmpTr[0]->id_top != $no) {
                        $tp = new MdlTransaksi();
                        $dupState = $tp->updateData(array(
                            "id" => $no,
                            "step_number" => $stepNumCurrent,
                        ), array(
                            "step_number" => $masterTargetStepNum,
                            //                    "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],

                        )) or die("Failed to update tr next-state!");

                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $no,
                                "step_number" => $stepNumCurrent,
                            ),
                            "value" => array(
                                "step_number" => $masterTargetStepNum,
                                //                    "step_number" => $childTargetStepNum,
                                "trash_4" => "1",
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                            ),
                        );
                        cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData(array(
                            "transaksi_id" => $no,
                        ), array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "transaksi_id" => $no,
                            ),
                            "value" => array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            ),
                        );
                        cekLime("UPDATE transaksi data...");
                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        // }
                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                            "prev_id" => $no,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        // region netralisasi payment source
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("sisa>0");
                        $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                        cekBiru($this->db->last_query());
                        if (sizeof($paymentSrc) > 0) {
                            //            arrPrint($paymentSrc);
                            foreach ($paymentSrc as $pSpec) {
                                if ($pSpec->terbayar == 0) {
                                    $where = array(
                                        "id" => $pSpec->id,
                                        "transaksi_id" => $pSpec->transaksi_id,
                                    );
                                    $data = array(
                                        "sisa" => 0,
                                        "returned" => $pSpec->sisa,
                                        "sisa_valas" => 0,
                                        "returned_valas" => $pSpec->sisa_valas,
                                    );

                                    $tra = New MdlTransaksi();
                                    $tra->setFilters(array());
                                    $tra->updatePaymentSrc($where, $data);
                                    cekUngu(":: mereject payment source bila ada...");
                                    cekUngu($this->db->last_query());
                                }
                                else {
                                    mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                                }
                            }
                        }
                        else {
                            cekBiru(":: tidak ada payment source... ::");
                        }
                        // endregion netralisasi payment source

                        // region netralisasi extended step
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $exTmp = $tr->lookupExtStepByTrID($no);
                        if (sizeof($exTmp) > 0) {
                            foreach ($exTmp as $exSpec) {

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->rejectExtStepByID($exSpec['id']);
                                $mongListUpadte['update']['extra'][] = array(
                                    "where" => array(
                                        "id" => $valID,
                                    ),
                                    "value" => array(
                                        "state" => "-1",
                                    ),
                                );
                                cekUngu(":: mereject extended step bila ada...");
                                cekUngu($this->db->last_query());
                            }
                        }
                        else {
                            cekBiru(":: tidak ada extended step... ::");
                        }

                        // endregion netralisasi extended step


                        //region entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;
                            //                        cekHitam($this->db->last_query());
                            if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                                $insertIDs = array();
                                foreach ($tableIn_detail as $dSpec) {
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detil'] = $insertIDs;
                                        //                                    cekHitam($this->db->last_query());
                                    }
                                }
                            }
                        }
                        //endregion

                        $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

                        //===if rollback is needed
                        //rollback preproc, master
                        if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                            //            cekbiru("ada config pre-proc master $stepNumCurrent");
                            $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                            //            arrprint($iterator);
                            if (sizeof($iterator) > 0) {
                                $it = 0;
                                cekbiru("ada iterator pre-proc master");
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $it++;
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'] . "_reverse";
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                                    echo "reverse master-preproc: $comName, initializing values <br>";
                                    $tmpOutParams[$cCtr] = array();


                                    $subParams = array();

                                    if (isset($tComSpec['static'])) {
                                        foreach ($tComSpec['static'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $subParams['static'][$key] = $realValue;

                                        }

                                        if (array_key_exists($oriComName, $prepConfigs)) {
                                            if (sizeof($prepConfigs[$oriComName]) > 0) {
                                                foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                    $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                                }
                                            }
                                        }

                                        if (!isset($subParams['static']["transaksi_id"])) {
                                            $subParams['static']["transaksi_id"] = $no;
                                        }


                                        $subParams['static']["fulldate"] = date("Y-m-d");
                                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                    }
                                    if (sizeof($subParams) > 0) {
                                        $tmpOutParams[$cCtr] = $subParams;
                                    }


                                    $mdlName = "Pre" . ucfirst($comName);
                                    $this->load->model("Preprocs/" . $mdlName);
                                    $m = new $mdlName($resultParams);


                                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                        $tobeExecuted = true;
                                    }
                                    else {
                                        $tobeExecuted = false;
                                    }

                                    if ($tobeExecuted) {
                                        arrprint($tmpOutParams[$cCtr]);
                                        $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                        $gotParams = $m->exec();


                                    }
                                    else {
                                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                    }

                                }
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
                        }
                        //rollback preproc, detail
                        if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                            //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                            $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                            //            arrprint($iterator);
                            if (sizeof($iterator) > 0) {
                                $it = 0;
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $it++;
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'] . "_reverse";
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "reverse preproc (detail): $comName, initializing values <br>";
                                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                                        $tmpOutParams[$cCtr] = array();
                                        //                        $id = $dSpec['id'];
                                        $id = $xid;
                                        $subParams = array();

                                        if (isset($tComSpec['static'])) {
                                            foreach ($tComSpec['static'] as $key => $value) {

                                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                                $subParams['static'][$key] = $realValue;

                                            }

                                            if (array_key_exists($oriComName, $prepConfigs)) {
                                                cekhitam("terdapat di dalam prepConfig");
                                                if (sizeof($prepConfigs[$oriComName]) > 0) {
                                                    foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                        $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                                    }
                                                }
                                            }
                                            else {
                                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                            }
                                            if (!isset($subParams['static']["transaksi_id"])) {
                                                $subParams['static']["transaksi_id"] = $no;
                                            }


                                            $subParams['static']["fulldate"] = date("Y-m-d");
                                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                            $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                        }

                                        if (sizeof($subParams) > 0) {

                                            $tmpOutParams[$cCtr][] = $subParams;
                                        }


                                        $comName = $tComSpec['comName'] . "_reverse";
                                        $srcGateName = $tComSpec['srcGateName'];
                                        $srcRawGateName = $tComSpec['srcRawGateName'];
                                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                                        echo "sub preproc #$it: $comName, sending values <br>";

                                        $mdlName = "Pre" . ucfirst($comName);
                                        $this->load->model("Preprocs/" . $mdlName);
                                        $m = new $mdlName($resultParams);


                                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                            $tobeExecuted = true;
                                        }
                                        else {
                                            $tobeExecuted = false;
                                        }

                                        if ($tobeExecuted) {

                                            //                            arrprint($tmpOutParams[$cCtr]);

                                            $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                            $gotParams = $m->exec();

                                            //                            cekbiru("gotparams");
                                            //                            arrprint($gotParams);

                                        }
                                        else {
                                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                        }

                                    }
                                }
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
                        }
                        //rollback postproc, master
                        if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                            //            cekbiru("ada config pre-proc master $stepNumCurrent");
                            $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback main post-processor: $comName<br>";

                                    $dSpec = $_SESSION[$cCode][$srcGateName];
                                    $tmpOutParams = array();
                                    if (isset($tComSpec['loop'])) {
                                        foreach ($tComSpec['loop'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $tmpOutParams['loop'][$key] = $realValue;

                                        }
                                    }
                                    if (isset($tComSpec['static'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $tmpOutParams['static'][$key] = $realValue;

                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                        }

                                        $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                        $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];


                                    }
                                    if (isset($tComSpec['static2'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static2'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                            $tmpOutParams['static2'][$key] = $realValue;

                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                            $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                            $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                        }

                                        $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                                        $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                                        $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                                    }


                                    if (array_key_exists($oriComName, $postConfigs)) {
                                        if (sizeof($postConfigs[$oriComName]) > 0) {
                                            foreach ($postConfigs[$oriComName] as $key) {
                                                $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                                cekbiru("oldVal: $oldVal");
                                                $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                cekHijau("newVal: $newVal");
                                                //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                                $tmpOutParams['static'][$key] = $newVal;
                                            }
                                        }
                                    }

                                    //lgShowError("Ada kesalahan",);
                                    $mdlName = "Com" . ucfirst($comName);
                                    $this->load->model("Coms/" . $mdlName);
                                    $m = new $mdlName();

                                    cekBiru("kiriman rollback main-postproc $comName");
                                    arrPrint($tmpOutParams);
                                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


                                }
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
                        }
                        //rollback postproc, detail
                        if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                            $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback sub-postProcessor: $comName, initializing values <br>";
                                    //                arrPrint($_SESSION[$cCode][$srcGateName]);
                                    $tmpOutParams[$cCtr] = array();
                                    foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                                        $subParams = array();
                                        if (isset($tComSpec['loop'])) {
                                            foreach ($tComSpec['loop'] as $key => $value) {

                                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $subParams['loop'][$key] = $realValue;

                                            }
                                        }
                                        if (isset($tComSpec['static'])) {
                                            foreach ($tComSpec['static'] as $key => $value) {

                                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $subParams['static'][$key] = $realValue;
                                                //                                cekBiru("$key diisi dengan $realValue");

                                            }

                                            if (array_key_exists($oriComName, $postConfigs)) {
                                                //                                cekhitam("terdapat di dalam postConfig");
                                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                                    foreach ($postConfigs[$oriComName] as $key) {
                                                        //                                        $replVal=makeValue($src,$_SESSION[$cCode][$srcGateName][$cnt],$_SESSION[$cCode][$srcGateName][$cnt],0);
                                                        //                                        cekbiru("$key akan direplace dengan nilai $replVal");
                                                        //                                        $subParams['static'][$key]=$replVal;

                                                        $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                        cekbiru("oldVal2: $oldVal");
                                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                        cekHijau("newVal2: $newVal");
                                                        $subParams['static'][$key] = $newVal;
                                                        //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                                        //                                        $tmpOutParams['static'][$key]=$newVal;
                                                    }
                                                }
                                            }
                                            else {
                                                //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                            }

                                            //                            $subParams['static']["transaksi_id"] = $insertID;
                                            if (!isset($subParams['static']["transaksi_id"])) {
                                                $subParams['static']["transaksi_id"] = $no;
                                            }
                                            if (!isset($subParams['static']["transaksi_no"])) {
                                                $subParams['static']["transaksi_no"] = $no;
                                            }
                                            $subParams['static']["fulldate"] = date("Y-m-d");
                                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                            $subParams['static']["keterangan"] = "rollback of $no";
                                            $subParams['static']["rejection"] = true;
                                        }


                                        if (sizeof($subParams) > 0) {
                                            $tmpOutParams[$cCtr][] = $subParams;
                                        }
                                    }
                                }

                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "sub-postProcessor: $comName, sending values <br>";

                                    $mdlName = "Com" . ucfirst($comName);
                                    $this->load->model("Coms/" . $mdlName);
                                    $m = new $mdlName();


                                    cekBiru("kiriman rollback detail-postproc $comName");
                                    arrPrint($tmpOutParams[$cCtr]);
                                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                }
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                        }

                        //endregion

                    }
                    //endregion

//                    mati_disini("=== masuk sini ===");
                }
                else {
                    // hanya mundur 1 langkah di pihak target
//mati_disini(__LINE__);
                    //region update step2an di masternya
                    $nextMasterStep = $stepNumCurrent;
                    $nextProp = array(
                        "num" => $nextMasterStep,
                        "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                        "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                        "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                    );
                    echo "nextMasterStep: $nextMasterStep<br>";
//                    arrPrint($nextProp);
//                    cekKuning($masterTargetStepNum);
                    //update masternya, transaksi TOP
                    if ($tmpTr[0]->id_top != $no) {
                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $masterTargetStepNum,
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            "sub_step_current" => $masterTargetStepNum,
                            "sub_step_number" => $masterTargetStepNum,
                            //                "valid_qty" => $new_valid_qty,
                        );
                    }
                    else {
                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $masterTargetStepNum,
                            //                        "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => dtime("Y-m-d H:i:s"),
                            "cancel_id" => $this->session->login['id'],
                            "cancel_name" => $this->session->login['nama'],
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        );
                    }
                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $tmpTr[0]->id_top,
                    ), $arrData) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $tmpTr[0]->id_top
                        ),
                        "value" => $arrData,
                    );
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //endregion

                    //region update step transaksi 1 step sebelumnya (detail)
                    if (sizeof($tmpTr) > 0) {
                        $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
//                        arrPrint($arrPrevID);
                        foreach ($arrPrevID as $prevID) {
                            $tb = new MdlTransaksi();
                            $tb->setFilters(array());
                            $dupState = $tb->updateData(array(
                                "id" => $prevID,
                            ), array(
                                "status_4" => "11",
                            )) or die("Failed to update tr next-state!");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array(
                                    "id" => $prevID
                                ),
                                "value" => array(
                                    "status_4" => "11",
                                ),
                            );
                            cekKuning("UPDATE transaksi 1 step sebelumnya...");
                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }
                                        //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekKuning("UPDATE transaksi data...");
                                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }

                        }
                    }
                    //endregion

                    //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                    $tp = new MdlTransaksi();
                    $dupState = $tp->updateData(array(
                        "id" => $no,
                        "step_number" => $stepNumCurrent,
                    ), array(
                        "step_number" => $masterTargetStepNum,
                        //                    "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i:s"),
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_id" => $this->session->login['id'],

                    )) or die("Failed to update tr next-state!");

                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $no,
                            "step_number" => $stepNumCurrent,
                        ),
                        "value" => array(
                            "step_number" => $masterTargetStepNum,
                            //                    "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        ),
                    );
                    cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                    cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
//arrPrintWebs($mongListUpadte);
                    $to = new MdlTransaksi();
                    $to->setFilters(array());
                    $to->setTableName($to->getTableNames()['detail']);
                    $dupState = $to->updateData(array(
                        "transaksi_id" => $no,
                    ), array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    )) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['detail'][] = array(
                        "where" => array(
                            "transaksi_id" => $no, "id" => $no,
                        ),
                        "value" => array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        ),
                    );
                    cekLime("UPDATE transaksi data...");
                    cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //endregion

                    //region sesuaikan signature untuk cloningan, ikut minus
                    //        $dwsign = $tr->writeSignature($no, array(
                    $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                        "prev_id" => $no,
                        "nomer" => "rejection",
                        "step_number" => $childTargetStepNum, // ini minus step number
                        "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                        "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                        "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //endregion

                    // region netralisasi payment source
                    $tr = New MdlTransaksi();
                    $tr->setFilters(array());
                    $tr->addFilter("sisa>0");
                    $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                    cekBiru($this->db->last_query());
                    if (sizeof($paymentSrc) > 0) {
                        //            arrPrint($paymentSrc);
                        foreach ($paymentSrc as $pSpec) {
                            if ($pSpec->terbayar == 0) {
                                $where = array(
                                    "id" => $pSpec->id,
                                    "transaksi_id" => $pSpec->transaksi_id,
                                );
                                $data = array(
                                    "sisa" => 0,
                                    "returned" => $pSpec->sisa,
                                    "sisa_valas" => 0,
                                    "returned_valas" => $pSpec->sisa_valas,
                                );

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->updatePaymentSrc($where, $data);
                                cekUngu(":: mereject payment source bila ada...");
                                cekUngu($this->db->last_query());
                            }
                            else {
                                mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                            }
                        }
                    }
                    else {
                        cekBiru(":: tidak ada payment source... ::");
                    }
                    // endregion netralisasi payment source

                    // region netralisasi extended step
                    $tr = New MdlTransaksi();
                    $tr->setFilters(array());
                    $exTmp = $tr->lookupExtStepByTrID($no);
                    if (sizeof($exTmp) > 0) {
                        foreach ($exTmp as $exSpec) {

                            $tra = New MdlTransaksi();
                            $tra->setFilters(array());
                            $tra->rejectExtStepByID($exSpec['id']);
                            $mongListUpadte['update']['extra'][] = array(
                                "where" => array(
                                    "id" => $exSpec['id'],
                                ),
                                "value" => array(
                                    "state" => "-1",
                                ),
                            );
                            cekUngu(":: mereject extended step bila ada...");
                            cekUngu($this->db->last_query());
                        }
                    }
                    else {
                        cekBiru(":: tidak ada extended step... ::");
                    }

                    // endregion netralisasi extended step

                    //==entry point
                    if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                        $tableIn_master['trash_4'] = 1;
                        $tableIn_master['cancel_id'] = $this->session->login['id'];
                        $tableIn_master['cancel_name'] = $this->session->login['nama'];
                        $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                        $tableIn_master['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                        $mongoList['main'][] = $epID;

                        if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                            $insertIDs = array();
                            foreach ($tableIn_detail as $dSpec) {
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                            }
                        }
                    }

                    $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

                    //===if rollback is needed
                    //rollback preproc, master
                    if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                        //            cekbiru("ada config pre-proc master $stepNumCurrent");
                        $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                        //            arrprint($iterator);
                        if (sizeof($iterator) > 0) {
                            $it = 0;
                            cekbiru("ada iterator pre-proc master");
                            foreach ($iterator as $cCtr => $tComSpec) {
                                $it++;
                                $oriComName = $tComSpec['comName'];
                                $comName = $tComSpec['comName'] . "_reverse";
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                                echo "reverse master-preproc: $comName, initializing values <br>";
                                $tmpOutParams[$cCtr] = array();


                                $subParams = array();

                                if (isset($tComSpec['static'])) {
                                    foreach ($tComSpec['static'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                        $subParams['static'][$key] = $realValue;

                                    }

                                    if (array_key_exists($oriComName, $prepConfigs)) {
                                        if (sizeof($prepConfigs[$oriComName]) > 0) {
                                            foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            }
                                        }
                                    }

                                    if (!isset($subParams['static']["transaksi_id"])) {
                                        $subParams['static']["transaksi_id"] = $no;
                                    }


                                    $subParams['static']["fulldate"] = date("Y-m-d");
                                    $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                }
                                if (sizeof($subParams) > 0) {
                                    $tmpOutParams[$cCtr] = $subParams;
                                }


                                $mdlName = "Pre" . ucfirst($comName);
                                $this->load->model("Preprocs/" . $mdlName);
                                $m = new $mdlName($resultParams);


                                if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                    $tobeExecuted = true;
                                }
                                else {
                                    $tobeExecuted = false;
                                }

                                if ($tobeExecuted) {
                                    arrprint($tmpOutParams[$cCtr]);
                                    $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $gotParams = $m->exec();


                                }
                                else {
                                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                }

                            }
                        }
                    }
                    else {
                        cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
                    }
                    //rollback preproc, detail
                    if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                        //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                        $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                        //            arrprint($iterator);
                        if (sizeof($iterator) > 0) {
                            $it = 0;
                            foreach ($iterator as $cCtr => $tComSpec) {
                                $it++;
                                $oriComName = $tComSpec['comName'];
                                $comName = $tComSpec['comName'] . "_reverse";
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                echo "reverse preproc (detail): $comName, initializing values <br>";
                                foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                                    $tmpOutParams[$cCtr] = array();
                                    //                        $id = $dSpec['id'];
                                    $id = $xid;
                                    $subParams = array();

                                    if (isset($tComSpec['static'])) {
                                        foreach ($tComSpec['static'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                            $subParams['static'][$key] = $realValue;

                                        }

                                        if (array_key_exists($oriComName, $prepConfigs)) {
                                            cekhitam("terdapat di dalam prepConfig");
                                            if (sizeof($prepConfigs[$oriComName]) > 0) {
                                                foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                    $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                                }
                                            }
                                        }
                                        else {
                                            cekhitam("TIDAK terdapat di dalam prepConfig");
                                        }
                                        if (!isset($subParams['static']["transaksi_id"])) {
                                            $subParams['static']["transaksi_id"] = $no;
                                        }


                                        $subParams['static']["fulldate"] = date("Y-m-d");
                                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                    }

                                    if (sizeof($subParams) > 0) {

                                        $tmpOutParams[$cCtr][] = $subParams;
                                    }


                                    $comName = $tComSpec['comName'] . "_reverse";
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                                    echo "sub preproc #$it: $comName, sending values <br>";

                                    $mdlName = "Pre" . ucfirst($comName);
                                    $this->load->model("Preprocs/" . $mdlName);
                                    $m = new $mdlName($resultParams);


                                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                        $tobeExecuted = true;
                                    }
                                    else {
                                        $tobeExecuted = false;
                                    }

                                    if ($tobeExecuted) {

                                        //                            arrprint($tmpOutParams[$cCtr]);

                                        $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                        $gotParams = $m->exec();

                                        //                            cekbiru("gotparams");
                                        //                            arrprint($gotParams);

                                    }
                                    else {
                                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                    }

                                }
                            }
                        }
                    }
                    else {
                        cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
                    }
                    //rollback postproc, master
                    if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                        //            cekbiru("ada config pre-proc master $stepNumCurrent");
                        $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $cCtr => $tComSpec) {
                                $oriComName = $tComSpec['comName'];
                                $comName = $tComSpec['comName'];
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                echo "rollback main post-processor: $comName<br>";

                                $dSpec = $_SESSION[$cCode][$srcGateName];
                                $tmpOutParams = array();
                                if (isset($tComSpec['loop'])) {
                                    foreach ($tComSpec['loop'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                        $tmpOutParams['loop'][$key] = $realValue;

                                    }
                                }
                                if (isset($tComSpec['static'])) {
                                    //cekHere("DISINI OIII");
                                    foreach ($tComSpec['static'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                        $tmpOutParams['static'][$key] = $realValue;

                                    }
                                    if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                        $tmpOutParams['static']["transaksi_id"] = $insertID;
                                    }
                                    if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                        $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                    }

                                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];


                                }
                                if (isset($tComSpec['static2'])) {
                                    //cekHere("DISINI OIII");
                                    foreach ($tComSpec['static2'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                        $tmpOutParams['static2'][$key] = $realValue;

                                    }
                                    if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                        $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                    }
                                    if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                        $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                    }

                                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                                }


                                if (array_key_exists($oriComName, $postConfigs)) {
                                    if (sizeof($postConfigs[$oriComName]) > 0) {
                                        foreach ($postConfigs[$oriComName] as $key) {
                                            $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                            cekbiru("oldVal: $oldVal");
                                            $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                            cekHijau("newVal: $newVal");
                                            //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                            $tmpOutParams['static'][$key] = $newVal;
                                        }
                                    }
                                }

                                //lgShowError("Ada kesalahan",);
                                $mdlName = "Com" . ucfirst($comName);
                                $this->load->model("Coms/" . $mdlName);
                                $m = new $mdlName();

                                cekBiru("kiriman rollback main-postproc $comName");
                                arrPrint($tmpOutParams);
                                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


                            }
                        }
                    }
                    else {
                        cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
                    }
                    //rollback postproc, detail
                    if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                        $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                        if (sizeof($iterator) > 0) {
                            foreach ($iterator as $cCtr => $tComSpec) {
                                $oriComName = $tComSpec['comName'];
                                $comName = $tComSpec['comName'];
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                echo "rollback sub-postProcessor: $comName, initializing values <br>";
                                //                arrPrint($_SESSION[$cCode][$srcGateName]);
                                $tmpOutParams[$cCtr] = array();
                                foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                                    $subParams = array();
                                    if (isset($tComSpec['loop'])) {
                                        foreach ($tComSpec['loop'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                            $subParams['loop'][$key] = $realValue;

                                        }
                                    }
                                    if (isset($tComSpec['static'])) {
                                        foreach ($tComSpec['static'] as $key => $value) {

                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                            $subParams['static'][$key] = $realValue;
                                            //                                cekBiru("$key diisi dengan $realValue");

                                        }

                                        if (array_key_exists($oriComName, $postConfigs)) {
                                            //                                cekhitam("terdapat di dalam postConfig");
                                            if (sizeof($postConfigs[$oriComName]) > 0) {
                                                foreach ($postConfigs[$oriComName] as $key) {
                                                    //                                        $replVal=makeValue($src,$_SESSION[$cCode][$srcGateName][$cnt],$_SESSION[$cCode][$srcGateName][$cnt],0);
                                                    //                                        cekbiru("$key akan direplace dengan nilai $replVal");
                                                    //                                        $subParams['static'][$key]=$replVal;

                                                    $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                    cekbiru("oldVal2: $oldVal");
                                                    $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                    cekHijau("newVal2: $newVal");
                                                    $subParams['static'][$key] = $newVal;
                                                    //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                                    //                                        $tmpOutParams['static'][$key]=$newVal;
                                                }
                                            }
                                        }
                                        else {
                                            //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                        }

                                        //                            $subParams['static']["transaksi_id"] = $insertID;
                                        if (!isset($subParams['static']["transaksi_id"])) {
                                            $subParams['static']["transaksi_id"] = $no;
                                        }
                                        if (!isset($subParams['static']["transaksi_no"])) {
                                            $subParams['static']["transaksi_no"] = $no;
                                        }
                                        $subParams['static']["fulldate"] = date("Y-m-d");
                                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $subParams['static']["keterangan"] = "rollback of $no";
                                        $subParams['static']["rejection"] = true;
                                    }


                                    if (sizeof($subParams) > 0) {
                                        $tmpOutParams[$cCtr][] = $subParams;
                                    }
                                }
                            }

                            foreach ($iterator as $cCtr => $tComSpec) {
                                $oriComName = $tComSpec['comName'];
                                $comName = $tComSpec['comName'];
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                echo "sub-postProcessor: $comName, sending values <br>";

                                $mdlName = "Com" . ucfirst($comName);
                                $this->load->model("Coms/" . $mdlName);
                                $m = new $mdlName();


                                cekBiru("kiriman rollback detail-postproc $comName");
                                arrPrint($tmpOutParams[$cCtr]);
                                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            }
                        }
                    }
                    else {
                        cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                    }
//mati_disini(__LINE__);
                }

            }
            else {
                cekBiru("yang membatalkan pihak source/sumber...");
                cekBiru("TIDAK ADA CONNECTING MUNDUR...");
//mati_disini(__LINE__);

                //region update step2an di masternya
                $nextMasterStep = $stepNumCurrent;
                $nextProp = array(
                    "num" => $nextMasterStep,
                    "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                    "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                    "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                );
                echo "nextMasterStep: $nextMasterStep<br>";
                arrPrint($nextProp);
                cekKuning($masterTargetStepNum);
                //update masternya, transaksi TOP
                if ($tmpTr[0]->id_top != $no) {
                    $arrData = array(
                        "next_step_code" => $nextProp['code'],
                        "next_step_label" => $nextProp['label'],
                        "next_group_code" => $nextProp['groupID'],
                        "next_step_num" => $nextProp['num'],
                        "step_current" => $masterTargetStepNum,
                        "step_number" => $masterTargetStepNum,
                    );
                    $arrData_detail = array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        "sub_step_current" => $masterTargetStepNum,
                        "sub_step_number" => $masterTargetStepNum,
                        //                "valid_qty" => $new_valid_qty,
                    );
                }
                else {
                    $arrData = array(
                        "next_step_code" => $nextProp['code'],
                        "next_step_label" => $nextProp['label'],
                        "next_group_code" => $nextProp['groupID'],
                        "next_step_num" => $nextProp['num'],
                        "step_current" => $masterTargetStepNum,
                        "step_number" => $masterTargetStepNum,
                        //                        "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_id" => $this->session->login['id'],
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_dtime" => date("Y-m-d H:i:s"),

                    );
                    $arrData_detail = array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    );
                }
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array(
                    //                "id" => $no,
                    "id" => $tmpTr[0]->id_top,
                ), $arrData) or die("Failed to update tr next-state!");
                $mongListUpadte['update']['main'][] = array(
                    "where" => array(
                        "id" => $tmpTr[0]->id_top
                    ),
                    "value" => $arrData,
                );
                cekHijau("UPDATE transaksi step sebelumnya...");
                cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                //endregion

                //region update step transaksi 1 step sebelumnya (detail)
                if (sizeof($tmpTr) > 0) {
                    $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                    arrPrint($arrPrevID);
                    foreach ($arrPrevID as $prevID) {
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $dupState = $tb->updateData(array(
                            "id" => $prevID,
                        ), array(
                            "status_4" => "11",
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $prevID
                            ),
                            "value" => array(
                                "status_4" => "11",
                            ),
                        );
                        cekKuning("UPDATE transaksi 1 step sebelumnya...");
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                        $td = new MdlTransaksi();
                        $td->setFilters(array());
                        $rslt = $td->lookupJoinedByID($prevID)->result();
                        if (sizeof($rslt) > 0) {
                            foreach ($rslt as $rsltSpec) {
                                if (array_key_exists($rsltSpec->produk_id, $items)) {
                                    $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                    //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                    if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                        $new_valid_qty = $rsltSpec->valid_qty;
                                        //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                    }
                                    else {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                    }
                                    //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                    $arrData_detail["valid_qty"] = $new_valid_qty;
                                    $tr = new MdlTransaksi();
                                    $tr->setFilters(array());
                                    $tr->setTableName($tr->getTableNames()['detail']);
                                    $dupState = $tr->updateData(array(
                                        "transaksi_id" => $prevID,
                                        "produk_id" => $rsltSpec->produk_id,
                                    ), $arrData_detail) or die("Failed to update tr next-state!");
                                    $mongListUpadte['update']['detail'][] = array(
                                        "where" => array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ),
                                        "value" => $arrData_detail,
                                    );
                                    cekKuning("UPDATE transaksi data...");
                                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                }
                            }
                        }

                    }
                }
                //endregion

                //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                $tp = new MdlTransaksi();
                $dupState = $tp->updateData(array(
                    "id" => $no,
                    "step_number" => $stepNumCurrent,
                ), array(
                    "step_number" => $masterTargetStepNum,
                    //                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['nama'],
                    "cancel_id" => $this->session->login['id'],

                )) or die("Failed to update tr next-state!");

                $mongListUpadte['update']['main'][] = array(
                    "where" => array(
                        "id" => $no,
                        "step_number" => $stepNumCurrent,
                    ),
                    "value" => array(
                        "step_number" => $masterTargetStepNum,
                        //                    "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i:s"),
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_id" => $this->session->login['id'],
                    ),
                );
                cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                $to = new MdlTransaksi();
                $to->setFilters(array());
                $to->setTableName($to->getTableNames()['detail']);
                $dupState = $to->updateData(array(
                    "transaksi_id" => $no,
                ), array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                )) or die("Failed to update tr next-state!");
                $mongListUpadte['update']['detail'][] = array(
                    "where" => array(
                        "transaksi_id" => $no, "id" => $no,
                    ),
                    "value" => array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    ),
                );
                cekLime("UPDATE transaksi data...");
                cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                //endregion

                //region sesuaikan signature untuk cloningan, ikut minus
                //        $dwsign = $tr->writeSignature($no, array(
                $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                    "prev_id" => $no,
                    "nomer" => "rejection",
                    "step_number" => $childTargetStepNum, // ini minus step number
                    "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                    "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                    "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                    //            "transaksi_id" => $no,
                )) or die("Failed to write signature");
                $mongoList['sign'][] = $dwsign;
                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                //endregion

                // region netralisasi payment source
                $tr = New MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("sisa>0");
                $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                cekBiru($this->db->last_query());
                if (sizeof($paymentSrc) > 0) {
                    //            arrPrint($paymentSrc);
                    foreach ($paymentSrc as $pSpec) {
                        if ($pSpec->terbayar == 0) {
                            $where = array(
                                "id" => $pSpec->id,
                                "transaksi_id" => $pSpec->transaksi_id,
                            );
                            $data = array(
                                "sisa" => 0,
                                "returned" => $pSpec->sisa,
                                "sisa_valas" => 0,
                                "returned_valas" => $pSpec->sisa_valas,
                            );

                            $tra = New MdlTransaksi();
                            $tra->setFilters(array());
                            $tra->updatePaymentSrc($where, $data);
                            cekUngu(":: mereject payment source bila ada...");
                            cekUngu($this->db->last_query());
                        }
                        else {
                            mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                        }
                    }
                }
                else {
                    cekBiru(":: tidak ada payment source... ::");
                }
                // endregion netralisasi payment source

                // region netralisasi extended step
                $tr = New MdlTransaksi();
                $tr->setFilters(array());
                $exTmp = $tr->lookupExtStepByTrID($no);
                if (sizeof($exTmp) > 0) {
                    foreach ($exTmp as $exSpec) {

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->rejectExtStepByID($exSpec['id']);
                        $mongListUpadte['update']['extra'][] = array(
                            "where" => array(
                                "id" => $exSpec['id'],
                            ),
                            "value" => array(
                                "state" => "-1",
                            ),
                        );
                        cekUngu(":: mereject extended step bila ada...");
                        cekUngu($this->db->last_query());
                    }
                }
                else {
                    cekBiru(":: tidak ada extended step... ::");
                }

                // endregion netralisasi extended step

                //==entry point
                if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                    if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                        if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                            $masterID = $currentMasterID;
                            $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                            $tCodeTargetJenisTransaksi = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                            $modul_transaksi = $this->modul;
                            cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                            if ($connecTo == NULL) {
                                mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                            }
                            $oldCode = $cCode;
                            $cCode = "_TR_" . $connecTo;
                            $_SESSION[$cCode] = array(
                                'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                                'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                                'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                                'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                                'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                                'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                                'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                                'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                                'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                                'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                                'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                                'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                                'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                                'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                                'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                                'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                                'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                                'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                                'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                                'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                                'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                                'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                                'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                                'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                                'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                                'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                                'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                                'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                                'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                                'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                                'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                                'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                                "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                                "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                                "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                                "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                            );
                            // masuk ke gerbang TableInMaster, tabel transaksi
                            $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                                "jenis_master" => $this->jenisTr,
                                "jenis_top" => $connecTo,
                                "jenis" => $connecTo,
                                "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "transaksi_jenis" => $connecTo,
                                "step_avail" => 1,
                                "step_current" => 1,
                                "step_number" => 1,
                                "next_step_code" => "",
                                "next_step_label" => "",
                                "next_group_code" => "",
                                "next_step_num" => "0",
                                "trash_4" => 1,
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                                "deskripsi" => "rejection",
                                "oleh_id" => my_id(),
                                "oleh_nama" => my_name()
                            );
                            // masuk ke gerbang main
                            $masterReplacersO = array(
                                "stepCode" => $connecTo,
                                "jenisTrTop" => $connecTo,
                                "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                                "jenis_master" => $this->jenisTr,
                                "jenis_top" => $connecTo,
                                "jenis" => $connecTo,
                                "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "transaksi_jenis" => $connecTo,
                                "stepCode" => $connecTo,
                                "jenisTrTop" => $connecTo,
                                "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "step_avail" => 1,
                                "step_current" => 1,
                                "step_number" => 1,
                                "next_step_code" => "",
                                "next_step_label" => "",
                                "next_group_code" => "",
                                "next_step_num" => "0",
                                "olehID" => my_id(),
                                "olehName" => my_name()
                            );
                            foreach ($masterReplacersO as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                            }
                            foreach ($masterReplacers as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                            //region penomoran receipt
                            $this->load->model("CustomCounter");
                            $cn = new CustomCounter("transaksi");
                            $cn->setType("transaksi");
                            $cn->setModul($modul_transaksi);
                            $cn->setStepCode($tCodeTargetJenisTransaksi);
                            $counterForNumber = array($this->configCore[$this->jenisTr]['formatNotaEdit']);
                            if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['countersEdit'])) {
                                die(__LINE__ . " Used number should be registered in 'counters' config as well");
                            }
                            echo "<div style='background:#ff7766;'>";
                            foreach ($counterForNumber as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                            }
                            echo "</div style='background:#ff7766;'>";

                            $stepNumber = 1;
                            $tmpNomorNota = $paramSpec['paramString'];
                            $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                            $nextProp = array(
                                "num" => 0,
                                "code" => "",
                                "label" => "",
                                "groupID" => "",
                            );
                            //endregion

                            //region dynamic counters
                            // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                            $cn = new CustomCounter("transaksi");
                            $cn->setType("transaksi");
                            $cn->setModul($modul_transaksi);
                            $cn->setStepCode($tCodeTargetJenisTransaksi);
                            $configCustomParams = $this->configCore[$this->jenisTr]['countersEdit'];
                            arrPrintHijau($configCustomParams);
                            $configCustomParams[] = "stepCode";
                            //arrPrint($configCustomParams);
                            if (sizeof($configCustomParams) > 0) {
                                $cContent = array();
                                foreach ($configCustomParams as $i => $cRawParams) {
                                    $cParams = explode("|", $cRawParams);
                                    $cValues = array();
                                    foreach ($cParams as $param) {
                                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                    }
                                    $cRawValues = implode("|", $cValues[$i]);
                                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                                    $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                    switch ($paramSpec['id']) {
                                        case 0: //===counter type is new
                                            $paramKeyRaw = print_r($cParams, true);
                                            $paramValuesRaw = print_r($cValues[$i], true);
                                            $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                            break;
                                        default: //===counter to be updated
                                            $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                            break;
                                    }
                                    //echo "<hr>";
                                }
                            }
                            $appliedCounters = base64_encode(serialize($cContent));
                            $appliedCounters_inText = print_r($cContent, true);
                            //mati_disini();
//arrPrintPink($cContent);
                            //
                            //region addition on master


                            $addValues = array(
                                'counters' => $appliedCounters,
                                'counters_intext' => $appliedCounters_inText,
                                'nomer' => $tmpNomorNota,
                                'nomer2' => $tmpNomorNotaAlias,
                                'dtime' => date("Y-m-d H:i:s"),
                                'fulldate' => date("Y-m-d"),
                                "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                "step_number" => 1,
                                "step_current" => 1,
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "tail_number" => 1,
                                "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }
                            //endregion

                            //
                            //region addition on detail
                            $addSubValues = array(
                                "sub_step_number" => 1,
                                "sub_step_current" => 1,
                                "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                "next_substep_num" => $nextProp['num'],
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "sub_tail_number" => 1,
                                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                            );
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                                foreach ($addSubValues as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                                }
                            }
                            //endregion
                            // </editor-fold>
                            //endregion

                            $addValues = array(
                                'counters' => $appliedCounters,
                                'counters_intext' => $appliedCounters_inText,
                                'nomer' => $tmpNomorNota,
                                'nomer2' => $tmpNomorNotaAlias,
                                'dtime' => date("Y-m-d H:i:s"),
                                'fulldate' => date("Y-m-d"),
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }
                            $masterReplacers = array(
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                                "counters" => $appliedCounters,
                                "counters_intext" => $appliedCounters_inText,
                            );
                            foreach ($masterReplacers as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }
                            $detailReplacers = array(
                                "sub_step_avail" => 1,
                                "sub_step_current" => 1,
                                "sub_step_number" => 1,
                                "next_substep_num" => "",
                                "next_substep_code" => "",
                                "next_substep_label" => "",
                                "next_subgroup_code" => "",
                            );
                            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                                foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                    foreach ($dSpec as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                    }
                                }
                            }
                            $itemsReplacers = array(
                                "next_substep_num" => "",
                                "next_substep_code" => "",
                                "next_substep_label" => "",
                                "next_subgroup_code" => "",
                            );
                            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                                foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                    foreach ($dSpec as $key => $val) {
                                        $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                    }
                                }
                            }

                            //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                            if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                                $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                                $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                                $_SESSION[$cCode]['tableIn_master']['cli'] = 1;
                                $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                                $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                                $tr = new MdlTransaksi();
                                $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                                $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                                cekHitam("[$insertID] :: " . $this->db->last_query());
                                $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                                $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                                $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                                if ($insertID < 1) {
                                    die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                                }
                                $mongoList['main'] = array($insertID, $epID);
                                //==transaksi_id dan nomor nota diinject kan ke gate utama
                                $injectors = array(
                                    "transaksi_id" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                );
                                $arrInjectorsTarget = array(
                                    "items",
                                    "items2_sum",
                                    "rsltItems",
                                );
                                foreach ($injectors as $key => $val) {
                                    $_SESSION[$cCode]['main'][$key] = $val;
                                    foreach ($arrInjectorsTarget as $target) {
                                        if (isset($_SESSION[$cCode][$target])) {
                                            foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                                if (isset($_SESSION[$cCode][$target][$id])) {
                                                    $_SESSION[$cCode][$target][$id][$key] = $val;
                                                }
                                            }
                                        }
                                    }
                                }

                                //===signature
                                $dwsign = $tr->writeSignature($insertID, array(
                                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                    "step_number" => 1,
                                    "step_code" => $connecTo,
                                    "step_name" => $this->configUiJenis["connectToReject"][1]["label"],
                                    "group_code" => "",
                                    "oleh_id" => $this->session->login['id'],
                                    "oleh_nama" => $this->session->login['nama'],
                                    "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                    "transaksi_id" => $masterID,
                                    "deskripsi" => "edit transaksi",
                                    "cabang_id" => $this->session->login['cabang_id'],
                                    "cabang_nama" => $this->session->login['cabang_nama'],
                                    "current_transaksi_id" => $masterID,
                                    "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                                )) or die("Failed to write signature");
                                showLast_query("kuning");
                                $mongoList['sign'][] = $dwsign;
                                $idHis = array(
                                    $stepNumber => array(
                                        "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                        "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                        "step" => $stepNumber,
                                        "trID" => $insertID,
                                        "nomer" => $tmpNomorNota,
                                        "nomer2" => $tmpNomorNotaAlias,
                                        "counters" => $appliedCounters,
                                        "counters_intext" => $appliedCounters_inText,
                                    ),
                                );
                                $idHis_blob = blobEncode($idHis);
                                $idHis_intext = print_r($idHis, true);
                                $tr = new MdlTransaksi();
                                $dupState = $tr->updateData(array("id" => $insertID), array(
                                    "next_step_num" => $nextProp['num'],
                                    "next_step_code" => $nextProp['code'],
                                    "next_step_label" => $nextProp['label'],
                                    "next_group_code" => $nextProp['groupID'],

                                    //===references
//                            "id_master" => $insertID,
                                    "id_master" => $masterID,// milik transkasiID yang diedit
                                    "id_top" => $insertID,
                                    "ids_prev" => "",
                                    "ids_prev_intext" => "",
                                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                    "nomers_prev" => "",
                                    "nomers_prev_intext" => "",
                                    "jenises_prev" => "",
                                    "jenises_prev_intext" => "",
                                    "ids_his" => $idHis_blob,
                                    "ids_his_intext" => $idHis_intext,

                                )) or die("Failed to update tr next-state!");
                                cekHijau($this->db->last_query());

                                $addValues = array(
                                    //===references
                                    "id_master" => $insertID,
                                    "id_top" => $insertID,
                                    "ids_prev" => "",
                                    "ids_prev_intext" => "",
                                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                    "nomers_prev" => "",
                                    "nomers_prev_intext" => "",
                                    "jenises_prev" => "",
                                    "jenises_prev_intext" => "",
                                    "ids_his" => $idHis_blob,
                                    "ids_his_intext" => $idHis_intext,
                                );
                                foreach ($addValues as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                }

                            }
                            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                                $inserMainValues = array();
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                    //matiHEre("hooppp");
                                    $inserMainValues = array();
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                        if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                            $dd = $tr->writeMainValues($insertID, array(
                                                "key" => $key,
                                                "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                            ));

                                            $inserMainValues[] = $dd;
                                            $mongoList['mainValues'][] = $dd;
                                        }
                                    }
                                }

                                if (sizeof($inserMainValues) > 0) {
                                    $arrBlob = blobEncode($inserMainValues);
                                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                                }

                            }
                            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                                $inserMainValues = array();
                                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                    $inserMainValues[] = $dd;
                                    $mongoList['mainValues'][] = $dd;
                                }

                                if (sizeof($inserMainValues) > 0) {
                                    $arrBlob = blobEncode($inserMainValues);
                                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                    $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                    //                    cekkuning("making a clone for input key $key / $val");
                                    //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                    //                    $replacers=array(
                                    //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                    //                    );
                                    //                    foreach($replacers as $key=>$val){
                                    //                        $tmpTableIn[$key]=$val;
                                    //                    }
                                    //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                                foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                    $tr->writeMainApplets($insertID, array(
                                        "mdl_name" => $amdl,
                                        "key" => $aSpec['key'],
                                        "label" => $aSpec['labelValue'],
                                        "description" => $aSpec['description'],
                                    ));
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                    $tr->writeMainElements($insertID, array(
                                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                        "name" => $aSpec['name'],
                                        "label" => $aSpec['label'],
                                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                        "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                    ));
                                    //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

                                $insertIDs = array();
                                $insertDeIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                    if ($insertDetailID < 1) {
                                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                                    }
                                    else {
                                        $insertIDs[] = $insertDetailID;
                                        $insertDeIDs[$insertID][] = $insertDetailID;
                                        $mongoList['detail'][] = $insertDetailID;
                                    }
                                    if ($epID != 999) {
                                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                                        if ($insertEpID < 1) {
                                            die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                                        }
                                        else {
                                            $insertIDs[] = $insertEpID;
                                            $insertDeIDs[$epID][] = $insertEpID;
                                            $mongoList['detail'][] = $insertEpID;
                                        }
                                    }
                                    cekUngu($this->db->last_query());
                                }


                                if (sizeof($insertIDs) == 0) {
                                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                                }
                                else {
                                    $indexing_details = array();
                                    foreach ($insertDeIDs as $key => $numb) {
                                        $indexing_details[$key] = $numb;
                                    }

                                    foreach ($indexing_details as $k => $arrID) {
                                        $arrBlob = blobEncode($arrID);
                                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                        cekOrange($this->db->last_query());
                                    }
                                }
                            }
                            else {
                                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detail'] = $insertIDs;
                                    }
                                    cekUngu($this->db->last_query());
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                    $insertIDs[] = $insertDetailID;
                                    $mongoList['detail'][] = $insertDetailID;
                                    if ($epID != 999) {
                                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                                        $insertIDs[] = $dd;
                                        $mongoList['detail'][] = $dd;
                                    }
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detil'][] = $dd;
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detil'] = $insertIDs;
                                    }
                                    cekUngu($this->db->last_query());
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                            if (isset($_SESSION[$cCode]['tableIn_detail'][$pID])) {
                                                $dd = $tr->writeDetailValues($insertID, array(
                                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                                    "produk_id" => $pID,
                                                    "key" => $key,
                                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : "0",
                                                ));
                                                $insertIDs[$pID][] = $dd;
                                                $mongoList['detailValues'][] = $dd;

                                            }
                                        }
                                    }
                                }

                                if (sizeof($insertIDs) > 0) {
                                    $arrBlob = blobEncode($insertIDs);
                                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                                }

                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                                        $insertIDs = array();
                                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                            $dd = $tr->writeDetailValues($insertID, array(
                                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                                "produk_id" => $pID,
                                                "key" => $key,
                                                "value" => $dSpec[$src],
                                            ));
                                            $insertIDs[] = $dd;
                                            $mongoList['detailValues'][] = $dd;
                                        }
                                    }
                                }
                            }
                            //endregion

                            $baseRegistries = array(
                                'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                                'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                                'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                                'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                                'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                                'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                                'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                                "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                                //----
                                'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                                'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                                //----
                            );
                            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                            showLast_query("hijau");
                            cekHijau("SELESAI menjalankan EDITOR...");
                        }
                    }
                    else {
                        $tableIn_master['trash_4'] = 1;
                        $tableIn_master['cancel_id'] = $this->session->login['id'];
                        $tableIn_master['cancel_name'] = $this->session->login['nama'];
                        $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                        $tableIn_master['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                        $mongoList['main'][] = $epID;
                        if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                            $insertIDs = array();
                            foreach ($tableIn_detail as $dSpec) {
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                            }
                        }
                    }
                }

                $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

                //===if rollback is needed
                //rollback preproc, master
                if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                    //            cekbiru("ada config pre-proc master $stepNumCurrent");
                    $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                    //            arrprint($iterator);
                    if (sizeof($iterator) > 0) {
                        $it = 0;
                        cekbiru("ada iterator pre-proc master");
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $it++;
                            $oriComName = $tComSpec['comName'];
                            $comName = $tComSpec['comName'] . "_reverse";
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                            echo "reverse master-preproc: $comName, initializing values <br>";
                            $tmpOutParams[$cCtr] = array();


                            $subParams = array();

                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                    $subParams['static'][$key] = $realValue;

                                }

                                if (array_key_exists($oriComName, $prepConfigs)) {
                                    if (sizeof($prepConfigs[$oriComName]) > 0) {
                                        foreach ($prepConfigs[$oriComName] as $key => $src) {
                                            $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                        }
                                    }
                                }

                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $no;
                                }


                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                            }
                            if (sizeof($subParams) > 0) {
                                $tmpOutParams[$cCtr] = $subParams;
                            }


                            $mdlName = "Pre" . ucfirst($comName);
                            $this->load->model("Preprocs/" . $mdlName);
                            $m = new $mdlName($resultParams);


                            if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                $tobeExecuted = true;
                            }
                            else {
                                $tobeExecuted = false;
                            }

                            if ($tobeExecuted) {
                                arrprint($tmpOutParams[$cCtr]);
                                $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $gotParams = $m->exec();


                            }
                            else {
                                cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                            }

                        }
                    }
                }
                else {
                    cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
                }
                //rollback preproc, detail
                if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                    //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                    $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                    //            arrprint($iterator);
                    if (sizeof($iterator) > 0) {
                        $it = 0;
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $it++;
                            $oriComName = $tComSpec['comName'];
                            $comName = $tComSpec['comName'] . "_reverse";
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            echo "reverse preproc (detail): $comName, initializing values <br>";
                            foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                                $tmpOutParams[$cCtr] = array();
                                //                        $id = $dSpec['id'];
                                $id = $xid;
                                $subParams = array();

                                if (isset($tComSpec['static'])) {
                                    foreach ($tComSpec['static'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                        $subParams['static'][$key] = $realValue;

                                    }

                                    if (array_key_exists($oriComName, $prepConfigs)) {
                                        cekhitam("terdapat di dalam prepConfig");
                                        if (sizeof($prepConfigs[$oriComName]) > 0) {
                                            foreach ($prepConfigs[$oriComName] as $key => $src) {
                                                $subParams['static'][$key] = makeValue($src, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                            }
                                        }
                                    }
                                    else {
                                        cekhitam("TIDAK terdapat di dalam prepConfig");
                                    }
                                    if (!isset($subParams['static']["transaksi_id"])) {
                                        $subParams['static']["transaksi_id"] = $no;
                                    }


                                    $subParams['static']["fulldate"] = date("Y-m-d");
                                    $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                }

                                if (sizeof($subParams) > 0) {

                                    $tmpOutParams[$cCtr][] = $subParams;
                                }


                                $comName = $tComSpec['comName'] . "_reverse";
                                $srcGateName = $tComSpec['srcGateName'];
                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                                echo "sub preproc #$it: $comName, sending values <br>";

                                $mdlName = "Pre" . ucfirst($comName);
                                $this->load->model("Preprocs/" . $mdlName);
                                $m = new $mdlName($resultParams);


                                if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                    $tobeExecuted = true;
                                }
                                else {
                                    $tobeExecuted = false;
                                }

                                if ($tobeExecuted) {

                                    //                            arrprint($tmpOutParams[$cCtr]);

                                    $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $gotParams = $m->exec();

                                    //                            cekbiru("gotparams");
                                    //                            arrprint($gotParams);

                                }
                                else {
                                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                }

                            }
                        }
                    }
                }
                else {
                    cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
                }
                //rollback postproc, master
                if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                    //            cekbiru("ada config pre-proc master $stepNumCurrent");
                    $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $oriComName = $tComSpec['comName'];
                            $comName = $tComSpec['comName'];
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            echo "rollback main post-processor: $comName<br>";

                            $dSpec = $_SESSION[$cCode][$srcGateName];
                            $tmpOutParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                    $tmpOutParams['loop'][$key] = $realValue;

                                }
                            }
                            if (isset($tComSpec['static'])) {
                                //cekHere("DISINI OIII");
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                    $tmpOutParams['static'][$key] = $realValue;

                                }
                                if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                    $tmpOutParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                    $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                }

                                $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];


                            }
                            if (isset($tComSpec['static2'])) {
                                //cekHere("DISINI OIII");
                                foreach ($tComSpec['static2'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                    $tmpOutParams['static2'][$key] = $realValue;

                                }
                                if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                    $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                    $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                }

                                $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                                $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                                $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                            }


                            if (array_key_exists($oriComName, $postConfigs)) {
                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                    foreach ($postConfigs[$oriComName] as $key) {
                                        $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                        cekbiru("oldVal: $oldVal");
                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                        cekHijau("newVal: $newVal");
                                        $tmpOutParams['static'][$key] = $newVal;

                                        if (isset($tmpOutParams['loop'][$key])) {
                                            cekMerah("masuk disini...");
                                            $oldLoopVal = isset($tmpOutParams['loop'][$key]) ? $tmpOutParams['loop'][$key] : 0;
                                            $newLoopVal = $oldLoopVal < 0 ? abs($oldLoopVal) : -($oldLoopVal);
                                            $tmpOutParams['loop'][$key] = $newLoopVal;
                                        }
                                    }
                                }
                            }

                            //lgShowError("Ada kesalahan",);
                            $mdlName = "Com" . ucfirst($comName);
                            $this->load->model("Coms/" . $mdlName);
                            $m = new $mdlName();

                            cekBiru("kiriman rollback main-postproc $comName");
                            arrPrint($tmpOutParams);
                            $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


                        }
                    }
                }
                else {
                    cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
                }
                //rollback postproc, detail
                if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                    $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                    //------
                    cekHitam(":: tambahan bila reject step 1 ::");
                    if (isset($this->configUi[$jenisTr]["lockerCheck"]) && ($this->configUi[$jenisTr]["lockerCheck"] == true) && ($stepNumCurrent == 1)) {
                        cekHitam(":: kembalikan locker stok ke active ::");
//                    $iterator[98] = array(
//                        "comName" => "LockerStock",
//                        "loop" => array(),
//                        "static" => array
//                        (
//                            "cabang_id" => "placeID",
//                            "jenis" => ".produk",
//                            "state" => ".hold",
//                            "jumlah" => "qty",
//                            "produk_id" => "id",
//                            "nama" => "name",
//                            "satuan" => "satuan",
//                            "oleh_id" => "olehID",
//                            "oleh_nama" => "olehName",
//                            "transaksi_id" => ".0",
//                            "nomer" => ".0",
//                            "gudang_id" => "gudangID",
//                        ),
//                        "reversable" => 1,
//                        "srcGateName" => "items",
//                        "srcRawGateName" => "items",
//                    );
//                    $iterator[99] = array(
//                        "comName" => "LockerStock",
//                        "loop" => array(),
//                        "static" => array
//                        (
//                            "cabang_id" => "placeID",
//                            "jenis" => ".produk",
//                            "state" => ".active",
//                            "jumlah" => "-qty",
//                            "produk_id" => "id",
//                            "nama" => "name",
//                            "satuan" => "satuan",
//                            "oleh_id" => ".0",
//                            "oleh_nama" => ".0",
//                            "transaksi_id" => ".0",
//                            "nomer" => ".0",
//                            "gudang_id" => "gudangID",
//                        ),
//                        "reversable" => 1,
//                        "srcGateName" => "items",
//                        "srcRawGateName" => "items",
//                    );
                        $iteratorAdd = array();
                        foreach ($iterator as $cCtr => $tComSpec) {
                            if (isset($tComSpec['static']['state']) && ($tComSpec['static']['state'] == '.hold')) {
                                if (isset($tComSpec['static']['oleh_id']) && ($tComSpec['static']['oleh_id'] != '.0')) {
                                    // bila state == .hold dan oleh_id != .0, maka dibuatkan ::
                                    // HOLD, +QTY, oleh_id dan ACTIVE, -QTY
                                    $tComSpecAddHold = $tComSpec;
                                    $tComSpecAddActive = $tComSpec;
                                    $staticReplaceHold = array(
                                        "jumlah" => "qty",
                                        "transaksi_no" => ".0",
                                    );
                                    $staticReplaceActive = array(
                                        "jumlah" => "-qty",
                                        "transaksi_id" => ".0",
                                        "nomer" => ".0",
                                        "state" => ".active",
                                        "oleh_id" => ".0",
                                        "oleh_nama" => "",
                                        "transaksi_no" => ".0",
                                    );
                                    foreach ($staticReplaceHold as $k_rpc => $v_rpc) {
                                        $tComSpecAddHold['static'][$k_rpc] = $v_rpc;
                                    }
                                    foreach ($staticReplaceActive as $k_rpc => $v_rpc) {
                                        $tComSpecAddActive['static'][$k_rpc] = $v_rpc;
                                    }

                                    $iteratorAdd[101] = $tComSpecAddHold; // postprocc hold by orang, no trID
                                    $iteratorAdd[102] = $tComSpecAddActive; // postprocc active, no orang, no trID
                                }
                            }
                        }
                        if (sizeof($iteratorAdd) > 0) {
                            foreach ($iteratorAdd as $ii => $spec) {
                                $iterator[$ii] = $spec;
                            }
                        }
                    }
                    //------
//                arrPrintPink($iterator);
//                mati_disini(__LINE__);

                    if (sizeof($iterator) > 0) {
                        foreach ($iterator as $cCtr => $tComSpec) {
                            $oriComName = $tComSpec['comName'];
                            $comName = $tComSpec['comName'];
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            echo "rollback sub-postProcessor: $comName, initializing values <br>";
                            //                arrPrint($_SESSION[$cCode][$srcGateName]);
                            $tmpOutParams[$cCtr] = array();
                            foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                                $subParams = array();
                                if (isset($tComSpec['loop'])) {
                                    foreach ($tComSpec['loop'] as $key => $value) {

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                        $subParams['loop'][$key] = $realValue;
                                        if (isset($subParams['loop'][$key])) {
                                            cekMerah("masuk disini...");
                                            $oldLoopVal = isset($subParams['loop'][$key]) ? $subParams['loop'][$key] : 0;
                                            $newLoopVal = $oldLoopVal < 0 ? abs($oldLoopVal) : -($oldLoopVal);
                                            $subParams['loop'][$key] = $newLoopVal;
                                        }
                                    }
                                }
                                if (isset($tComSpec['static'])) {
                                    foreach ($tComSpec['static'] as $key => $value) {
                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                        $subParams['static'][$key] = $realValue;
                                        //                                cekBiru("$key diisi dengan $realValue");
                                    }

                                    if (array_key_exists($oriComName, $postConfigs)) {
                                        //                                cekhitam("terdapat di dalam postConfig");
                                        if (sizeof($postConfigs[$oriComName]) > 0) {
                                            foreach ($postConfigs[$oriComName] as $key) {
                                                //                                        $replVal=makeValue($src,$_SESSION[$cCode][$srcGateName][$cnt],$_SESSION[$cCode][$srcGateName][$cnt],0);
                                                //                                        cekbiru("$key akan direplace dengan nilai $replVal");
                                                //                                        $subParams['static'][$key]=$replVal;

                                                $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                cekbiru("oldVal2: $oldVal");
                                                $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                cekHijau("newVal2: $newVal");
                                                $subParams['static'][$key] = $newVal;
                                                //                                $tmpOutParams['static'][$key]=makeValue($src,$_SESSION[$cCode][$srcGateName],$_SESSION[$cCode][$srcGateName],0);
                                                //                                        $tmpOutParams['static'][$key]=$newVal;
                                            }
                                        }
                                    }
                                    else {
                                        //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                    }


                                    if (!isset($subParams['static']["transaksi_id"])) {
                                        $subParams['static']["transaksi_id"] = $no;
                                    }
                                    if (!isset($subParams['static']["transaksi_no"])) {
                                        $subParams['static']["transaksi_no"] = $currentNomer;
                                    }
                                    $subParams['static']["fulldate"] = date("Y-m-d");
                                    $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $subParams['static']["keterangan"] = "rollback of $no";
                                    $subParams['static']["rejection"] = true;
                                }


                                if (sizeof($subParams) > 0) {
                                    $tmpOutParams[$cCtr][] = $subParams;
                                }
                            }
                        }
                        arrPrintHijau($tmpOutParams);
//                        mati_disini(__LINE__);


                        foreach ($iterator as $cCtr => $tComSpec) {
                            $oriComName = $tComSpec['comName'];
                            $comName = $tComSpec['comName'];
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            echo "sub-postProcessor: $comName, sending values <br>";

                            $mdlName = "Com" . ucfirst($comName);
                            $this->load->model("Coms/" . $mdlName);
                            $m = new $mdlName();


                            cekBiru("kiriman rollback detail-postproc $comName");
                            arrPrint($tmpOutParams[$cCtr]);
                            $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        }
                    }
                }
                else {
                    cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                }

            }

        }


        if (sizeof($referenceRevertConfigs) > 0) {
            if (isset($referenceRevertConfigs['enabled']) && ($referenceRevertConfigs['enabled'] == true)) {

                $arrQtyRevert = array();
                foreach ($items as $spec) {
                    $arrQtyRevert[$spec['id']] = $spec['qty'];
                }

                $referenceID = $_SESSION[$cCode]['main'][$referenceRevertConfigs['referenceID']];
                cekHitam(":: $referenceID ::");

                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $refTr = $tr->lookupDetailTransaksi($referenceID)->result();
                if (sizeof($refTr) > 0) {
                    foreach ($refTr as $spec) {
                        $qty = isset($arrQtyRevert[$spec->produk_id]) ? $arrQtyRevert[$spec->produk_id] : 0;
                        $data = array(
                            "valid_qty" => $spec->valid_qty + $qty,
                            "req_cancel_qty" => $spec->req_cancel_qty - $qty,
                        );
                        $where = array(
                            "produk_id" => $spec->produk_id,
                            "transaksi_id" => $spec->transaksi_id,
                        );
                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData($where, $data);
                        $mongListUpadte['update']['detail'][] = array(
                            "where" => $where,
                            "value" => $data,
                        );
                        cekPink2($this->db->last_query());
                    }
                }

                //arrPrint($arrQtyRevert);
            }
        }


        //region reaktivasi project karena didelete
        $iterator = isset($this->configCore[$jenisTr]['postProcRevert'][$jenisTarget]["detail"]) ? $this->configCore[$jenisTr]['postProcRevert'][$jenisTarget]["detail"] : array();

        // if(sizeof($iterator)>0){
        //     foreach ($iterator as $cCtr => $tComSpec) {
        //         $comName = $tComSpec['comName'];
        //         $srcGateName = $tComSpec['srcGateName'];
        //         $srcRawGateName = $tComSpec['srcRawGateName'];
        //         echo "sub-postProcessor: $comName, initializing values <br>";
        //         echo "<script>top.writeProgress('MENYIAPKAN DATA SUB-PROCESSORS UNTUK DIKIRIM...', 'head');</script>";
        //
        //         $tmpOutParams[$cCtr] = array();
        //         foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
        //             $subParams = array();
        //             if (isset($tComSpec['loop'])) {
        //                 foreach ($tComSpec['loop'] as $key => $value) {
        //
        //                     $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
        //                     $subParams['loop'][$key] = $realValue;
        //
        //                 }
        //             }
        //             if (isset($tComSpec['static'])) {
        //                 foreach ($tComSpec['static'] as $key => $value) {
        //
        //                     $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
        //                     $subParams['static'][$key] = $realValue;
        //                     cekBiru("$key diisi dengan $realValue");
        //
        //                 }
        //
        //                 if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
        //                     foreach ($paramPatchers[$comName] as $k => $v) {
        //                         if (!isset($subParams['static'][$k])) {
        //                             $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                         }
        //                     }
        //                 }
        //                 if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
        //                     $jenis = $_SESSION[$cCode]['main']['jenis'];
        //                     foreach ($paramForceFillers[$comName] as $k => $v) {
        //                         $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                         cekorange(":: $k diisikan dengan " . $subParams['static'][$k]);
        //                     }
        //                 }
        //
        //                 $subParams['static']["fulldate"] = date("Y-m-d");
        //                 $subParams['static']["dtime"] = date("Y-m-d H:i:s");
        //                 $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
        //             }
        //
        //             if (sizeof($subParams) > 0) {
        //                 $tmpOutParams[$cCtr][] = $subParams;
        //             }
        //             echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
        //         }
        //     }
        //
        //     foreach ($iterator as $cCtr => $tComSpec) {
        //         $comName = $tComSpec['comName'];
        //         $srcGateName = $tComSpec['srcGateName'];
        //         $srcRawGateName = $tComSpec['srcRawGateName'];
        //         echo "sub-postProcessor: $comName, sending values <br>";
        //         echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
        //         $mdlName = "Com" . ucfirst($comName);
        //         $this->load->model("Coms/" . $mdlName);
        //         $m = new $mdlName();
        //
        //         $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //         $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //         cekBiru($this->db->last_query());
        //     }
        //     matiHere($stepNumCurrent." ".$jenisTarget);
        // }
        $configPostRevertMain = isset($this->configCore[$jenisTr]['postProcRevert'][$jenisTarget]["master"]) ? $this->configCore[$jenisTr]['postProcRevert'][$jenisTarget]["master"] : array();

        //endregion
        //==================================================================================================
        //==MENGUPDATE LOCKER TRANSAKSI ====================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, NULL);
        //==================================================================================================


        //region update db project
        $this->load->model("Mdls/" . "MdlProdukProject");
        $o = new MdlProdukProject();
        $o->addFilter("transaksi_id='$transaksiID_reference'");
        $o->addFilter("status='1'");
        $tempProdukMaster = $o->lookUpAll()->result();

        if (count($tempProdukMaster) == 1) {
            $arrUpdate = array(
                "status" => 0,
                "trash" => 1,
                "closing_status" => 99, //99 = TRANSAKSI DIBATALKAN 1 = TRANSAKSI LENGKAP
                "closing_oleh_id" => $this->session->login['id'],
                "closing_oleh_nama" => $this->session->login['nama'],
                "closing_dtime" => date("Y-m-d H:i:s"),
                "closing_transaksi_nomer" => "TRANSAKSI DIBATALKAN",
            );
            $where = array(
                "id" => $tempProdukMaster[0]->id
            );
            $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
        }
        else {
            die(lgShowError("Ada kesalahan", "tidak ditemukan $transaksiID_reference pada transaksi_id project"));
        }

        //endregion update db project

        //==tampilkan receipt
        cekMerah("-- DONE --");


        echo "<script>top.close_holdon()</script>";


//        mati_disini("REJECT BERHASIL, saat ini sedang maintenance...");


        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }
        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }
        $arrAlert = array(
            "type" => "success",
            "title" => "Transaction updated",
            //                        "html" => "your order has been saved and ready to process",
            "html" => $this->session->errMsg,
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );

        echo swalAlert($arrAlert);
        echo topReload();

        unset($this->session->errMsg);
    }

    public function doRevertAll()
    {
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }


        $transaksiID_reference = $no = $this->uri->segment(5);
        $jenisTr_con = $jenisTr = $this->uri->segment(4);
        //        $masterTargetStepNum_con = $masterTargetStepNum = $this->uri->segment(5);
        //        $childTargetStepNum_con = $childTargetStepNum = $this->uri->segment(6);
        $stepNumCurrent = $stepNumCurrent = $masterTargetStepNum = $childTargetStepNum = $this->uri->segment(6);
        $cCode = "_TR_" . $jenisTr;


        // region transaksi yang dibuka
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("id='$no'");
        $tmpTr = $tr->lookupMainTransaksi()->result();
        //        cekOrange($this->db->last_query());
        $insertID = $tmpTr[0]->id;
        $insertNum = $tmpTr[0]->nomer;
        $masterID = $tmpTr[0]->id_master;
        // endregion transaksi yang dibuka
        cekHitam("trID: $insertID, masterID: $masterID");

        $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["target"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["target"] : NULL;

        //region membaca transaksi berdasarkan masterID
        $trm = new MdlTransaksi();
        $trm->setFilters(array());
        $trm->addFilter("id_master='$masterID'");
        $trm->addFilter("link_id='0'");
        $trm->addFilter("trash_4='0'");
        $tmpTrm = $trm->lookupMainTransaksi()->result();
        showLast_query("biru");
        $indexReg = array();
        $arrMainDataTrans = array();
        $arrMainDataTransID = array();
        $arrTrIDs = array();
        $regParam = array(
            "main",
            "items",
            "tableIn_master",
            "tableIn_detail",
        );
        foreach ($tmpTrm as $tmpTrmSpec) {
            $arrMainDataTransID[$tmpTrmSpec->id] = array(
                "step" => $tmpTrmSpec->step_number,
                "jenisTr" => $tmpTrmSpec->jenis_master,
                "transaksi_id" => $tmpTrmSpec->id,
                "nomer" => $tmpTrmSpec->nomer,
            );
//            $indexRegTmp = blobDecode($tmpTrmSpec->indexing_registry);
//            foreach ($indexRegTmp as $key => $val) {
//                if (in_array($key, $regParam)) {
//                    $indexReg[] = $val;
//                }
//            }
            $arrTrIDs[$tmpTrmSpec->id] = $tmpTrmSpec->id;
        }
        //endregion

        krsort($arrMainDataTransID);


        //region swap from registry
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
//        $tr->addFilter("transaksi_id in ('" . implode("','", $indexReg) . "')");
        $tr->addFilter("transaksi_id in ('" . implode("','", $arrTrIDs) . "')");
        $tmpReg = $tr->lookupDataRegistries()->result();
        //        cekmerah($this->db->last_query());

        $tmpRegData = array();
        if (sizeof($tmpReg) > 0) {
            foreach ($tmpReg as $row) {
                foreach ($row as $key_reg => $val_reg) {
                    if (in_array($key_reg, $regParam)) {
                        $tmpRegData[$row->transaksi_id][$key_reg] = $val_reg;
                    }
                }
            }
        }
        //endregion
        //arrPrintWebs($arrMainDataTransID);
//        arrPrintWebs($arrTrIDs);
//        arrPrintWebs($tmpRegData);
//        mati_disini("line " . __LINE__);

        $this->db->trans_start();


        //        $referenceRevertConfigs = isset($this->configUi[$jenisTr]['referenceRevert']) ? $this->configUi[$jenisTr]['referenceRevert'] : array();
        $prepConfigs = null != $this->config->item('hePreProcessors') ? $this->config->item('hePreProcessors') : array();
        $postConfigs = null != $this->config->item('hePostProcessors') ? $this->config->item('hePostProcessors') : array();
        $postDeniedConfigs = null != $this->config->item('hePostProcessorsDenied') ? $this->config->item('hePostProcessorsDenied') : array();


        $nextProp = array(
            "num" => 0,
            "code" => "",
            "label" => "",
            "groupID" => "",
        );

        $resultRejectID = array();
        $mongListUpadte = array();
        $mongoList = array();
        foreach ($arrMainDataTransID as $arrMainDataTransIDSpec) {

            $no = $arrMainDataTransIDSpec['transaksi_id'];
            $stepNumCurrent = $arrMainDataTransIDSpec['step'];
            $jenisTr = $arrMainDataTransIDSpec['jenisTr'];
            cekUngu(":: trID yang dibatalkan $no ::");
            $tp = new MdlTransaksi();
            $tp->addFilter("id='$no'");
            $tpTmp = $tp->lookupAll()->result();
            $currentMasterID = $tpTmp[0]->id_master;
            $currentProjectID = $tpTmp[0]->project_id;


            cekHitam("MENGEMBALIKAN PRE & POST UNTUK STEP $stepNumCurrent");

            $arrData = array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNumCurrent,
                //                "step_number" => $stepNumCurrent,
                "trash_4" => "1",
                "cancel_dtime" => date("Y-m-d H:i:s"),
                "cancel_name" => $this->session->login['nama'],
                "cancel_id" => $this->session->login['id'],
            );
            $arrData_detail = array(
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "next_substep_num" => $nextProp['num'],
                "sub_step_number" => 0,
            );

            foreach ($tmpRegData[$no] as $key_reg => $val_reg) {

                $var = $key_reg;
                $$var = blobDecode($val_reg);
            }


            //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
            $tp = new MdlTransaksi();
            $dupState = $tp->updateData(array(
                "id" => $no,
            ), $arrData) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array("id" => $no,),
                "value" => $arrData,
            );
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            $to = new MdlTransaksi();
            $to->setFilters(array());
            $to->setTableName($to->getTableNames()['detail']);
            $dupState = $to->updateData(array(
                "transaksi_id" => $no,
                "trash" => 0,
            ), $arrData_detail) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['detail'][] = array(
                "where" => array(
                    "transaksi_id" => $no,
                    "trash" => 0,
                ),
                "value" => $arrData_detail,
            );
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            //endregion


            //region sesuaikan signature untuk cloningan, ikut minus
            $arrSign = array(
                "prev_id" => $no,
                "nomer" => "rejection",
                "step_number" => -$stepNumCurrent, // ini minus step number
                "step_code" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['target'],
                "step_name" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['label'],
                "group_code" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['userGroup'],
                "oleh_id" => $this->session->login['id'],
                "oleh_nama" => $this->session->login['nama'],
                "keterangan" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['label'] . " oleh " . $this->session->login['nama'],
            );
            $dwsign = $tr->writeSignature($tmpTr[0]->id_top, $arrSign) or die("Failed to write signature");
            $mongoList['sign'][] = $dwsign;
            cekPink2($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion


            // region netralisasi payment source
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $tr->addFilter("sisa>0");
            $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
            cekBiru($this->db->last_query());
            if (sizeof($paymentSrc) > 0) {
                foreach ($paymentSrc as $pSpec) {
                    if ($pSpec->terbayar == 0) {
                        $where = array(
                            "id" => $pSpec->id,
                            "transaksi_id" => $pSpec->transaksi_id,
                        );
                        $data = array(
                            "sisa" => 0,
                            "returned" => $pSpec->sisa,
                            "sisa_valas" => 0,
                            "returned_valas" => $pSpec->sisa_valas,
                            "cancel_id" => $this->session->login['id'],
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                        );

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->updatePaymentSrc($where, $data);
                        cekUngu(":: mereject payment source bila ada...");
                        cekUngu($this->db->last_query());
                    }
                    else {
                        mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                    }
                }
            }
            else {
                cekBiru(":: tidak ada payment source... ::");
            }
            // endregion netralisasi payment source

            // region netralisasi extended step
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $exTmp = $tr->lookupExtStepByTrID($no);
            if (sizeof($exTmp) > 0) {
                foreach ($exTmp as $exSpec) {

                    $tra = New MdlTransaksi();
                    $tra->setFilters(array());
                    $tra->rejectExtStepByID($exSpec['id']);
                    $mongListUpadte['update']['extra'][] = array(
                        "where" => array(
                            "id" => $exSpec['id'],
                        ),
                        "value" => array(
                            "state" => "-1",
                        ),
                    );
                    cekUngu(":: mereject extended step bila ada...");
                    cekUngu($this->db->last_query());
                }
            }
            else {
                cekBiru(":: tidak ada extended step... ::");
            }

            // endregion netralisasi extended step


            // region menulis entry point
            if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                    if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                        $masterID = $currentMasterID;
                        $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        $tCodeTargetJenisTransaksi = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        $modul_transaksi = $this->modul;
                        cekHijau("START menjalankan REJECT ALL... [$masterID] [$connecTo]");
                        if ($connecTo == NULL) {
                            mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                        }
                        $oldCode = $cCode;
                        $cCode = "_TR_" . $connecTo;
                        $_SESSION[$cCode] = array(
                            'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                            'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                            'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                        );
                        // masuk ke gerbang TableInMaster, tabel transaksi
                        $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "trash_4" => 1,
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                            "deskripsi" => "rejection",
                            "oleh_id" => my_id(),
                            "oleh_nama" => my_name()
                        );
                        // masuk ke gerbang main
                        $masterReplacersO = array(
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "olehID" => my_id(),
                            "olehName" => my_name(),
                        );
                        foreach ($masterReplacersO as $key => $val) {
                            $_SESSION[$cCode]['main'][$key] = $val;
                        }
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }

                        //region penomoran receipt
                        $this->load->model("CustomCounter");
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $cn->setModul($modul_transaksi);
                        $cn->setStepCode($tCodeTargetJenisTransaksi);
                        $counterForNumber = array($this->configCore[$this->jenisTr]['formatNotaEdit']);
                        if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['countersEdit'])) {
                            die(__LINE__ . " Used number should be registered in 'counters' config as well");
                        }
                        echo "<div style='background:#ff7766;'>";
                        foreach ($counterForNumber as $i => $cRawParams) {
                            $cParams = explode("|", $cRawParams);
                            $cValues = array();
                            foreach ($cParams as $param) {
                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            }
                            $cRawValues = implode("|", $cValues[$i]);
                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                        }
                        echo "</div style='background:#ff7766;'>";

                        $stepNumber = 1;
                        $tmpNomorNota = $paramSpec['paramString'];
                        $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                        $nextProp = array(
                            "num" => 0,
                            "code" => "",
                            "label" => "",
                            "groupID" => "",
                        );
                        //endregion

                        //region dynamic counters
                        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $cn->setModul($modul_transaksi);
                        $cn->setStepCode($tCodeTargetJenisTransaksi);
                        $configCustomParams = $this->configCore[$this->jenisTr]['countersEdit'];
                        arrPrintHijau($configCustomParams);
                        $configCustomParams[] = "stepCode";
                        //arrPrint($configCustomParams);
                        if (sizeof($configCustomParams) > 0) {
                            $cContent = array();
                            foreach ($configCustomParams as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
                                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                switch ($paramSpec['id']) {
                                    case 0: //===counter type is new
                                        $paramKeyRaw = print_r($cParams, true);
                                        $paramValuesRaw = print_r($cValues[$i], true);
                                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                        break;
                                    default: //===counter to be updated
                                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                        break;
                                }
                                //echo "<hr>";
                            }
                        }
                        $appliedCounters = base64_encode(serialize($cContent));
                        $appliedCounters_inText = print_r($cContent, true);
                        //mati_disini();

//arrPrintPink("SINI LINE:  " . __LINE__ );
//arrPrintPink($tmpNomorNota);
                        //
                        //region addition on master


                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                            "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "step_number" => 1,
                            "step_current" => 1,
                            "next_step_num" => $nextProp['num'],
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "tail_number" => 1,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        //endregion

                        //
                        //region addition on detail
                        $addSubValues = array(
                            "sub_step_number" => 1,
                            "sub_step_current" => 1,
                            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "next_substep_num" => $nextProp['num'],
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "sub_tail_number" => 1,
                            "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                            foreach ($addSubValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                            }
                        }
                        //endregion
                        // </editor-fold>
                        //endregion

                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $masterReplacers = array(
                            "nomer" => $tmpNomorNota,
                            "nomer2" => $tmpNomorNotaAlias,
                            "counters" => $appliedCounters,
                            "counters_intext" => $appliedCounters_inText,
                        );
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $detailReplacers = array(
                            "sub_step_avail" => 1,
                            "sub_step_current" => 1,
                            "sub_step_number" => 1,
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                }
                            }
                        }
                        $itemsReplacers = array(
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                            foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                }
                            }
                        }

                        //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                        if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                            $_SESSION[$cCode]['tableIn_master']['cli'] = 1;
                            $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                            $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                            $tr = new MdlTransaksi();
                            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                            cekHitam("[$insertID] :: " . $this->db->last_query());
                            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                            $_SESSION[$cCode]['main']['nomer'] = $insertNum;

                            $resultRejectID[$no] = array(
                                "insertID" => $insertID,
                                "insertNum" => $insertNum,
                                "epID" => $epID,
                            );

                            if ($insertID < 1) {
                                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            $mongoList['main'] = array($insertID, $epID);
                            //==transaksi_id dan nomor nota diinject kan ke gate utama
                            $injectors = array(
                                "transaksi_id" => $insertID,
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                            );
                            $arrInjectorsTarget = array(
                                "items",
                                "items2_sum",
                                "rsltItems",
                            );
                            foreach ($injectors as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                                foreach ($arrInjectorsTarget as $target) {
                                    if (isset($_SESSION[$cCode][$target])) {
                                        foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                            $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                            if (isset($_SESSION[$cCode][$target][$id])) {
                                                $_SESSION[$cCode][$target][$id][$key] = $val;
                                            }
                                        }
                                    }
                                }
                            }

                            //===signature
                            $dwsign = $tr->writeSignature($insertID, array(
                                "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                "step_number" => 1,
                                "step_code" => $connecTo,
                                "step_name" => $this->configUiJenis["connectToReject"][1]["label"],
                                "group_code" => "",
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                "transaksi_id" => $masterID,
                                "deskripsi" => "edit transaksi",
                                "cabang_id" => $this->session->login['cabang_id'],
                                "cabang_nama" => $this->session->login['cabang_nama'],
                                "current_transaksi_id" => $masterID,
                                "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                            )) or die("Failed to write signature");
                            showLast_query("kuning");
                            $mongoList['sign'][] = $dwsign;
                            $idHis = array(
                                $stepNumber => array(
                                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                    "step" => $stepNumber,
                                    "trID" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                    "counters" => $appliedCounters,
                                    "counters_intext" => $appliedCounters_inText,
                                ),
                            );
                            $idHis_blob = blobEncode($idHis);
                            $idHis_intext = print_r($idHis, true);
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $insertID), array(
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],

                                //===references
//                            "id_master" => $insertID,
                                "id_master" => $masterID,// milik transkasiID yang diedit
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,

                            )) or die("Failed to update tr next-state!");
                            cekHijau($this->db->last_query());

                            $addValues = array(
                                //===references
                                "id_master" => $insertID,
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                            $inserMainValues = array();
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                //matiHEre("hooppp");
                                $inserMainValues = array();
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                    if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                        $dd = $tr->writeMainValues($insertID, array(
                                            "key" => $key,
                                            "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                        ));

                                        $inserMainValues[] = $dd;
                                        $mongoList['mainValues'][] = $dd;
                                    }
                                }
                            }

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }

                        }
                        if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                            $inserMainValues = array();
                            foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                                $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                $inserMainValues[] = $dd;
                                $mongoList['mainValues'][] = $dd;
                            }

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                            foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                //                    cekkuning("making a clone for input key $key / $val");
                                //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                //                    $replacers=array(
                                //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                //                    );
                                //                    foreach($replacers as $key=>$val){
                                //                        $tmpTableIn[$key]=$val;
                                //                    }
                                //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                            foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                            foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                $tr->writeMainApplets($insertID, array(
                                    "mdl_name" => $amdl,
                                    "key" => $aSpec['key'],
                                    "label" => $aSpec['labelValue'],
                                    "description" => $aSpec['description'],
                                ));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                            foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                $tr->writeMainElements($insertID, array(
                                    "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                    "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                    "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                    "name" => $aSpec['name'],
                                    "label" => $aSpec['label'],
                                    "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                    "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                ));
                                //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

                            $insertIDs = array();
                            $insertDeIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                if ($insertDetailID < 1) {
                                    die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                                }
                                else {
                                    $insertIDs[] = $insertDetailID;
                                    $insertDeIDs[$insertID][] = $insertDetailID;
                                    $mongoList['detail'][] = $insertDetailID;
                                }
                                if ($epID != 999) {
                                    $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                                    if ($insertEpID < 1) {
                                        die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                                    }
                                    else {
                                        $insertIDs[] = $insertEpID;
                                        $insertDeIDs[$epID][] = $insertEpID;
                                        $mongoList['detail'][] = $insertEpID;
                                    }
                                }
                                cekUngu($this->db->last_query());
                            }


                            if (sizeof($insertIDs) == 0) {
                                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong (LINE: ".__LINE__.")."));
                            }
                            else {
                                $indexing_details = array();
                                foreach ($insertDeIDs as $key => $numb) {
                                    $indexing_details[$key] = $numb;
                                }

                                foreach ($indexing_details as $k => $arrID) {
                                    $arrBlob = blobEncode($arrID);
                                    $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                    cekOrange($this->db->last_query());
                                }
                            }
                        }
                        else {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong (LINE: ".__LINE__.")."));
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                                if ($epID != 999) {
                                    $dd = $tr->writeDetailEntries($epID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detail'][] = $dd;
                                }
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $dd;
                                $mongoList['detil'][] = $dd;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detil'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                        if (isset($_SESSION[$cCode]['tableIn_detail'][$pID])) {
                                            $dd = $tr->writeDetailValues($insertID, array(
                                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                                "produk_id" => $pID,
                                                "key" => $key,
                                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : "0",
                                            ));
                                            $insertIDs[$pID][] = $dd;
                                            $mongoList['detailValues'][] = $dd;

                                        }
                                    }
                                }
                            }

                            if (sizeof($insertIDs) > 0) {
                                $arrBlob = blobEncode($insertIDs);
                                $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                                    $insertIDs = array();
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                        $dd = $tr->writeDetailValues($insertID, array(
                                            "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                            "produk_id" => $pID,
                                            "key" => $key,
                                            "value" => $dSpec[$src],
                                        ));
                                        $insertIDs[] = $dd;
                                        $mongoList['detailValues'][] = $dd;
                                    }
                                }
                            }
                        }
                        //endregion

                        $baseRegistries = array(
                            'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                            'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                            'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                            'items5' => isset($_SESSION[$cCode]['items5']) ? $_SESSION[$cCode]['items5'] : array(),
                            'items7' => isset($_SESSION[$cCode]['items7']) ? $_SESSION[$cCode]['items7'] : array(),
                            'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                            //----
                            'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                            'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                            //----
                        );
                        $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                        showLast_query("hijau");
                        cekHijau("SELESAI menjalankan REJECT ALL...");
                    }
                }
                else {
                    $tableIn_master['trash_4'] = 1;
                    $tableIn_master['deskripsi'] = "rejection";
                    $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                    $tableIn_master['cancel_name'] = $this->session->login['nama'];
                    $tableIn_master['cancel_id'] = $this->session->login['id'];
                    $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                    $mongoList['main'][] = $epID;
                    showLast_query("pink");
                    if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                        $insertIDs = array();
                        foreach ($tableIn_detail as $dSpec) {
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                showLast_query("pink2");
                            }
                        }
                    }
                }
            }
            // endregion menulis entry point


            $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;

//mati_disini("jenisTr target $jenisTr_component");
            //rollback preproc, master
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    cekbiru("ada iterator pre-proc master");
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                        $gateItems = $$srcGateName;

                        echo "reverse master-preproc: $comName, initializing values <br>";
                        $tmpOutParams[$cCtr] = array();


                        $subParams = array();

                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $gateItems, $gateItems, 0);
                                $subParams['static'][$key] = $realValue;

                            }

                            if (array_key_exists($oriComName, $prepConfigs)) {
                                if (sizeof($prepConfigs[$oriComName]) > 0) {
                                    foreach ($prepConfigs[$oriComName] as $key => $src) {
                                        $subParams['static'][$key] = makeValue($src, $gateItems, $gateItems, 0);
                                    }
                                }
                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                $subParams['static']["transaksi_id"] = $no;
                            }


                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                        }
                        if (sizeof($subParams) > 0) {
                            $tmpOutParams[$cCtr] = $subParams;
                        }


                        $mdlName = "Pre" . ucfirst($comName);
                        $this->load->model("Preprocs/" . $mdlName);
                        $m = new $mdlName($resultParams);


                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                            $tobeExecuted = true;
                        }
                        else {
                            $tobeExecuted = false;
                        }

                        if ($tobeExecuted) {
                            arrprint($tmpOutParams[$cCtr]);
                            $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();


                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
            }
            //rollback preproc, detail
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "reverse preproc (detail): $comName, initializing values <br>";
                        foreach ($gateItems as $xid => $dSpec) {
                            $tmpOutParams[$cCtr] = array();
                            //                        $id = $dSpec['id'];
                            $id = $xid;
                            $subParams = array();

                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $gateItems[$id], $gateItems[$id], 0);
                                    $subParams['static'][$key] = $realValue;

                                }

                                if (array_key_exists($oriComName, $prepConfigs)) {
                                    cekhitam("terdapat di dalam prepConfig");
                                    if (sizeof($prepConfigs[$oriComName]) > 0) {
                                        foreach ($prepConfigs[$oriComName] as $key => $src) {
                                            $subParams['static'][$key] = makeValue($src, $gateItems[$id], $gateItems[$id], 0);
                                        }
                                    }
                                }
                                else {
                                    cekhitam("TIDAK terdapat di dalam prepConfig");
                                }
                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $no;
                                }


                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = "rollingback " . $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                            }

                            if (sizeof($subParams) > 0) {

                                $tmpOutParams[$cCtr][] = $subParams;
                            }


                            $comName = $tComSpec['comName'] . "_reverse";
                            $srcGateName = $tComSpec['srcGateName'];
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                            echo "sub preproc #$it: $comName, sending values <br>";

                            $mdlName = "Pre" . ucfirst($comName);
                            $this->load->model("Preprocs/" . $mdlName);
                            $m = new $mdlName($resultParams);


                            if (sizeof($tmpOutParams[$cCtr]) > 0) {
                                $tobeExecuted = true;
                            }
                            else {
                                $tobeExecuted = false;
                            }

                            if ($tobeExecuted) {

                                //                            arrprint($tmpOutParams[$cCtr]);

                                $m->pair($no, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $gotParams = $m->exec();

                                //                            cekbiru("gotparams");
                                //                            arrprint($gotParams);

                            }
                            else {
                                cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                            }

                        }
                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
            }
            //rollback postproc, master
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "rollback main post-processor: $comName<br>";
                        if (!in_array($comName, $postDeniedConfigs)) {

                            $dSpec = $gateItems;
                            $tmpOutParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {

                                    $realValue = makeValue($value, $gateItems, $gateItems, 0);
                                    $tmpOutParams['loop'][$key] = $realValue;

                                }
                            }
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $gateItems, $gateItems, 0);
                                    $tmpOutParams['static'][$key] = $realValue;

                                }
                                if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                    $tmpOutParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                    $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                }

                                $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];


                            }
                            if (isset($tComSpec['static2'])) {

                                foreach ($tComSpec['static2'] as $key => $value) {

                                    $realValue = makeValue($value, $gateItems[$cCtr], $gateItems[$cCtr], 0);
                                    $tmpOutParams['static2'][$key] = $realValue;

                                }
                                if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                    $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                    $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                }

                                $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                                $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                                $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                            }

                            if (array_key_exists($oriComName, $postConfigs)) {
                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                    foreach ($postConfigs[$oriComName] as $key) {
                                        $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                        cekbiru("oldVal: $oldVal");
                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                        cekHijau("newVal: $newVal");
                                        $tmpOutParams['static'][$key] = $newVal;
                                    }
                                }
                            }


                            $mdlName = "Com" . ucfirst($comName);
                            $this->load->model("Coms/" . $mdlName);
                            $m = new $mdlName();

                            cekBiru("kiriman rollback main-postproc $comName");

                            $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);

                        }
                        else {
                            cekHitam("$comName denied");
                        }

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
            }

            $whitelist = array(
//                "ProdukProjectUpdate",
//                "ProdukProjectUpdate",
                "TransaksiProduk",
                "ProdukProjectItems3",
                "ProdukProjectItems4",
                "ProdukProjectItems5",
                "ProdukProjectItems7",
            );

            //rollback postproc, detail
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                if (sizeof($iterator) > 0) {
                    cekHitam("cetak iterator :: $jenisTr :: $stepNumCurrent || LINE: " . __LINE__);
                    arrPrintWebs($iterator);
                    $iteratorAdd = array();
                    foreach ($iterator as $cCtr => $tComSpec) {
                        if (isset($tComSpec['static']['state']) && ($tComSpec['static']['state'] == '.hold')) {
                            if (isset($tComSpec['static']['oleh_id']) && ($tComSpec['static']['oleh_id'] != '.0')) {
                                // bila state == .hold dan oleh_id != .0, maka dibuatkan ::
                                // HOLD, +QTY, oleh_id dan ACTIVE, -QTY
                                $tComSpecAddHold = $tComSpec;
                                $tComSpecAddActive = $tComSpec;
                                $staticReplaceHold = array(
                                    "jumlah" => "qty",
                                    "transaksi_no" => ".0",
                                );
                                $staticReplaceActive = array(
                                    "jumlah" => "-qty",
                                    "transaksi_id" => ".0",
                                    "nomer" => ".0",
                                    "state" => ".active",
                                    "oleh_id" => ".0",
                                    "oleh_nama" => "",
                                    "transaksi_no" => ".0",
                                );
                                foreach ($staticReplaceHold as $k_rpc => $v_rpc) {
                                    $tComSpecAddHold['static'][$k_rpc] = $v_rpc;
                                }
                                foreach ($staticReplaceActive as $k_rpc => $v_rpc) {
                                    $tComSpecAddActive['static'][$k_rpc] = $v_rpc;
                                }

                                $iteratorAdd[101] = $tComSpecAddHold; // postprocc hold by orang
                                $iteratorAdd[102] = $tComSpecAddActive; // postprocc active
                            }
                        }
                    }

                    if (sizeof($iteratorAdd) > 0) {
                        foreach ($iteratorAdd as $ii => $spec) {
                            $iterator[$ii] = $spec;
                        }
                    }
                    //                    arrPrintWebs($iterator);
                    //
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "rollback sub-postProcessor: $comName, initializing values <br>";

                        if (in_array($comName, $whitelist)) {

                        }
                        else {
                            if (!in_array($comName, $postDeniedConfigs)) {

                                $tmpOutParams[$cCtr] = array();
                                foreach ($gateItems as $cnt => $dSpec) {

                                    $subParams = array();
                                    if (isset($tComSpec['loop'])) {
                                        foreach ($tComSpec['loop'] as $key => $value) {

                                            $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                            $subParams['loop'][$key] = $realValue;

                                        }
                                    }
                                    if (isset($tComSpec['static'])) {
                                        foreach ($tComSpec['static'] as $key => $value) {

                                            $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                            $subParams['static'][$key] = $realValue;

                                        }
//cekHere("oriComName");
//cekHere($oriComName);
//cekHere($postConfigs);
                                        if (array_key_exists($oriComName, $postConfigs)) {

                                            if (sizeof($postConfigs[$oriComName]) > 0) {
                                                foreach ($postConfigs[$oriComName] as $key) {

                                                    $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                    $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                    $subParams['static'][$key] = $newVal;

                                                }
                                            }
                                        }
                                        else {
                                            //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                        }


                                        if (!isset($subParams['static']["transaksi_id"])) {
                                            $subParams['static']["transaksi_id"] = $no;
                                        }
                                        if (!isset($subParams['static']["transaksi_no"])) {
                                            $subParams['static']["transaksi_no"] = $no;
                                        }
                                        $subParams['static']["fulldate"] = date("Y-m-d");
                                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $subParams['static']["keterangan"] = "rollback of $no";
                                        $subParams['static']["rejection"] = true;
                                    }


                                    if (sizeof($subParams) > 0) {
                                        $tmpOutParams[$cCtr][] = $subParams;
                                    }
                                }
                            }
                            else {
                                cekHitam("$comName denied");
                            }
                        }


                    }


                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        echo "sub-postProcessor: $comName, sending values <br>";
                        if (in_array($comName, $whitelist)) {

                        }
                        else {

                            if (!in_array($comName, $postDeniedConfigs)) {

                                $mdlName = "Com" . ucfirst($comName);
                                $this->load->model("Coms/" . $mdlName);
                                $m = new $mdlName();


                                cekBiru("kiriman rollback detail-postproc $comName");
                                arrPrint($tmpOutParams[$cCtr]);
                                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            }
                            else {
                                cekHitam("$comName denied");
                            }
                        }

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
            }

            //            mati_disini();
            //==================================================================================================
            $this->load->model("Mdls/MdlTransaksiLaporan");
            $lt = New MdlTransaksiLaporan();
            $dataTransaksiLaporan = array(
                "transaksi_id" => $no,
                "master_id" => $masterID,
                "nomer" => $arrMainDataTransIDSpec['nomer'],
                "metode" => "reject",
            );
            $lt->addData($dataTransaksiLaporan) or matiHere("gagal menambahkan data*" . " | " . $this->db->last_query());
            showLast_query("ungu");
        }


        //==================================================================================================
        //==MENGUPDATE LOCKER TRANSAKSI ====================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, NULL);
        //==================================================================================================

//arrPrint($resultRejectID);
//arrPrint($masterTargetStepNum);
////
//matiHere();

        //region update db project
//        switch ($masterTargetStepNum) {
//            case "3":
                $currentProjectID = 0;
                //region update db project
                $this->load->model("Mdls/" . "MdlProdukProject");
                $o = new MdlProdukProject();
                $o->addFilter("transaksi_id='$masterID'");
//                $o->addFilter("id='$currentProjectID'");
                $o->addFilter("status='1'");
                $tempProdukMaster = $o->lookUpAll()->result();
                if (count($tempProdukMaster) == 1) {
                    $currentProjectID = $tempProdukMaster[0]->id;
                    $arrUpdate = array(
                        "status" => 0,
                        "trash" => 1,
                        "closing_status" => 99, //99 = TRANSAKSI DIBATALKAN 1 = TRANSAKSI LENGKAP
                        "closing_oleh_id" => $this->session->login['id'],
                        "closing_oleh_nama" => $this->session->login['nama'],
                        "closing_dtime" => date("Y-m-d H:i:s"),
                        "closing_transaksi_nomer" => "TRANSAKSI DIBATALKAN (" . $arrMainDataTransIDSpec['nomer'] . ")",
                    );
                    $where = array(
                        "id" => $tempProdukMaster[0]->id
                    );
                    $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
                }
                else {
                    matiHere("tidak ditemukan currentProjectID::$currentProjectID || transaksiID_reference::$masterID pada transaksi_id (".$o->getTableName().")");
                }

                $rejected_id = $resultRejectID[$masterID]['insertID'];
                $rejected_no = $resultRejectID[$masterID]['insertNum'];

                //region update db project
                $this->load->model("Mdls/" . "MdlProjectKomposisiWorkorderSub");
                $os = new MdlProjectKomposisiWorkorderSub();
                $os->setFilters(array());
                $os->addFilter("produk_id='$currentProjectID'");
                $os->addFilter("status='1'");
                $os->addFilter("trash='0'");
                $tempProdukMaster = $os->lookUpAll()->result();
//                showlast_query("hitam");
                if (!empty($tempProdukMaster)) {
                    $arrUpdate = array(
                        "status" => 0,
                        "trash" => 1,
                        "rejected" => 11, //99 = TRANSAKSI DIBATALKAN 1 = TRANSAKSI LENGKAP
                        "rejected_id" => $rejected_id,
                        "rejected_no" => $rejected_no,
                        "rejected_dtime" => date("Y-m-d H:i:s"),
                        "rejected_by_id" => $this->session->login['id'],
                        "rejected_by_nama" => $this->session->login['nama'],
                    );
                    foreach ($tempProdukMaster as $row) {
                        $where = array(
                            "id" => $row->id
                        );
                        $os->setFilters(array());
                        $updProject = $os->updateData($where, $arrUpdate, $os->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
//                        showlast_query("hitam");
                    }
                }
                else {
//                    matiHere("tidak ditemukan $transaksiID_reference $currentProjectID pada transaksi_id (".$os->getTableName().")");
                }

//                break;
//            default:
//                //region update db project
//
//
//                $this->load->model("Mdls/" . "MdlProdukProject");
//                $o = new MdlProdukProject();
//                $o->addFilter("transaksi_id='$transaksiID_reference'");
//                $o->addFilter("status='1'");
//                $tempProdukMaster = $o->lookUpAll()->result();
//                showLast_query("biru");
//
//                if (count($tempProdukMaster) == 1) {
//                    $arrUpdate = array(
//                        "status" => 0,
//                        "trash" => 1,
//                        "closing_status" => 99, //99 = TRANSAKSI DIBATALKAN 1 = TRANSAKSI LENGKAP
//                        "closing_oleh_id" => $this->session->login['id'],
//                        "closing_oleh_nama" => $this->session->login['nama'],
//                        "closing_dtime" => date("Y-m-d H:i:s"),
//                        "closing_transaksi_nomer" => "TRANSAKSI DIBATALKAN",
//                    );
//                    $where = array(
//                        "id" => $tempProdukMaster[0]->id
//                    );
//                    $updProject = $o->updateData($where, $arrUpdate, $o->getTableName()) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha menulis ke Produk Project"));
//                    showLast_query("orange");
//                }
//                else {
//
//                    matiHere("tidak ditemukan $transaksiID_reference pada transaksi_id project");
////            die(lgShowError("Ada kesalahan", "tidak ditemukan $transaksiID_reference pada transaksi_id project"));
//                }
//
//                break;
//        }


        //endregion update db project

//        mati_disini("REJECT BERHASIL, saat ini sedang maintenance...");
        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }
        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }
        $arrAlert = array(
            "type" => "success",
            "title" => "Transaction updated",
            //                        "html" => "your order has been saved and ready to process",
            "html" => $this->session->errMsg,
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );

        echo swalAlert($arrAlert);
        echo topReload();
        unset($this->session->errMsg);

    }

    public function viewIncompleteStepAntarCabang()
    {

        $this->jenisTr = $this->uri->segment(4);
        $configUi = $this->config->item("coTransaksiUi");
        $cCode = "_TR_" . $this->jenisTr;
        $historyFields = isset($configUi[$this->jenisTr]['shortHistoryFields']) ? $configUi[$this->jenisTr]['shortHistoryFields'] : array();
        $pairRegistries = isset($configUi[$this->jenisTr]['pairRegistries']) ? $configUi[$this->jenisTr]['pairRegistries'] : array();
        $connectTo = isset($configUi[$this->jenisTr]['connectTo']) ? $configUi[$this->jenisTr]['connectTo'] : "";
        $stepHistoryFields = isset($configUi[$this->jenisTr]['shortStepHistoryFields']) ? $configUi[$this->jenisTr]['shortStepHistoryFields'] : array();


        $arrayOnProgressView = array();
        if (sizeof($stepHistoryFields) > 0) {
            if (strlen($connectTo) > 0) {
                $pairRegistries = isset($configUi[$this->jenisTr]['pairRegistries']) ? $configUi[$this->jenisTr]['pairRegistries'] : array();
                $transaksiConfig = isset($configUi[$this->jenisTr]['steps']) ? $configUi[$this->jenisTr]['steps'] : array();
                $transaksiConnectConfig = isset($configUi[$connectTo]['steps']) ? $configUi[$connectTo]['steps'] : array();
                $transaksiStepConfig = isset($configUi[$this->jenisTr]['steps'][1]) ? $configUi[$this->jenisTr]['steps'][1] : array();
                $this->jenisTrTop = isset($transaksiStepConfig['target']) ? $transaksiStepConfig['target'] : "";


                $tr2 = new MdlTransaksi();
                $registryFields = $tr->getRegistryFields();
                $tr2->setFilters(array());

                if (isset($connectTo)) {
                    $tr2->addFilter("jenis_master='$connectTo'");
                    $tr2->addFilter("link_id='0'");
                    $tr2->addFilter("next_step_code>'0'");
                    $tr2->addFilterJoin("sub_step_number>'0'");
                    //                    $tr2->addFilter("gudang_id<>'0'");
                    //                    if ($this->session->login['cabang_id'] == CB_ID_PUSAT) {
                    //                    }
                    //                    else {
                    $tr2->addFilter("transaksi.toko_id='" . $this->session->login['toko_id'] . "'");
                    //                    }
                    $tmpSrc2 = $tr2->lookupJoined()->result();
                    //                    cekHere($this->db->last_query() . " --- " . count($tmpSrc2));

                    $tmp2 = array();
                    $tmpMasterIDResult = array();
                    $tmpMasterID = array();
                    $tmpResult = array();
                    $arrNextAction = array();
                    $tmpReg_result = array();
                    if (sizeof($tmpSrc2) > 0) {

                        foreach ($tmpSrc2 as $src2sSpec) {
                            $tmpMasterID[$src2sSpec->id_master] = $src2sSpec->id_master;
                            $arrNextAction[$src2sSpec->transaksi_id] = array(
                                "next_step_num" => $src2sSpec->next_substep_num,
                                "next_step_code" => $src2sSpec->next_substep_code,
                            );

                            $arrTransID[] = $src2sSpec->transaksi_id;
                            if (sizeof($pairRegistries) > 0) {

                                $filterField = array("main");
                                if (sizeof($registryFields) > 0) {
                                    foreach ($registryFields as $param) {
                                        if (in_array($param, $filterField)) {
                                            $tmpReg_result[$src2sSpec->transaksi_id][$param] = blobDecode($src2sSpec->$param);
                                        }
                                    }
                                }
                            }
                        }

                        $tr3 = new MdlTransaksi();
                        $tr3->setFilters(array());
                        $tr3->addFilter("link_id='0'");
                        $tr3->addFilter("id_master in ('" . implode("','", $tmpMasterID) . "')");
                        $tmpSrc3 = $tr3->lookupAll()->result();

                        //region membaca pairingan registries MAIN
                        //                        $tmpReg_result = array();
                        //                        if (sizeof($pairRegistries) > 0) {
                        //
                        //                            $trReg = new MdlTransaksi();
                        //                            $trReg->setFilters(array());
                        //                            $trReg->addFilter("param='main'");
                        //                            $trReg->addFilter("transaksi_id in ('" . implode("','", $arrTransID) . "')");
                        //                            $tmpReg = $trReg->lookupRegistries()->result();
                        //                            if (sizeof($tmpReg) > 0) {
                        //                                foreach ($tmpReg as $regRow) {
                        //                                    $param = $regRow->param;
                        //                                    $tmpReg_result[$regRow->transaksi_id][$param] = blobDecode($regRow->values);
                        //                                }
                        //                            }
                        //                        }
                        //endregion

                        foreach ($tmpSrc3 as $tmpSrc3Spec) {
                            $tmpMasterIDResult[$tmpSrc3Spec->id_master][$tmpSrc3Spec->jenis] = $tmpSrc3Spec->nomer;
                        }

                        foreach ($tmpSrc2 as $src2s) {
                            if (sizeof($tmpMasterIDResult[$src2s->id_master]) > 0) {
                                foreach ($tmpMasterIDResult[$src2s->id_master] as $key => $val) {

                                    $src2s->$key = $val;
                                }
                            }
                            $tmpResult[$src2s->id_master] = $src2s;
                        }

                        $arrNextPIC = callNextPIC($arrNextAction);


                        foreach ($tmpResult as $tmpSpec) {
                            if (sizeof($pairRegistries) > 0) {
                                if ((sizeof($tmpReg_result) > 0) && (isset($tmpReg_result[$tmpSpec->transaksi_id]))) {
                                    foreach ($tmpReg_result[$tmpSpec->transaksi_id] as $param => $eReg) {
                                        foreach ($eReg as $k => $v) {
                                            if (!isset($tmpSpec->$k)) {
                                                $tmpSpec->$k = $v;
                                            }
                                        }
                                    }
                                }
                            }


                            foreach ($stepHistoryFields as $fName => $fLabel) {

                                $keyFormat = array_key_exists($fName, getTransaksiJenis()) ? "nomer" : $fName;
                                $tmp2Datas[$fName] = isset($tmpSpec->$fName) ? formatField($keyFormat, $tmpSpec->$fName) : "-";
                            }

                            if ($tmpSpec->sub_step_number > 0) {
                                $tmp2Datas['state'] = "<span style='color:" . $configUi[$this->jenisTr]['steps'][$tmpSpec->sub_step_number]['stateColor'] . "'>" . $configUi[$this->jenisTr]['steps'][$tmpSpec->sub_step_number]['stateLabel'] . "</span>";
                                $tmp2Datas['state'] .= "<br>" . createStateSign($tmpSpec->sub_step_number, $tmpSpec->step_avail, $connectTo);
                            }
                            else {
                                $tmp2Datas['state'] = "<span style='color:#777777'>canceled</span>";
                            }


                            $tmp2Datas['next_pic'] = "-";
                            if (sizeof($arrNextPIC) > 0) {
                                if (isset($arrNextPIC[$tmpSpec->next_substep_code][$tmpSpec->next_substep_num])) {
                                    $next_pic = "";
                                    $nob = 1;
                                    foreach ($arrNextPIC[$tmpSpec->next_substep_code][$tmpSpec->next_substep_num] as $spec) {
                                        if ($tmpSpec->cabang_id == $spec['cabang_id']) {

                                            if ($next_pic == "") {
                                                $next_pic = "$nob. " . $spec['nama'];
                                            }
                                            else {
                                                $nob++;
                                                $next_pic = $next_pic . "<br>" . "$nob. " . $spec['nama'];
                                            }

                                        }
                                    }
                                    $tmp2Datas['next_pic'] = $next_pic;

                                }
                            }


                            $tmp2[] = $tmp2Datas;
                        }
                    }
                }


                $arrayOnProgressView = $tmp2; // $tmp2
            }
        }

        return $arrayOnProgressView;
    }

    public function clearContent()
    {
        // $this->jenisTr = $this->uri->segment(3);
        $cCode = $this->cCode;
        $_SESSION[$cCode] = null;
        unset($_SESSION[$cCode]);
        echo "<script>";
        echo "if(top.document.getElementById('shopping_cart')){";
        // echo "top.getData('" . base_url() . $this->modul."/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=0','shopping_cart');";
        echo "$('#shopping_cart').load('" . base_url() . $this->modul . "/_shoppingCart/viewCart/" . $this->jenisTr . "?selID=0')";
        echo "}";
        echo "</script>";
    }

    public function viewIncomplete()
    {

    }

    //---------------------------
    public function doPreEdit()
    {
        $no = rtrim($this->uri->segment(5), "-");

        //$targetStepNum = $this->uri->segment(4);
        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);

        $rawBuilderURL = blobEncode(current_url());
        $editMode = array(
            "edit" => "$no",
            "stepNum" => $stepNumber,
        );


        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tmpTr = $tr->lookupJoined();


        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            $sCtr = 0;
            foreach ($tmpSign as $row) {
                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }

        $rawItems = array();

        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "items2_sum" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            //endregion

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber] : null;
            $measurementDetails = isset($this->configUi[$this->jenisTr]["receiptMesurementRows"]) ? $this->configUi[$this->jenisTr]["receiptMesurementRows"] : array();
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


            //==periksa apakah ada ganjalan
            $trA = new MdlTransaksi();

            $extSteps = $trA->lookupExtSteps($trID);
            if (sizeof($extSteps) > 0) {
                cekmerah("ada ganjalan step sebanyak " . sizeof($extSteps));
            }
            else {
                cekhijau("TAK ada ganjalan step");
            }

            $paySrcs = $trA->lookupPaymentSrcs($trID, $this->jenisTr . "_");
            if (sizeof($paySrcs) > 0) {
                cekmerah("ada ganjalan paymentSrc sebanyak " . sizeof($paySrcs));
            }
            else {
                cekhijau("TAK ada ganjalan paymentSrc");
            }


            $allowEdit = isset($this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit']) ? $this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit'] : false;
            $editableFields = isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber] : array();


            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->setJoinedFilter(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTr = $tr->lookupJoined();

            //region valid subitem
            $tr->setFilters(array());
            $tr->setJoinedFilter(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
//            $tr->addFilterJoin("valid_qty>0");
            $tr->addFilterJoin("trash=0");
            $tmpTrSub = $tr->lookupJoinedSubItems();
            //endregion
            //            cekhitam($this->db->last_query());


            $extractedItems = array();//==untuk urusan update transaksi referer
            $validItems = array();
            $validItemSends = array();
            if (sizeof($tmpTr) > 0) {
                cekmerah("ada yang mau diekstrak");
                foreach ($tmpTr as $row) {
                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    $validItems[$row->produk_id] += $row->valid_qty;
                    $validItemSends[$row->produk_id] += $row->produk_ord_jml - $row->valid_qty;

                    if (!isset($extractedItems[$row->produk_id])) {
                        $extractedItems[$row->produk_id] = array();
                    }
                    $extractedItems[$row->produk_id][$row->id_detail] = array(
                        "id" => $row->id_detail,
                        "produk_id" => $row->produk_id,
                        "qty" => $row->produk_ord_jml,
                        "valid_qty" => $row->valid_qty,
                        "transaksi_id" => $row->transaksi_id,
                        "sent_qty" => $row->produk_ord_jml - $row->valid_qty,
                    );


                }
            }
            else {
                cekmerah("TIDAK ada yang mau diekstrak");
            }
            //            arrprint($validItems);
            //die();
            //            die();
            $extractedSubItems = array();//==untuk urusan update transaksi referer
            $validSubItems = array();
            $validSubItemSends = array();
            $validSubItemReqCancels = array();
            $validSubItemCancels = array();
            $validSunItemPreCancels = array();
            // arrPrint($tmpTrSub);
            if (sizeof($tmpTrSub) > 0) {
                cekmerah("ada yang mau diekstrak");
                foreach ($tmpTrSub as $rows) {
                    if (!isset($validSubItems[$rows->produk_id])) {
                        $validSubItems[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemSends[$rows->produk_id])) {
                        $validSubItemSends[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemCancels[$rows->produk_id])) {
                        $validSubItemCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemReqCancels[$rows->produk_id])) {
                        $validSubItemReqCancels[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPackeds[$rows->produk_id])) {
                        $validSubItemPackeds[$rows->produk_id] = 0;
                    }
                    if (!isset($validSubItemPreCancels[$rows->produk_id])) {
                        $validSubItemPreCancels[$rows->produk_id] = 0;
                    }

                    $validSubItems[$rows->produk_id] += isset($rows->valid_qty) ? $rows->valid_qty : 0;
                    $validSubItemSends[$rows->produk_id] += isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0;
                    $validSubItemCancels[$rows->produk_id] += isset($rows->cancel_qty) ? $rows->cancel_qty : 0;
                    $validSubItemReqCancels[$rows->produk_id] += isset($rows->req_cancel_qty) ? $rows->req_cancel_qty : 0;
                    $validSubItemPreCancels[$rows->produk_id] += isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0;
                    $validSubItemPackeds[$rows->produk_id] += isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0;

                    if (!isset($extractedSubItems[$rows->produk_id])) {
                        $extractedSubItems[$rows->produk_id] = array();
                    }
                    $extractedSubItems[$rows->produk_id][$rows->id_sub_detail] = array(
                        "id" => $rows->id_sub_detail,
                        "produk_id" => $rows->produk_id,
                        "qty" => $rows->produk_ord_jml,
                        "valid_qty" => $rows->valid_qty,
                        "transaksi_id" => $rows->transaksi_id,
                        "packed_qty" => isset($arrTmp__['582pkd'][$rows->produk_id]) ? $arrTmp__['582pkd'][$rows->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__['582spd'][$rows->produk_id]) ? $arrTmp__['582spd'][$rows->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$rows->produk_id]) ? $arrPreTmp__['1982'][$rows->produk_id] : 0,
                        "cancel_qty" => $rows->cancel_qty,
                        "outstanding" => $rows->produk_ord_jml - ($rows->produk_ord_jml - $rows->valid_qty),
                        "dikirim_qty" => $rows->produk_ord_diterima,
                    );
                }
            }
            //endregion


            //
            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            //            //cekMerah($this->db->last_query());
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //            arrPrint($detailValues);
            //endregion


            //region take from registries
            //==ambil value-gate
            $trr = new MdlTransaksi();
            $trr->setFilters(array());
            $trr->addFilter("transaksi_id='$no'");
            $tmpReg = $trr->lookupDataRegistries()->result();

            $mainOriginal = array();
            $itemsOriginal = array();
            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $masterGates = array();
            $childGates = array();
            $childGates2 = array();
            $childGates2_sum = array();
            $childGatesRsltItems = array();
            $childGatesRsltItems2 = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $childTableInParamsRsltItems = array();
            $childTableInParamsRsltItems2 = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $childTableInValueParamsRsltItems = array();
            $childTableInValueParamsRsltItems2 = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $mainInputs = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        if ($key_reg != "transaksi_id") {
                            switch ($key_reg) {
                                case "main"://
                                    $main = $main + unserialize(base64_decode($val_reg));
                                    $mainOriginal = $main;
                                    break;
                                case "items"://
                                    $items = $items + unserialize(base64_decode($val_reg));
                                    $itemsOriginal = $items;
                                    break;
                                case "items2"://
                                    $items2 = $items2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "rsltItems"://
                                    $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "rsltItems2"://
                                    $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "items2_sum"://
                                    $items2_sum = $items2_sum + unserialize(base64_decode($val_reg));
                                    break;

                                case "tableIn_master"://
                                    $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail"://
                                    $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_rsltItems"://
                                    $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_rsltItems2"://
                                    $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_master_values"://
                                    $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values"://
                                    $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values_rsltItems"://
                                    $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values_rsltItems2"://
                                    $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "main_add_values"://
                                    $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                                    break;
                                case "main_add_fields"://
                                    $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                                    break;

                                case "main_elements"://
                                    $mainElements = unserialize(base64_decode($val_reg));
                                    break;
                                case "main_inputs"://
                                    $mainInputs = unserialize(base64_decode($val_reg));
                                    break;
                            }
                        }
                    }

                }

            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion


            $masterReplacers = array(
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $masterTableInParams['jenis_top'],
                "harga" => 0,
                "masterID" => $masterID,
            );
            foreach ($masterReplacers as $key => $src) {
                $main[$key] = $src;
                $mainValues[$key] = $src;
                $masterGates[$key] = $src;
            }


            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();


            if (sizeof($items) > 0) {
                //                $tipeSize =array();
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";

                    if (array_key_exists($id, $validItems)) {
                        $items[$id]['jml'] = $validItems[$id];
                        $items[$id]['max_jml'] = $validItems[$id];
                        $items[$id]['sent_jml'] = $validItemSends[$id];
                        if (sizeof($editableFields) > 0) {
                            foreach ($editableFields as $fName) {
                                $items[$id]["max_$fName"] = isset($iSpec[$fName]) ? $iSpec[$fName] : 0;
                            }
                        }

                        if (sizeof($measurementDetails)) {
                            if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
                                $selectedColl = $measurementDetails[$tipeSize];
                                foreach ($selectedColl as $colSelected => $tempHelper) {
                                    //                                    cekHitam("$heAngka");

                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        cekHitam($newKey);
                                        $items[$id][$newKey] = $heAngka($iSpec[$colSelected]);
                                    }
                                    //
                                }
                            }

                        }
                    }
                    else {
                        unset($items[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);

                    }


                }
            }


            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "rsltItems" => $rsltItems,
                "rsltItems2" => $rsltItems2,
                "extractedItems" => $extractedItems,
                "extractedSubItems" => $extractedSubItems,
                "tableIn_master" => $masterTableInParams,
                "tableIn_detail" => $childTableInParams,
                "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
                "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
                "tableIn_master_values" => $masterTableInValueParams,
                "tableIn_detail_values" => $childTableInValueParams,
                "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
                "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
                "main_add_values" => $masterAddValues,
                //        ""=>$childAddValues ,
                "main_add_fields" => $masterAddFields,
                //                "main_applets"          => $mainApplets,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                //
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "mode" => $editMode,
                "mainOriginal" => $mainOriginal,
                "itemsOriginal" => $itemsOriginal,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;

            }
            //endregion


            //==init replacer
            //==recover nilai HARGA master
            $_SESSION[$cCode]['main']['harga'] = 0;

            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                foreach ($_SESSION[$cCode]['items'] as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                }
            }

//            if(sizeof($extractedSubItems)>0){
//                foreach($extractedSubItems as $pID => $pSpec){
//                    foreach($pSpec as $dID => $ppSpec){
//
//                    }
//                }
//            }
            if (sizeof($_SESSION[$cCode]['items2_sum']) > 0) {
                arrPrintPink($_SESSION[$cCode]['items2_sum']);
                foreach ($_SESSION[$cCode]['items2_sum'] as $pID => $iiSpec) {
                    if (!array_key_exists($pID, $extractedSubItems)) {
                        // valid_qty di $extractedSubItems sudah nol, maka
                        // qty dan jml di items2_sum di-nol-kan
                        $_SESSION[$cCode]['items2_sum'][$pID]['qty'] = 0;
                        $_SESSION[$cCode]['items2_sum'][$pID]['jml'] = 0;
                    }
                    else {
                        foreach ($extractedSubItems[$pID] as $ddID => $ddSpec) {
//                            arrPrint($ddSpec);
                            if ($pID == $ddSpec['produk_id']) {

                                $_SESSION[$cCode]['items2_sum'][$pID]['qty'] = $ddSpec['valid_qty'];
                                $_SESSION[$cCode]['items2_sum'][$pID]['jml'] = $ddSpec['valid_qty'];
                            }
                        }
                    }
                }
            }

        }
        else {
            die(lgShowAlert("No such transaction. You may want to refresh the browser to re-fetch actual content."));
        }

//cekKuning($_SESSION[$cCode]['items2_sum']);
//mati_disini();
        $link = MODUL_PATH . "Create/index/" . $this->jenisTr;

        topRedirect($link);

        die();


    }

    public function editForm()
    {

        if (!isset($this->session->login['id'])) {
            redirect(base_url() . "Login");
        }
        //        arrPrint($this->uri->segment_array());
        //cekHitam("putihhh");
        //===pageView options
        if (!isset($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'])) {
            $viewModeConfig = isset($this->configUi[$this->jenisTr]['defaultViewMode']) ? $this->configUi[$this->jenisTr]['defaultViewMode'] : "list";
            $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] = isset($_GET['viewMode']) ? $_GET['viewMode'] : $viewModeConfig;
        }
        //        die();
        $viewModeSpec = array(
            "icon" => "",
            "url" => "",
        );
        $thisPage = base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3);
        switch ($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode']) {
            case "list":
                $viewModeSpec = array(
                    "icon" => "	glyphicon glyphicon-th-large",
                    "url" => $thisPage . "?viewMode=thumbnail",
                );
                break;
            case "thumbnail":
                $viewModeSpec = array(
                    "icon" => "glyphicon glyphicon-align-justify",
                    "url" => $thisPage . "?viewMode=list",
                );
                break;
        }
        $viewModeSwitch = "<a href='javascript:void(0)' onclick=\"location.href='" . $viewModeSpec['url'] . "';\"><span class='" . $viewModeSpec['icon'] . "'></span></a>";


        if (!isset($this->session->login['id'])) {
            redirect(base_url() . "Login");
        }
        //die();

        $jenisTr = $this->uri->segment(4);
        $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;
        //        arrPrint($_SESSION[$cCode]);
        //        matiHere();
        //        heInitCart($jenisTr);
        //        arrPrint($jenisTr);
        heInitGates($this->jenisTr);

        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        $historyFields = $this->configUi[$jenisTr]['shortHistoryFields'];
        $glanceHistoryFields = isset($this->configUi[$jenisTr]['glanceHistoryFields']) ? $this->configUi[$jenisTr]['glanceHistoryFields'] : array("nomer" => "receipt no");
        $glanceHistoryFields2 = array("nomer" => "receipt no"); //init;
        $selectorProcessor = base_url() . $this->configUi[$jenisTr]['selectorProcessor'] . "/$jenisTr";
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }
        //
        //region lookup on-going transactions

        $arrayOnprogress = array();
        $progressFields = $historyFields;
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";
        $steps = $this->configUi[$jenisTr]['steps'];
        //        if (sizeof($steps) > 1) {
        //            $stepCodes = array();
        //            $jmlStep = count($steps);
        //            foreach ($steps as $stepNumber => $stepSpec) {
        //                if ($stepNumber < $jmlStep) {
        //                    $stepCodes[] = $stepSpec['target'];
        //                }
        //
        //            }
        //
        //
        //            $this->load->model("MdlTransaksi");
        //            $tr = new MdlTransaksi();
        //            $tr->addFilter("jenis_top='" . $steps[1]['target'] . "'");
        //            $tr->addFilter("next_substep_code<>''");
        //            $tmpHist = $tr->lookupRecentUndoneEntries_joined($this->session->login['cabang_id'], $this->session->login['gudang_id'])->result();
        //
        //            $arrayOnprogress = array();
        //            if (sizeof($tmpHist) > 0) {
        //                foreach ($tmpHist as $row) {
        //                    $tmp = array();
        //                    foreach ($historyFields as $fName => $fLabel) {
        //                        //$tmp[$fName] = $row->$fName;
        //                        $tmp[$fName] = formatField($fName, $row->$fName);
        //                    }
        ////                    $tmp['state'] = $this->configUi[$jenisTr]['steps'][$row->step_current]['stateLabel'];
        //                    if ($row->sub_step_number > 0) {
        //                        $tmp['state'] = "<span style='color:" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateColor'] . "'>" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateLabel'] . "</span>";
        //                        $tmp['state'] .= "<br>" . createStateSign($row->sub_step_number, $row->step_avail);
        //                    } else {
        //                        $tmp['state'] = "<span style='color:#777777'>canceled</span>";
        //                    }
        //
        //                    $tmp['action'] = "";
        //                    $nextStepNum = ($row->next_substep_num);
        //                    $currentStepNum = ($row->sub_step_number);
        ////                    echo $currentStepNum." vs ".$nextStepNum."<br>";
        //                    $allowJoin = isset($this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin']) && $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] : false;
        //
        //
        //                    $allowFollowup = false;
        //                    if ($row->sub_step_number > 0) {
        //                        if (in_array($this->configUi[$jenisTr]['steps'][$currentStepNum]['userGroup'], $this->session->login['membership'])) {
        //                            $allowFollowup = true;
        //                            $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
        //                        }
        //                    }
        //
        //                    if (isset($this->configUi[$jenisTr]['steps'][$nextStepNum])) {
        //                        if (in_array($this->configUi[$jenisTr]['steps'][$nextStepNum]['userGroup'], $this->session->login['membership'])) {
        //                            $allowFollowup = true;
        //                            $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];
        //
        //                        }
        //                    }
        //
        //                    if ($allowFollowup) {
        //                        $stepLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['label'];
        //
        //                        $followupLink = "document.getElementById('result').src=('" . base_url() . "Transaksi/followupPrePreview/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
        ////                        $tmp['action'] = "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='javascript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
        //                        $tmp['action'] = "<div class='input-group'>";
        //                        $tmp['action'] .= "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='javascript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
        //                        if ($allowJoin) {
        //                            $tmp['action'] .= "<span class='input-group-addon'>";
        //                            $tmp['action'] .= "<a title='process many items at once' href='" . base_url() . "Transaksi/viewIncomplete/" . $this->jenisTr . "/$currentStepNum'><span class='fa fa-dedent'></span></a>";
        //                            $tmp['action'] .= "</span class='input-group-addon'>";
        //                        }
        //                    }
        //                    $arrayOnprogress[] = $tmp;
        //                }
        //            }
        //        } else {
        //            $arrayOnprogress = array();
        //        }
        //endregion

        //

        //region menambah supplier/customer (kalau berwenang)
        $pihakModel = $this->configUi[$this->jenisTr]['pihakModel'];
        $dataAccess = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel] : array(
            "viewers" => array(),
            "creators" => array(),
            "creatorAdmins" => array(),
            "updaters" => array(),
            "updaterAdmins" => array(),
            "deleters" => array(),
            "deleterAdmins" => array(),
            "historyViewers" => array(),
        );
        $dataLabel = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel]['label'] : $pihakModel;
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $addPihakStr = "";
        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $pihakModel);
        //        arrprint($dataAccess['creators']);
        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $dataLabel . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        }
                                        );";
                $addPihakStr = "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' title='add $dataLabel' data-toggle='tooltip' data-placement='right' class='btn btn-default' onclick=\"$addClick\">
                                            <span class='fa fa-user-plus'>                                            
                                             </span>
                                        </a>
                                </span>";
            }
        }
        //endregion

        //region menambah item/produk (kalau berwenang)
        $pihakModel = $this->configUi[$this->jenisTr]['selectorModel'];
        $dataAccess = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel] : array(
            "viewers" => array(),
            "creators" => array(),
            "creatorAdmins" => array(),
            "updaters" => array(),
            "updaterAdmins" => array(),
            "deleters" => array(),
            "deleterAdmins" => array(),
            "historyViewers" => array(),
        );
        $dataLabel = isset($this->config->item('heDataBehaviour')[$pihakModel]) ? $this->config->item('heDataBehaviour')[$pihakModel]['label'] : $pihakModel;
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $addItemStr = "";
        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $pihakModel);
        //        arrprint($dataAccess['creators']);
        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $dataLabel . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        }
                                        );";
                $addItemStr = "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' title='add $dataLabel' data-toggle='tooltip' data-placement='right' class='btn btn-default' onclick=\"$addClick\">
                                            <span class='fa fa-plus-circle'>                                            
                                             </span>
                                        </a>
                                </span>";
            }
        }
        //endregion


        //
        //region lookup on-going from connected requests
        $progress2Fields = array();
        $arrayOnprogress2 = array();
        $needToClear = false;
        //endregion

        //
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("transaksi.gudang_id='" . $this->session->login['gudang_id'] . "'");
        $tr->addFilter("transaksi.jenis_master='" . $this->jenisTr . "'");

        //        $tr->addFilter("transaksi.next_step_code=''");
        $tmpHist = $tr->lookupRecentHistories()->result();

        // print_r($tmpHist);die();
        $arrayHistory = array();
        if (sizeof($tmpHist) > 0) {
            if (sizeof($pairRegistries) > 0) {
                $arrTransID = array();
                $arrIndexID = array();
                foreach ($tmpHist as $row) {
                    $req_index = isset($row->indexing_registry) ? blobDecode($row->indexing_registry) : array();
                    foreach ($pairRegistries as $reg) {
                        if (isset($req_index[$reg])) {
                            $arrIndexID[] = $req_index[$reg];
                        }
                    }
                    $arrTransID[] = $row->id;
                }
                $tmpReg_result = array();
                if (sizeof($arrIndexID) > 0) {
                    $trReg = new MdlTransaksi();
                    $trReg->setFilters(array());
                    $trReg->addFilter("trash='0'");
                    $trReg->addFilter("id in ('" . implode("','", $arrIndexID) . "')");
                    $tmpReg = $trReg->lookupRegistries()->result();

                    if (sizeof($tmpReg) > 0) {
                        foreach ($tmpReg as $regRow) {
                            $tmpReg_result[$regRow->transaksi_id] = blobDecode($regRow->values);
                        }
                    }
                }
            }
            foreach ($tmpHist as $row) {

                if (isset($tmpReg_result[$row->id]) && sizeof($tmpReg_result[$row->id]) > 0) {
                    foreach ($tmpReg_result[$row->id] as $k => $v) {
                        if (!isset($row->$k)) {
                            $row->$k = $v;
                        }
                    }
                }


                $tmp = array();
                foreach ($historyFields as $fName => $fLabel) {
                    $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : formatField($fName, 0);
                }
                $arrayHistory[] = $tmp;
            }
        }

        //endregion
        //


        $barcodeSettings = isset($this->configUi[$this->jenisTr]['barcodeSettings']) ? $this->configUi[$this->jenisTr]['barcodeSettings'] : array();

        //==mobile scan (if possible)
        $mobScanStr = sizeof($barcodeSettings) ? "<span class='input-group-btn'>
                                        <a href='javascript:void(0)' class='btn btn-default' onclick=\"getScan()\">
                                            <span class='fa fa-qrcode'>
                                             </span>
                                        </a>
                                </span>" : "";


        //
        //region external tool
        if (isset($this->configUi[$jenisTr]['extTool'])) {
            $extToolConfig = $this->configUi[$jenisTr]['extTool'];
            $srcVar = $extToolConfig['sentParam'];
            $srcField = $extToolConfig['sentField'];
            $externSrc = $extToolConfig['externSrc'];
            $rawParam = array();
            $backUrl = base_url() . $extToolConfig['backUrl'];
            if (isset($_SESSION[$cCode][$srcVar]) && sizeof($_SESSION[$cCode][$srcVar]) > 0) {

                foreach ($_SESSION[$cCode][$srcVar] as $id => $rSpec) {
                    if (isset($rSpec[$srcField])) {
                        $rawParam[$id] = $rSpec[$srcField];
                    }
                }
            }
            //            arrPrint($rawParam);die();
            if (sizeof($rawParam) > 0) {
                $param = base64_encode(serialize($rawParam));
                $backUrl = base64_encode(serialize($backUrl));
                $extTool = "<a class='btn btn-default' href='javascript:void(0)' onclick=\"window.open('" . $extToolConfig['url'] . "?param=$param&extern=" . $_SESSION[$cCode]['main'][$externSrc] . "&back=$backUrl','wTool');\" >" . $extToolConfig['label'] . "</a>";
            }
            else {
                $extTool = "<a class='btn btn-default' disabled>" . $extToolConfig['label'] . "</a>";
            }

        }
        else {
            //            //cekMerah("extTool doesnt exist");
            $extTool = "";
        }
        //endregion

        $allowTmpSave = isset($this->configUi[$jenisTr]['allowTmpSave']) ? $this->configUi[$jenisTr]['allowTmpSave'] : false;
        //region prepare params to viewer

        $data = array(
            "mode" => $this->uri->segment(2),
            "isMobile" => $isMob,
            "errMsg" => $this->session->errMsg,
            //            "template" => $this->configUi[$jenisTr]["template"],
            "template" => "application/template/transaksi_edit.html",
            "title" => " ",
            "subTitle" => "Edit " . $this->configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "jenisTransaksi" => $jenisTr,
            "selectedID" => $this->uri->segment(3),
            "trName" => $this->configUi[$jenisTr]["label"],
            //            "selectorCaller" => base_url() . "_selectorItem/" . $this->configUi[$jenisTr]["selectorCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel"],
            "selectorCaller" => base_url() . $this->configUi[$jenisTr]["selectorCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel"],

            "selectorLabel" => $this->configUi[$jenisTr]["selectorLabel"],
            "selectorCaller2" => isset($this->configUi[$jenisTr]["selectorCaller2"]) ? base_url() . $this->configUi[$jenisTr]["selectorCaller2"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel2"] : "",
            //            "pihakCaller" => base_url() . "_selectorPihak/" . $this->configUi[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["pihakModel"],
            "selectorLabel2" => isset($this->configUi[$jenisTr]["selectorLabel2"]) ? $this->configUi[$jenisTr]["selectorLabel2"] : "",
            "pihakCaller" => base_url() . $this->configUi[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["pihakModel"],
            "pihakCallerDelete" => base_url() . "Selectors/_processPihak/remove/$jenisTr",
            // "pihakLabel"=>$this->configUi[$jenisTr]["pihakLabel"],
            "pihakLabel" => isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] . "(" . $this->configUi[$jenisTr]["pihakLabel"] . ")" : $this->configUi[$jenisTr]["pihakLabel"],
            "arrayHistoryLabels" => $historyFields,
            "arrayHistory" => $arrayHistory,
            "arrayProgressLabels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progressFields : $glanceHistoryFields,
            "arrayProgress2Labels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progress2Fields : $glanceHistoryFields2,
            "arrayOnProgress" => $arrayOnprogress,
            "arrayOnProgress2" => $arrayOnprogress2,
            "reqFormTarget" => isset($reqFormTarget) ? $reqFormTarget : "",

            //            "strPaymentMethod" => $strPaymentMethod,
            "extTool" => $extTool,
            "columnRecorderTarget" => base_url() . "ValueGate/recordColumn/" . $this->jenisTr . "/",
            "defaultDescription" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "allowJoin" => isset($this->configUi[$jenisTr]["steps"][1]['allowJoin']) && $this->configUi[$jenisTr]["steps"][1]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][1]['allowJoin'] : false,
            "allowTmpSave" => $allowTmpSave,
            "needToClear" => $needToClear,
            "addPihakStr" => $addPihakStr,
            "addItemStr" => $addItemStr,
            "mobScanStr" => $mobScanStr,
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3),
            "viewMode" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'],
            "viewModeSwitch" => $viewModeSwitch,
            "barcodeSettings" => $barcodeSettings,
            "selectorProcessor" => $selectorProcessor,

        );
        //endregion
        //        arrPrint($data);
        $this->load->view("transaksi", $data);
        //        $this->session->errMsg = "";
    }

    //---------------------------
    //extract data to shoppingcart
    public function preCancelPacking()
    {
        $no = rtrim($this->uri->segment(5), "-");
        $stepNumber = $this->uri->segment(7);
        $targetJenisTr = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = blobEncode(current_url());

        $this->jenisTr = $targetJenisTr;
        $cCode = "_TR_" . $this->jenisTr;

        $cancelMode = array(
            "cancel" => "$no",
        );

        $editMode = array();

        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tmpTr = $tr->lookupJoined();


        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            $sCtr = 0;
            foreach ($tmpSign as $row) {
                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }

        $rawItems = array();

        cekHere("no: $no ::: $targetJenisTr");
        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {

            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }
            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            //endregion

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$targetJenisTr]['receiptDetailFields'][$stepNumber]) ? $this->configLayout[$targetJenisTr]['receiptDetailFields'][$stepNumber] : array();
            $itemNumLabels = isset($this->configUi[$targetJenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$targetJenisTr]['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($this->configUi[$targetJenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$targetJenisTr]['shoppingCartAmountValue'][$stepNumber] : null;
            $measurementDetails = isset($this->configUi[$targetJenisTr]["receiptMesurementRows"]) ? $this->configUi[$targetJenisTr]["receiptMesurementRows"] : array();
            $xCancelConfig = isset($this->configUi[$targetJenisTr]["xShipmentConfig"][$currentStepNum]) ? $this->configUi[$targetJenisTr]["xShipmentConfig"][$currentStepNum] : array();


            $currentID = $tmpTr[0]->transaksi_id;
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $cCodeOrig = "_TR_" . $origJenis;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = (1);


            if (isset($_SESSION[$cCodeOrig])) {
                $_SESSION[$cCodeOrig] = null;
                unset($_SESSION[$cCodeOrig]);
            }

            //==periksa apakah ada ganjalan
            $trA = new MdlTransaksi();
            $extSteps = $trA->lookupExtSteps($trID);
            if (sizeof($extSteps) > 0) {
                cekmerah("ada ganjalan step sebanyak " . sizeof($extSteps));
            }
            else {
                cekhijau("TAK ada ganjalan step");
            }

            $paySrcs = $trA->lookupPaymentSrcs($trID, $this->jenisTr . "_");
            if (sizeof($paySrcs) > 0) {
                cekmerah("ada ganjalan paymentSrc sebanyak " . sizeof($paySrcs));
            }
            else {
                cekhijau("TAK ada ganjalan paymentSrc");
            }

            $allowEdit = isset($this->configUi[$targetJenisTr]['steps'][$stepNumber]['allowEdit']) ? $this->configUi[$targetJenisTr]['steps'][$stepNumber]['allowEdit'] : false;
            $editableFields = isset($this->configUi[$targetJenisTr]['shoppingCartEditableFields'][$stepNumber]) ? $this->configUi[$targetJenisTr]['shoppingCartEditableFields'][$stepNumber] : array();

            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTr = $tr->lookupJoined();
            showLast_query("biru");
            $id_top = isset($tmpTr[0]->id_top) ? $tmpTr[0]->id_top : "";

            //region prepacked
            $tmpTrPrePacked = array();
            $trPrePack = new MdlTransaksi();
            $trPrePack->setFilters(array());
            $trPrePack->addFilter("cancel_packing_source_id in (" . implode(",", explode("-", $no)) . ")");
            $trPrePack->addFilterJoin("valid_qty>0");
            $trPrePack->addFilter("trash_4<1");
            $tmpTrPrePacked = $trPrePack->lookupJoined();
            //            showLast_query("merah");
            //            cekMerah("ada " . sizeof($tmpTrPrePacked));

            $arrPreTmp__ = array();
            if (sizeof($tmpTrPrePacked) > 0) {
                foreach ($tmpTrPrePacked as $y => $dd) {
                    if (!isset($arrPreTmp__[$dd->jenis][$dd->produk_id])) {
                        $arrPreTmp__[$dd->jenis][$dd->produk_id] = 0;
                    }
                    $arrPreTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
                }
            }
            //endregion prepacked

            //region packed
            $tmpTrPacked = array();
            $trPack = new MdlTransaksi();
            $trPack->setFilters(array());
            $trPack->addFilter("id_top in (" . implode(",", explode("-", $id_top)) . ")");
            $trPack->addFilterJoin("valid_qty>0");
            $tmpTrPacked = $trPack->lookupJoined();
            //            showLast_query("kuning");
            //            cekKuning("ada " . sizeof($tmpTrPacked));

            $arrTmp__ = array();
            if (sizeof($tmpTrPacked) > 0) {

                foreach ($tmpTrPacked as $y => $dd) {
                    if (!isset($arrTmp__[$dd->jenis][$dd->produk_id])) {
                        $arrTmp__[$dd->jenis][$dd->produk_id] = 0;
                    }
                    $arrTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
                }
            }
            //endregion packed

            //            arrPrint($arrTmp__);

            $extractedItems = array();//==untuk urusan update transaksi referer
            $validItems = array();
            $validItemSends = array();
            $validItemReqCancels = array();
            $validItemCancels = array();
            $validItemPreCancels = array();
            $validItemPackeds = array();

            if (sizeof($tmpTr) > 0) {
                //                cekmerah("ada yang mau diekstrak");
                //                arrPrint($tmpTr);
                $shipment = isset($xCancelConfig['shipment']) ? $xCancelConfig['shipment'] : "";
                $packing = isset($xCancelConfig['packing']) ? $xCancelConfig['packing'] : "";
                $cancel = isset($xCancelConfig['cancel']) ? $xCancelConfig['cancel'] : "";

                foreach ($tmpTr as $row) {
                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    if (!isset($validItemCancels[$row->produk_id])) {
                        $validItemCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemReqCancels[$row->produk_id])) {
                        $validItemReqCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPackeds[$row->produk_id])) {
                        $validItemPackeds[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPreCancels[$row->produk_id])) {
                        $validItemPreCancels[$row->produk_id] = 0;
                    }

                    $validItems[$row->produk_id] += $row->valid_qty;
                    //                    $validItemSends[$row->produk_id] += $row->produk_ord_jml - $row->cancel_qty - $row->valid_qty;
                    //                    $validItemSends[$row->produk_id] += isset($arrTmp__['582spd'][$row->produk_id]) ? $arrTmp__['582spd'][$row->produk_id] : 0; // ini jumlah yang sudah dikirim atau GRN
                    $validItemSends[$row->produk_id] += isset($arrTmp__[$shipment][$row->produk_id]) ? $arrTmp__[$shipment][$row->produk_id] : 0; // ini jumlah yang sudah dikirim atau GRN
                    $validItemReqCancels[$row->produk_id] += isset($row->req_cancel_qty) ? $row->req_cancel_qty : 0;
                    $validItemCancels[$row->produk_id] += isset($row->cancel_qty) ? $row->cancel_qty : 0;
                    //                    $validItemPreCancels[$row->produk_id] += isset($arrPreTmp__['1982'][$row->produk_id]) ? $arrPreTmp__['1982'][$row->produk_id] : 0; // ini jumlah yang sudah direquest cancel item
                    $validItemPreCancels[$row->produk_id] += isset($arrPreTmp__[$cancel][$row->produk_id]) ? $arrPreTmp__[$cancel][$row->produk_id] : 0; // ini jumlah yang sudah direquest cancel item
                    //                    $validItemPackeds[$row->produk_id] += isset($arrTmp__['582pkd'][$row->produk_id]) ? $arrTmp__['582pkd'][$row->produk_id] : 0; // ini jumlah prepacking
                    $validItemPackeds[$row->produk_id] += isset($arrTmp__[$packing][$row->produk_id]) ? $arrTmp__[$packing][$row->produk_id] : 0; // ini jumlah prepacking

                    if (!isset($extractedItems[$row->produk_id])) {
                        $extractedItems[$row->produk_id] = array();
                    }

                    $extractedItems[$row->produk_id][$row->id_detail] = array(
                        "id" => $row->id_detail,
                        "produk_id" => $row->produk_id,
                        "qty" => $row->produk_ord_jml,
                        "valid_qty" => $row->valid_qty,
                        "transaksi_id" => $row->transaksi_id,
                        //                        "packed_qty" => isset($arrTmp__['582pkd'][$row->produk_id]) ? $arrTmp__['582pkd'][$row->produk_id] : 0, // ini jumlah prepacking
                        "packed_qty" => isset($arrTmp__[$packing][$row->produk_id]) ? $arrTmp__[$packing][$row->produk_id] : 0, // ini jumlah prepacking
                        "cancel_qty" => $row->cancel_qty,
                        "req_cancel_qty" => $row->req_cancel_qty,
                        "sent_qty" => $row->produk_ord_jml - $row->cancel_qty - $row->valid_qty,
                        "outstanding" => $row->produk_ord_jml - ($row->produk_ord_jml - $row->valid_qty),
                    );
                }
                //                arrPrintWebs($extractedItems);
            }
            else {
                cekmerah("TIDAK ada yang mau diekstrak");
            }
            //endregion

            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //endregion

            //region take from registries
            //==ambil value-gate
            $trr = new MdlTransaksi();
            $trr->setFilters(array());
            $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
            $tmpReg = $trr->lookupDataRegistries()->result();
            //            cekKuning(__LINE__ . " " . $this->db->last_query());

            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $masterGates = array();
            $childGates = array();
            $childGates2 = array();
            $childGates2_sum = array();
            $childGatesRsltItems = array();
            $childGatesRsltItems2 = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $childTableInParamsRsltItems = array();
            $childTableInParamsRsltItems2 = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $childTableInValueParamsRsltItems = array();
            $childTableInValueParamsRsltItems2 = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $mainInputs = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        switch ($key_reg) {
                            case "main"://
                                $main = $main + unserialize(base64_decode($val_reg));
                                break;
                            case "items"://
                                $items = $items + unserialize(base64_decode($val_reg));
                                break;
                            case "items2"://
                                $items2 = $items2 + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems"://
                                $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems2"://
                                $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "items2_sum"://
                                $items2_sum = $items2_sum + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master"://
                                $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail"://
                                $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems"://
                                $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems2"://
                                $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master_values"://
                                $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values"://
                                $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems"://
                                $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems2"://
                                $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_values"://
                                $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_fields"://
                                $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                                break;
                            case "main_elements"://
                                $mainElements = unserialize(base64_decode($val_reg));
                                break;
                            case "main_inputs"://
                                $mainInputs = unserialize(base64_decode($val_reg));
                                break;
                        }
                    }
                }
            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion

            $masterReplacers = array(
                "jenisTrMaster" => $targetJenisTr,
                "jenisTrTop" => $targetJenisTr,
                "harga" => 0,
                "masterID" => $masterID,
                "currentID" => $currentID,
            );
            foreach ($masterReplacers as $key => $src) {
                $main[$key] = $src;
                $mainValues[$key] = $src;
                $masterGates[$key] = $src;
            }

            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();

            if (sizeof($items) > 0) {
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $items[$id]['handler'] = $this->modul . "/" . "_processSelectNotaItem";
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";
                    if (array_key_exists($id, $validItems)) {
                        //                        $items[$id]['jml'] = $validItems[$id]-(int)$validItemPreCancels[$id];//orig
                        $items[$id]['jml'] = $validItems[$id];
                        $items[$id]['max_jml'] = (int)$validItems[$id] + (int)$validItemSends[$id] + (int)$validItemPackeds[$id] + (int)$validItemCancels[$id] + (int)$validItemReqCancels[$id];
                        $items[$id]['sent_jml'] = $validItemSends[$id];
                        $items[$id]['packed_jml'] = $validItemPackeds[$id];
                        $items[$id]['cancel_jml'] = $validItemCancels[$id];
                        $items[$id]['req_cancel_jml'] = $validItemPreCancels[$id];

                        if (sizeof($editableFields) > 0) {
                            foreach ($editableFields as $fName) {
                                $items[$id]["max_$fName"] = isset($iSpec[$fName]) ? $iSpec[$fName] : 0;
                            }
                        }
                        if (sizeof($measurementDetails)) {
                            if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
                                $selectedColl = $measurementDetails[$tipeSize];
                                foreach ($selectedColl as $colSelected => $tempHelper) {
                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        cekHitam($newKey);
                                        $items[$id][$newKey] = $heAngka($iSpec[$colSelected]);
                                    }
                                }
                            }
                        }
                    }
                    else {
                        unset($items[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);
                    }
                }
            }

            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "rsltItems" => $rsltItems,
                "rsltItems2" => $rsltItems2,
                "extractedItems" => $extractedItems,
                "tableIn_master" => $masterTableInParams,
                "tableIn_detail" => $childTableInParams,
                "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
                "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
                "tableIn_master_values" => $masterTableInValueParams,
                "tableIn_detail_values" => $childTableInValueParams,
                "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
                "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
                "main_add_values" => $masterAddValues,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "mode" => $cancelMode,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;
            }
            //endregion

            //==init replacer
            //==recover nilai HARGA master
            $_SESSION[$cCode]['main']['harga'] = 0;
            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                foreach ($_SESSION[$cCode]['items'] as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                }
            }
        }
        else {
            die(lgShowAlert("No such transaction. You may want to refresh the browser to re-fetch actual content."));
        }


        $link = MODUL_PATH . "Create/index/$targetJenisTr";
        //        mati_disini($link);
        topRedirect($link);
        die();

    }

    //preview on approval
    public function followupCancelPackingPrePreview()
    {

        $no = rtrim($this->uri->segment(5), "-");
        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = blobEncode(current_url());

        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tmpTr = $tr->lookupJoined();
        showLast_query("biru");
        cekBiru("joined: " . sizeof($tmpTr));
        //endregion

        $cancelPackingId = isset($tmpTr[0]->cancel_packing_source_id) ? $tmpTr[0]->cancel_packing_source_id : 0;
        $tmpTrCancelPacking = array();
        $id_top_source_cancel_packing = array();
        if ($cancelPackingId > 0) {
            $tr->setFilters(array());
            $tr->addFilter("id in (" . implode(",", explode("-", $cancelPackingId)) . ")");
            $tmpTrCancelPacking = $tr->lookupJoined();
            $id_top_source_cancel_packing = $tmpTrCancelPacking[0]->id_top;
        }

        //        matiHere($id_top_source_cancel_packing);

        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            $sCtr = 0;
            foreach ($tmpSign as $row) {
                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }
        $rawItems = array();

        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            //endregion

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber] : null;
            $measurementDetails = isset($this->configUi[$this->jenisTr]["receiptMesurementRows"]) ? $this->configUi[$this->jenisTr]["receiptMesurementRows"] : array();
            $validatePaymentLocker = isset($this->configUi[$this->jenisTr]["validatePaymentSource"][$stepNumber]) ? $this->configUi[$this->jenisTr]["validatePaymentSource"][$stepNumber] : array();
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);

            //region periksa locker value
            $tempLocker = array();
            $tempBtnUndo = array();
            if (sizeof($validatePaymentLocker) > 0) {
                $mdlName = "Mdls/" . $validatePaymentLocker;
                $this->load->model($mdlName);
                $l = new $validatePaymentLocker();
                $l->addFilter("transaksi_id='$no'");
                $l->addFilter("state='active'");
                $l->addFilter("nilai>0");
                $tempLocker = $l->lookupAll()->result();

                if (sizeof($tempLocker) > 0) {
                    $tempBtnUndo = array(
                        "allowedUndone" => true,//tidak boleh di undo/reject
                        "allowedFollow" => false,//boleh di followup
                    );
                }
                else {
                    $jnTarget = isset($this->config->item('payment_source')[$this->jenisTr][$currentStepNum][0]['jenisTarget']) ? $this->config->item('payment_source')[$this->jenisTr][$currentStepNum][0]['jenisTarget'] : "";
                    $tempBtnUndo = array(
                        "allowedUndone" => true,// boleh di undo/reject
                        "allowedFollow" => true,//tidak boleh di followup
                        "label" => isset($this->configUi[$jnTarget]['label']) ? $this->configUi[$jnTarget]['label'] : "",
                    );
                }
            }

            //endregion

            //==periksa apakah ada ganjalan
            $trA = new MdlTransaksi();
            $extSteps = $trA->lookupExtSteps($masterID);
            if (sizeof($extSteps) > 0) {
                cekmerah("ada ganjalan step sebanyak " . sizeof($extSteps));
            }
            else {
                cekhijau("TAK ada ganjalan step");
            }
            $paySrcs = $trA->lookupPaymentSrcs($masterID, $this->jenisTr . "_");
            if (sizeof($paySrcs) > 0) {
                cekmerah("ada ganjalan paymentSrc sebanyak " . sizeof($paySrcs));
            }
            else {
                cekhijau("TAK ada ganjalan paymentSrc");
            }

            $allowEdit = isset($this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit']) ? $this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowEdit'] : false;
            $allowCancel = isset($this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowCancel']) ? $this->configUi[$this->jenisTr]['steps'][$stepNumber]['allowCancel'] : false;
            $editableFields = isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$stepNumber] : array();
            $xCancelConfig = isset($this->configUi[$this->jenisTr]["xShipmentConfig"][$stepNumber]) ? $this->configUi[$this->jenisTr]["xShipmentConfig"][$stepNumber] : array();


            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilterJoin("sub_step_number='" . $currentStepNum . "'");
            $tr->addFilterJoin("next_substep_code='" . $this->configUi[$this->jenisTr]['steps'][$stepNumber]['target'] . "'");
            $tr->addFilterJoin("next_substep_num='$stepNumber'");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTr = $tr->lookupJoined();


            $id_top = isset($tmpTr[0]->id_top) ? $tmpTr[0]->id_top : "";
            $idTr = isset($tmpTr[0]->id) ? $tmpTr[0]->id : "";
            $trPack = new MdlTransaksi();
            $trPack->setFilters(array());
            $trPack->addFilter("id_top in (" . implode(",", explode("-", $id_top)) . ")");
            $trPack->addFilterJoin("valid_qty>0");
            $tmpTrPacked = $trPack->lookupJoined();

            $tmpTrPrePacked = array();
            if (sizeof($id_top_source_cancel_packing) > 0) {
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("id_top in (" . implode(",", explode("-", $id_top_source_cancel_packing)) . ")");
                $trPrePack->addFilterJoin("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined();
            }
            else {
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("cancel_packing_source_id in (" . implode(",", explode("-", $no)) . ")");
                $trPrePack->addFilterJoin("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined();
            }

            $arrPreTmp__ = array();
            foreach ($tmpTrPrePacked as $y => $dd) {
                if (!isset($arrPreTmp__[$dd->jenis][$dd->produk_id])) {
                    $arrPreTmp__[$dd->jenis][$dd->produk_id] = 0;
                }
                $arrPreTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
            }

            $arrTmp__ = array();
            foreach ($tmpTrPacked as $y => $dd) {
                if (!isset($arrTmp__[$dd->jenis][$dd->produk_id])) {
                    $arrTmp__[$dd->jenis][$dd->produk_id] = 0;
                }
                $arrTmp__[$dd->jenis][$dd->produk_id] += $dd->produk_ord_jml;
            }

            $extractedItems = array();//==untuk urusan update transaksi referer

            $validItems = array();
            $validItemSends = array();
            $validItemCancels = array();
            $validItemPreCancels = array();
            $validItemSents = array();

            if (sizeof($tmpTr) > 0) {
                //                cekmerah("ada yang mau diekstrak");
                $shipment = isset($xCancelConfig['shipment']) ? $xCancelConfig['shipment'] : "";
                $packing = isset($xCancelConfig['packing']) ? $xCancelConfig['packing'] : "";
                $cancel = isset($xCancelConfig['cancel']) ? $xCancelConfig['cancel'] : "";


                foreach ($tmpTr as $row) {

                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    if (!isset($validItemCancels[$row->produk_id])) {
                        $validItemCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPackeds[$row->produk_id])) {
                        $validItemPackeds[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPreCancels[$row->produk_id])) {
                        $validItemPreCancels[$row->produk_id] = 0;
                    }

                    $validItems[$row->produk_id] += $row->valid_qty;
                    $validItemSends[$row->produk_id] += isset($arrTmp__[$shipment][$row->produk_id]) ? $arrTmp__[$shipment][$row->produk_id] : 0;
                    $validItemCancels[$row->produk_id] += $row->cancel_qty;
                    $validItemPreCancels[$row->produk_id] += isset($arrPreTmp__[$cancel][$row->produk_id]) ? $arrPreTmp__[$cancel][$row->produk_id] : 0;
                    $validItemPackeds[$row->produk_id] += isset($arrTmp__[$packing][$row->produk_id]) ? $arrTmp__[$packing][$row->produk_id] : 0;

                    if (!isset($extractedItems[$row->produk_id])) {
                        $extractedItems[$row->produk_id] = array();
                    }
                    $extractedItems[$row->produk_id][$row->id_detail] = array(
                        "id" => $row->id_detail,
                        "produk_id" => $row->produk_id,
                        "qty" => $row->produk_ord_jml,
                        "valid_qty" => $row->valid_qty,
                        "transaksi_id" => $row->transaksi_id,
                        //                        "packed_qty" => isset($arrTmp__['582pkd'][$row->produk_id]) ? $arrTmp__['582pkd'][$row->produk_id] : 0,
                        "packed_qty" => isset($arrTmp__[$packing][$row->produk_id]) ? $arrTmp__[$packing][$row->produk_id] : 0,
                        //                        "sent_qty" => isset($arrTmp__['582spd'][$row->produk_id]) ? $arrTmp__['582spd'][$row->produk_id] : 0,
                        "sent_qty" => isset($arrTmp__[$shipment][$row->produk_id]) ? $arrTmp__[$shipment][$row->produk_id] : 0,
                        //                        "req_cancel_qty" => isset($arrPreTmp__['1982'][$row->produk_id]) ? $arrPreTmp__['1982'][$row->produk_id] : 0,
                        "req_cancel_qty" => isset($arrPreTmp__[$cancel][$row->produk_id]) ? $arrPreTmp__[$cancel][$row->produk_id] : 0,
                        "cancel_qty" => $row->cancel_qty,
                        "outstanding" => $row->produk_ord_jml - ($row->produk_ord_jml - $row->valid_qty),
                    );
                }
            }
            else {
                cekmerah("TIDAK ada yang mau diekstrak");
            }

            //            cekHijau(__LINE__);
            //            arrprint($extractedItems);

            //endregion

            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            //            //cekMerah(__LINE__. " " .$this->db->last_query());
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //            arrPrint($detailValues);
            //endregion

            //region take from registries
            //==ambil value-gate
            $trr = new MdlTransaksi();
            $trr->setFilters(array());
            $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
            $tmpReg = $trr->lookupDataRegistries()->result();

            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $masterGates = array();
            $childGates = array();
            $childGates2 = array();
            $childGates2_sum = array();
            $childGatesRsltItems = array();
            $childGatesRsltItems2 = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $childTableInParamsRsltItems = array();
            $childTableInParamsRsltItems2 = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $childTableInValueParamsRsltItems = array();
            $childTableInValueParamsRsltItems2 = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $mainInputs = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        switch ($key_reg) {
                            case "main"://
                                $main = $main + unserialize(base64_decode($val_reg));
                                break;
                            case "items"://
                                $items = $items + unserialize(base64_decode($val_reg));
                                break;
                            case "items2"://
                                $items2 = $items2 + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems"://
                                $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "rsltItems2"://
                                $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "items2_sum"://
                                $items2_sum = $items2_sum + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master"://
                                $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail"://
                                $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems"://
                                $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_rsltItems2"://
                                $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master_values"://
                                $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values"://
                                $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems"://
                                $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values_rsltItems2"://
                                $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_values"://
                                $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_fields"://
                                $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                                break;
                            case "main_elements"://
                                $mainElements = unserialize(base64_decode($val_reg));
                                break;
                            case "main_inputs"://
                                $mainInputs = unserialize(base64_decode($val_reg));
                                break;
                        }
                    }
                }

            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion

            //region replacer Downpayment avail
            if (isset($mainInputs['dp'])) {
                if (isset($this->configUi[$this->jenisTr]["updateDownpayment"][$stepNumber])) {
                    $this->load->model("Coms/ComLockerValue");
                    $mi = new ComLockerValue();
                    $mi->addFilter("produk_id='" . $main['masterID'] . "'");
                    $mainInputAvail = $mi->fetchBalances("downpayment");
                    $lockerVal = $mainInputAvail[0]->nilai;
                    $mainValTmp_dp = $main['dp_value'];
                    $mainValTmp_dp_ppn = $main['dp_ppn_value'];

                    if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                        cekOrange();
                        $validate = round($mainInputAvail[0]->nilai - $mainValTmp_dp, 2);
                        if ($lockerVal > 0) {
                            $valnew = $main['new_net1'] - $lockerVal > 0 ? 0 : $main['new_net1'];
                            $main['dp_value'] = $valnew;
                            $main['dp_ppn_value'] = $valnew * 10 / 100;
                        }
                        else {
                            $main['dp_value'] = 0;
                            $main['dp_ppn_value'] = 0;
                            //                        $main['valid_dp'] = 0;
                        }

                        if ($validate > 0) {
                            $mainInputs['dp'] = $mainInputAvail[0]->nilai;

                        }
                        else {
                            if ($validate < 0) {
                                if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                                    $main['downpayment'] = $mainInputs['dp'];
                                    $mainInputs['downpayment'] = $mainInputs['dp'];
                                    $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['dp_ppn_value'];

                                }
                                unset($mainInputs['dp']);
                                cekhere("sini po");
                            }
                            //                        if(!isset($main['valid_dp'])){
                            //                            $main['valid_dp'] = $mainInputAvail[0]->nilai;
                            //                        }

                        }
                    }
                    else {
                        //                         $mainInputs['dp'] = 0;
                        $main['dp_value'] = 0;
                        $main['dp_ppn_value'] = 0;
                        unset ($mainInputs['dp']);
                    }

                    if (!isset($main['valid_dp'])) {
                        $main['valid_dp'] = $mainInputAvail[0]->nilai;
                    }
                }


            }
            else {
                if (isset($main['valid_dp']) && $main['valid_dp'] > 0) {
                    $main['downpayment'] = $main['dp'];
                    $mainInputs['downpayment'] = $main['dp'];
                    $main['total_ui'] = $masterTableInValueParams['tagihan'] - $masterTableInValueParams['nilai_tambah_ppn_out'];
                }
            }
            //endregion

            $masterReplacers = array(
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $masterTableInParams['jenis_top'],
                "harga" => 0,
                "masterID" => $masterID,
            );
            foreach ($masterReplacers as $key => $src) {
                $main[$key] = $src;
                $mainValues[$key] = $src;
                $masterGates[$key] = $src;
            }

            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();

            if (sizeof($items) > 0) {
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";
                    if (array_key_exists($id, $validItems)) {
                        $items[$id]['jml'] = $validItems[$id] - (int)$validItemPreCancels[$id];
                        $items[$id]['max_jml'] = $validItems[$id] - (int)$validItemPreCancels[$id];
                        $items[$id]['packed_jml'] = $validItemPackeds[$id];
                        $items[$id]['sent_jml'] = $validItemSends[$id];
                        $items[$id]['cancel_jml'] = $validItemCancels[$id];
                        $items[$id]['req_cancel_jml'] = $validItemPreCancels[$id];
                        if (sizeof($editableFields) > 0) {
                            foreach ($editableFields as $fName) {
                                $items[$id]["max_$fName"] = isset($iSpec[$fName]) ? $iSpec[$fName] : 0;
                            }
                        }
                        if (sizeof($measurementDetails)) {
                            if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
                                $selectedColl = $measurementDetails[$tipeSize];
                                foreach ($selectedColl as $colSelected => $tempHelper) {
                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        cekHitam($newKey);
                                        $items[$id][$newKey] = $heAngka($iSpec[$colSelected]);
                                    }
                                }
                            }
                        }
                        if ($subAmountConfig != null) {
                            $tmpEx = $cal->multiExplode($subAmountConfig);
                            if (sizeof($tmpEx) > 1) {
                                $newSrc = $subAmountConfig;
                                foreach ($tmpEx as $key2 => $val2) {
                                    if (isset($items[$id][$val2])) {
                                        $newSrc = str_replace($val2, $items[$id][$val2], $newSrc);
                                    }
                                    else {
                                        if (isset($tmp[$val2])) {
                                            $newSrc = str_replace($val2, $items[$val2], $newSrc);
                                        }
                                        else {
                                            $newSrc = str_replace($val2, "0", $newSrc);
                                        }
                                    }
                                }
                                $subtotal = $cal->calculate($newSrc);
                            }
                            else {
                                $subtotal = $items[$id][$subAmountConfig];
                            }
                        }
                        else {
                            $subtotal = 0;
                        }
                        $items[$id]['subtotal'] = $subtotal;
                    }
                    else {
                        cekUngu(":: masuk sini, UNSET semua ::");
                        unset($items[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);
                    }
                }
            }

            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "rsltItems" => $rsltItems,
                "rsltItems2" => $rsltItems2,
                "extractedItems" => $extractedItems,
                "tableIn_master" => $masterTableInParams,
                "tableIn_detail" => $childTableInParams,
                "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
                "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
                "tableIn_master_values" => $masterTableInValueParams,
                "tableIn_detail_values" => $childTableInValueParams,
                "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
                "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
                "main_add_values" => $masterAddValues,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "lockerPayment" => $tempBtnUndo,
            );
            //            cekKuning("swapping $cCode");
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;
            }
            //endregion

            //==init replacer
            //==recover nilai HARGA master
            $_SESSION[$cCode]['main']['harga'] = 0;
            //==default load dari nota, maka dianggap langsung done
            $_SESSION[$cCode]['main']['status_4'] = 1;
            $_SESSION[$cCode]['main']['trash_4'] = 0;
            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                foreach ($_SESSION[$cCode]['items'] as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                }
            }

            $this->load->helper("he_value_builder");
            resetValues($this->jenisTr);

            fillValues_he_value_builder($this->jenisTr, $this->uri->segment(7), $this->uri->segment(6), $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);

            $actionTarget = "top.BootstrapDialog.closeAll();top.BootstrapDialog.show(
                                   {
                                       title:'FollowUp Cancel Packing Preview',
                                       message: " . 'top.$' . "('<div></div>').load('" . MODUL_PATH . "FollowUp/followupCancelPackingPreview/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "?rawBuilderURL=$rawBuilderURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        type:top.BootstrapDialog.TYPE_DEFAULT,
                                        draggable:true,
                                        closable:false,


                                        }
                                        );";


            echo "<script>top.close_holdon();$actionTarget</script>";

        }
        else {
            die(lgShowAlert("No such transaction. You may want to refresh the browser to re-fetch actual content."));
        }


    }

    public function followupCancelPackingPreview()
    {
        cekHitam(__FUNCTION__);
        $no = rtrim($this->uri->segment(5), "-");
        $targetStepNum = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $afterTargetStepNum = ($targetStepNum + 1);

        $rawPrevURL = blobEncode(current_url());
        $rawBuilderURL = $_GET['rawBuilderURL'];

        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilterJoin("sub_step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined();
        //endregion

        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        if (sizeof($tmpSign) > 0) {
            $sCtr = 0;
            foreach ($tmpSign as $row) {
                $signNumbers[$sCtr] = "" . $row->step_number;
                $sCtr++;
            }
        }
        else {
            //            cekkuning("TAK ada signs");
        }


        $rawItems = array();
        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $pelaku = $tmpTr[0]->oleh_id;
            $cCode = "_TR_" . $this->jenisTr;

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "items2" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            if (!isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = array();
            }
            //endregion

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum] : array();
            $itemLabels2 = isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][$targetStepNum] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$targetStepNum] : array();
            $itemNumLabels2 = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields2'][$targetStepNum] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$targetStepNum] : null;
            $noteEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartNoteEnabled'] == true ? true : false;
            $noteEditabled = isset($this->configUi[$this->jenisTr]['shoppingCartNoteEditabled'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNoteEditabled'][$targetStepNum] : false;
            $noteType = isset($this->configUi[$this->jenisTr]['shoppingCartNoteType']) ? $this->configUi[$this->jenisTr]['shoppingCartNoteType'] : "text";
            $addRowsConfigs = isset($this->configUi[$this->jenisTr]['additionalRows']) ? $this->configUi[$this->jenisTr]['additionalRows'] : array();
            $imageEnabled = isset($this->configUi[$this->jenisTr]['shoppingCartImageEnabled']) && $this->configUi[$this->jenisTr]['shoppingCartImageEnabled'] == true ? true : false;
            $imageType = isset($this->configUi[$this->jenisTr]['shoppingCartImageType']) ? $this->configUi[$this->jenisTr]['shoppingCartImageType'] : "text";

            $masterID = $tmpTr[0]->id_master;
            $trID = $tmpTr[0]->id;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


            //region tabel2 tarikan untuk kolom2 nilai (hpp, ppn, dll)
            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }
            //endregion

            //region take from registries
            //==ambil value-gate
            $tr->setFilters(array());
            //            $tr->addFilter("trash='0'");
            $tmpReg = $tr->lookupDataRegistriesByMasterID($trID)->result();

            $main = array();
            $items = array();
            $masterGates = array();
            $childGates = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $masterAddValues = array();
            $masterAddFields = array();

            $mainElements = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        switch ($key_reg) {
                            case "main"://
                                $main = unserialize(base64_decode($val_reg));
                                break;
                            case "items"://
                                $items = unserialize(base64_decode($val_reg));
                                break;
                            case "items2"://
                                $items2 = unserialize(base64_decode($val_reg));
                                break;
                            case "items2_sum"://
                                $items2_sum = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master"://
                                $masterTableInParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail"://
                                $childTableInParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_master_values"://
                                $masterTableInValueParams = unserialize(base64_decode($val_reg));
                                break;
                            case "tableIn_detail_values"://
                                $childTableInValueParams = unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_values"://
                                $masterAddValues = unserialize(base64_decode($val_reg));
                                break;
                            case "main_add_fields"://
                                $masterAddFields = unserialize(base64_decode($val_reg));
                                break;
                            case "main_elements"://
                                $mainElements = unserialize(base64_decode($val_reg));
                                break;
                        }
                    }
                }
            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion

            foreach ($tmpTr as $row) {
                $id = $row->produk_id;
                $tmp = array();
                if (sizeof($itemLabels) > 0) {
                    foreach ($itemLabels as $key => $val) {
                        if (isset($_SESSION[$cCode]['tableIn_detail_values'][$row->produk_id][$key])) {
                            $fieldValue = $_SESSION[$cCode]['tableIn_detail_values'][$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                $fieldValue = $row->$key;
                            }
                        }
                        $tmp[$key] = $fieldValue;
                    }
                }

                //region calculate subtotal
                //                arrPrint($childGates[$id]);
                //===perhitungan subtotal
                $this->load->library("FieldCalculator");
                $cal = new FieldCalculator();


                if ($subAmountConfig != null) {

                    $arrChildGates[$id] = isset($childGates[$id]) ? $childGates[$id] : array();
                    $subtotal = makeValue($subAmountConfig, $arrChildGates[$id], $arrChildGates[$id], 0);
                }
                else {
                    $subtotal = 0;
                    //                    //cekHijau("subtotal NOL");
                }
                $tmp["subtotal"] = $subtotal;
                //endregion

                $rawItems[$row->produk_id] = $tmp;
            }

        }
        else {

            $errMsg = "the entry you are trying to access does not exist.<br>";
            $errMsg .= "you may try to refresh the browser by pressing F5 button on your keyboard.<br>";
            $errMsg .= "if this error re-occurs, please contact system developer.<br>";


            echo "<script>top.BootstrapDialog.closeAll();</script>";
            die(lgShowAlert($errMsg));
        }
        //endregion

        $items = array();
        $items2 = array();

        $jenisTr = $this->jenisTr;
        $_SESSION[$cCode]['main']['currentID'] = $no;

        //region deteksi tombol2 followup
        $currentStepIndex = array_search($currentStepNum, $signNumbers, true);


        //region ========================approve, reject, undo====================================
        $origTCode = heGetOriginTCode($this->jenisTr);
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
        $userGroup_editElementAllowed = $this->config->item("userGroup_editElementAllowed") != NULL ? $this->config->item("userGroup_editElementAllowed") : array();
        $thisStepGID = isset($this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup'] : "";
        $nextStepGID = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup'] : "";
        $hideFollowUp = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp'] : false;
        $editElementAllowed = array_intersect($userGroup_editElementAllowed, $mems);
        $allowFollowup = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup'] : true;

        $preProcRevConfig = null != $this->config->item("hePreProcessors");
        $preCompRevConfig = null != $this->config->item("heComponents");

        $deleteSpec = array(
            "label" => "cannot delete",
            "targetUrl" => "",
            "warning" => "",
        );
        $undoSpec = array(
            "label" => "cannot undo",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpec = array(
            "label" => "cannot reject 1 step",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectionSpecAll = array(
            "label" => "cannot reject all steps",
            "targetUrl" => "",
            "warning" => "",
        );
        $approvalSpec = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $rejectAllAllowed = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $editSpec = array(
            "label" => "cannot edit",
            "targetUrl" => "",
            "warning" => "",
        );

        $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
        $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);

        //
        cekmerah("evPre: $evPre, evPos: $evPost, evCom: $evCom, currentStep: $currentStepNum, targetStep: $targetStepNum");
        cekKuning("origTCode: $origTCode, currentStepNum: $currentStepNum");
        cekKuning(placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "reject"));

        //==delete, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum == 1) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "delete", $this->configUiJenis)) {//$targetStepNum
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                        );
                    }
                    else {
                    }
                }
                else {
                    //                    cekungu("bukan credit");
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekUngu("delete pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                        );
                    }
                    else {
                        //                        cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                    }
                }
            }
            else {
                //                if (!isset($_SESSION[$cCode]['main']['paymentMethod'])) {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                if ($evPre == null && $evPost == null && $evCom == null) {
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $deleteSpec = array(
                        "label" => "safely delete",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik DELETE akan membuat transaksi dimatikan.",
                    );
                }
                //                }
            }
        }
        else {
            //            cekmerah("NOT possible to delete, $pelaku != " . $this->session->login['id']);
        }

        //==undo, hanya yang mengotorisasi transaksi
        if (($origTCode == null) && ($currentStepNum > 1) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "undo", $this->configUiJenis)) {
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekHere("$evPre :: $evPost :: $evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                        );
                    }
                    else {
                        //                cekmerah("NOT allowed to REJECT");
                    }
                    //undonya
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                cekhijau("allowed to undo");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $undoSpec = array(
                            "label" => "undo last step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                        );
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                //                cekmerah("evPre: $evPre, evPos: $evPost, evCom: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                cekhijau("allowed to undo");
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $undoSpec = array(
                        "label" => "undo last step",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik UNDO akan membuat transaksi mundur 1 langkah.",
                    );
                }
                else {
                    //                cekmerah("NOT allowed to undo");
                }
                //                }
            }
        }
        else {
            //            cekmerah("NOT possible to undo");
        }

        //==reject, hanya yang memiliki hak akses selanjutnya
        if (($origTCode == null) && ($currentStepNum > 0) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "reject", $this->configUiJenis)) {//$targetStepNum
            //            cekHijau("ready to reject");
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                //                cekKuning("kena if locker payment");
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                        );

                        if ($rejectAllAllowed == true) {

                            $rejectionSpecAll = array(
                                "label" => "reject all steps",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                            );
                        }
                    }

                }
                else {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                    //                    cekUngu("pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                        );

                        if ($rejectAllAllowed == true) {
                            $rejectionSpecAll = array(
                                "label" => "reject all steps",
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                                "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                            );
                        }
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                cekHitam("evPreProcc: $evPre, evPostProcc: $evPost, evCom: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                    cekhijau("allowed to REJECT || LINE: " . __LINE__);
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $rejectionSpec = array(
                        "label" => "reject 1 step",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "Klik REJECT akan membuat transaksi mundur 1 langkah.",
                    );
                    if ($rejectAllAllowed == true) {

                        $rejectionSpecAll = array(
                            "label" => "reject all steps",
                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doRevertAll/$jenisTr/$no/$currentStepNum",
                            "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                        );
                    }
                }
                else {
                    cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                }

            }
        }
        else {
            //            cekmerah("NOT possible to reject");
        }


        //edit, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum > 0) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "edit", $this->configUiJenis)) {
            $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
            cekHere("$evPre :: $evPost :: $evCom :: -- $evMaster");
            if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                //                cekhijau("allowed to EDIT");
                $editSpec = array(
                    "label" => "edit",
                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doPreEdit/$jenisTr/$no/$currentStepNum",
                    "warning" => "pressing EDIT will modify entire transaction data. continue?",
                );
            }
            else {
                //                cekmerah("NOT allowed to EDIT");
            }
        }
        else {
            if ($pelaku == $this->session->login['id']) {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCoreJenis, $this->configUiJenis);
                cekHitam("$evPre :: $evPost :: $evCom :: $evMaster :: $currentStepNum");
                if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                    //                    cekhijau("allowed to EDIT");
                    $editSpec = array(
                        "label" => "edit",
                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doPreEdit/$jenisTr/$no/$currentStepNum",
                        "warning" => "pressing EDIT will modify entire transaction data. continue?",
                    );
                }
                else {
                    //                    cekmerah("NOT allowed to EDIT");
                }
            }
        }


        //==approve
        if ($targetStepNum > $currentStepNum) {
            if ($allowFollowup == true) {
                if (isset($_SESSION[$cCode]['lockerPayment']['allowedFollow']) && $_SESSION[$cCode]['lockerPayment']['allowedFollow'] == true) {
                    if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                        if (isset($this->accessList[$this->jenisTr])) {
                            if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {

                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                        }
                        else {
                            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                                //                cekBiru(":: $currentStepNum :: $targetStepNum ::");
                                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                                $msgWarning2 = array();
                                if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                    $trs = new MdlTransaksi();
                                    $trs->setFilters(array());
                                    $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                    if (sizeof($tmpPymSrc)) {
                                        if ($tmpPymSrc[0]->sisa > 0) {
                                            $approvalSpec = array(
                                                "label" => "continue to next step",
                                                "targetUrl" => "",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                //                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $approvalSpec = array(
                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                            );
                        }
                        else {
                            cekUngu("tidak ada approve");
                        }
                    }
                }
                else {
                    if (isset($this->accessList[$this->jenisTr])) {
                        if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(

                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                            $msgWarning2 = array();
                            if ((sizeof($paymentSrcCek)) && (isset($paymentSrcCek['enabled'])) && ($paymentSrcCek['enabled'] == true)) {
                                $trs = new MdlTransaksi();
                                $trs->setFilters(array());
                                $tmpPymSrc = $trs->lookupPaymentSrcByTransID($_SESSION[$cCode]['main']['masterID'])->result();
                                if (sizeof($tmpPymSrc)) {
                                    if ($tmpPymSrc[0]->sisa > 0) {
                                        $approvalSpec = array(
                                            "label" => "continue to next step",
                                            "targetUrl" => "",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {

                                $approvalSpec = array(
                                    //                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                        else {

                        }
                    }
                }
            }
            if ((isset($lockerPreDownpayment)) && ($lockerPreDownpayment == true)) {
                $paymentSrcCek = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['paymentSrc'] : array();
                $msgWarning2 = array();
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $paymentSrcCek['label'],
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
            if (isset($lockShipment) && ($lockShipment == true)) {
                $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                    "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                    "label" => $lockShipmentLabel,
                );
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
        }
        else {
            //            cekmerah("NOT possible to approve");
        }
        //endregion

        if (sizeof($signNumbers) > 0) {
            if ($currentStepIndex > 0) {
                $beforeCurrentIndex = ($currentStepIndex - 1);
                $beforeCurrentStep = $signNumbers[$beforeCurrentIndex];
            }
            else {

                $beforeCurrentStep = 0;
            }

            $masterRevertStep = $beforeCurrentStep;
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "", $this->configUiJenis)) {
                $mComponents = isset($this->configCore[$this->jenisTr]['components'][$currentStepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$currentStepNum]['master'] : array();

                if (sizeof($mComponents) > 0) {
                    $comNames = array();
                    foreach ($mComponents as $cSpec) {
                        $comNames[] = $cSpec['comName'];
                    }
                    if (in_array("Jurnal", $comNames)) {
                        //==tidak bisa di-revert
                    }
                    else {
                        $allowRevert = true;
                        $revertLabel = "undo";
                        $childRevertStep = -($currentStepNum);
                        $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    }
                }
                else {
                    $allowRevert = true;
                    //                    $revertLabel = $masterRevertStep . "undo " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                    $revertLabel = "undo";
                    $childRevertStep = -($currentStepNum);
                    $revertTarget = MODUL_PATH . __CLASS__ . "/doRevert/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";
                }

            }

        }


        //region check if i may approve or unapprove current transaction
        if (isset($this->configUi[$jenisTr]['steps'][$targetStepNum])) {
            if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                $allowFollowup = true;
                $buttonLabel = $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'];
                $acceptTarget = MODUL_PATH . __CLASS__ . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum";
                if (isset($masterRevertStep)) {
                    $mPreProcs = heCountPreProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mPostProcs = heCountPostProcs_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);
                    $mComs = heCountComponents_he_stepping($this->jenisTr, $currentStepNum, $this->configCore);

                    //==set default to ENABLED
                    $childRevertStep = -($currentStepNum);
                    $rejectionLabel = "reject (def)";
                    $rejectionTarget = MODUL_PATH . __CLASS__ . "/dontFollowup/$jenisTr/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

                    if (sizeof($mPreProcs['reversable']) > 0 || sizeof($mPostProcs['reversable']) > 0) {//maka cek dulu, boleh  cancel apa kagak
                        //==set default to DISABLED
                        $rejectionLabel = "can not reject";
                        $rejectionTarget = "";

                    }
                    else {//==langsung bisa dicancel
                        if (heJournalExists($this->jenisTr, $currentStepNum)) {
                            $rejectionLabel = "can not reject";
                            $rejectionTarget = "";
                        }
                        else {
                            //boleh
                        }

                    }

                }
            }
        }
        //endregion

        //region prevalidator
        $items = $rawItems;
        if (isset($this->configCore[$this->jenisTr]['preValidator'][$targetStepNum])) {
            $procList = $this->configCore[$this->jenisTr]['preValidator'][$targetStepNum];

            if (sizeof($procList) > 0) {
                //                //cekBiru("now processing prevalidator..<br>");
                foreach ($procList as $procName) {
                    $mdlProcName = "PreValidator" . $procName;
                    $this->load->model($mdlProcName);
                    //                                            cekHijau("preval name: $mdlProcName<br>");
                    if (isset($childGates) && sizeof($childGates) > 0) {
                        $prc = new $mdlProcName();
                        $requiredParams = $prc->getRequiredParams();
                        if (sizeof($requiredParams) > 0) {
                            $sentParams = array();
                            foreach ($childGates as $odSpec) {
                                $tmp = array();
                                foreach ($requiredParams as $key) {
                                    $tmp[$key] = $odSpec[$key];
                                }

                                $sentParams[] = $tmp;
                            }

                            $prc->pair($masterID, $sentParams);
                            $gotParams = $prc->exec();
                            //                                cekHijau("gotParams");
                            //                                arrprint($gotParams);
                            //                            print_r($gotParams);die();
                            if (isset($gotParams['items2']) && sizeof($gotParams['items2']) > 0) {

                                //                                $items2 = $rawItems;
                                $items2 = $gotParams['items2'];
                                foreach ($gotParams['items2'] as $id => $iSpec) {
                                    //										$id=$iSpec['id'];
                                    if (isset($_SESSION[$cCode]['items'][$id])) {

                                        $items2[$id]['produk_ord_jml'] = $iSpec['produk_ord_jml'];
                                        $items2[$id]['produk_nama'] = $rawItems[$id]['produk_nama'];
                                        $items2[$id]['satuan'] = $rawItems[$id]['satuan'];


                                        $items[$id]['produk_ord_jml'] -= $iSpec['produk_ord_jml'];
                                        $_SESSION[$cCode]['items'][$id]['jml'] -= $iSpec['produk_ord_jml'];
                                        if ($items[$id]['produk_ord_jml'] < 1) {
                                            unset($items[$id]);
                                        }
                                        if ($_SESSION[$cCode]['items'][$id]['jml'] < 1) {
                                            unset($_SESSION[$cCode]['items'][$id]);
                                        }
                                    }
                                }
                            }

                        }
                        else {
                            die("preval $procName does not have requiredParams!");
                        }

                    }
                    else {
                        die("out_detail contains nothing!. skipping preprocessor");
                    }
                }
            }

        }
        else {
            //                echo("no preval defined. skipping preval..<br>");
        }

        //endregion

        //region preview bottom elements

        $saveWarning = "";
        $buttonLabel = $this->configUi[$jenisTr]["steps"][$targetStepNum]['actionLabel'];
        if (isset($this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum])) {
            $saveWarning .= "clicking <strong>$buttonLabel</strong> button will make transaction state to: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . "</strong>";
            $saveWarning .= "<br>It would need to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$afterTargetStepNum]['userGroup'] . "</strong>";
        }
        else {
            $saveWarning .= "clicking <strong>$buttonLabel</strong> button will instantly make transaction state to <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['stateLabel'] . "</strong>";
        }

        //endregion

        //region warn if irreverseble
        $mComponents = isset($this->configCore[$this->jenisTr]['components'][$targetStepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$targetStepNum]['master'] : array();
        if (sizeof($mComponents) > 0) {
            $comNames = array();
            $reks = array();
            foreach ($mComponents as $cSpec) {
                $comNames[] = $cSpec['comName'];
                if ($cSpec['comName'] == "Jurnal") {
                    if (isset($cSpec['loop']) && sizeof($cSpec['loop']) > 0) {
                        foreach ($cSpec['loop'] as $rek => $v) {
                            $reks[$rek] = $rek;
                        }
                    }
                }
            }
            if (in_array("Jurnal", $comNames)) {
                //==tidak bisa di-revert
                $saveWarning .= "<br><span class='text-danger'>starting from this point, you can not undo the change made on this entry.</span>";
                if (sizeof($reks) > 0) {
                    $saveWarning .= "<br><h6><span class='text-blue'>these accounts will be affected at journal: <strong>" . implode(", ", $reks) . ".</strong></span></h6>";
                }
            }
        }
        //endregion


        $this->load->library("Validator");
        $vd = new Validator();
        $vd->setCCode($this->cCode);
        $vd->setConfigUiJenis($this->configUiJenis);
        $msgWarning = $vd->validate2();


        //region replace main labels with properties from future/next step
        $mainProp = $tmpTr[0];
        //        $mainProp = (object)$_SESSION[$cCode]['main'];
        $mainPropReplacers = array(//===replace khusus kebutuhan preview next step
            "jenis_label" => $tmpTr[0]->next_step_label,
            "nomer" => $tmpTr[0]->nomer,
            "result_nomer" => "(to be generated)",
            "dtime" => date("Y-m-d H:i:s"),
        );
        foreach ($mainPropReplacers as $key => $val) {
            $mainProp->$key = $val;
        }
        //endregion

        //region prepare params for viewer

        $editableAddVals = array();
        if (isset($this->configCore[$this->jenisTr]['externalValues']) && sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configCore[$this->jenisTr]['externalValues'] as $exName => $exSpec) {
                if ($exSpec['useAt'] == $targetStepNum) {
                    $editableAddVals[] = $exName;
                }
            }
        }
        else {

        }


        $editableElements = array();
        $elementConfigs = isset($this->configUi[$this->jenisTr]['receiptElements']) ? $this->configUi[$this->jenisTr]['receiptElements'] : array();
        $relElementConfigs = isset($this->configUi[$this->jenisTr]['relativeElements']) ? $this->configUi[$this->jenisTr]['relativeElements'] : array();
        $relOptionConfigs = isset($this->configUi[$this->jenisTr]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();
        $xShipmentConfig = isset($this->configUi[$this->jenisTr]['xShipmentConfig']) ? $this->configUi[$this->jenisTr]['xShipmentConfig'] : array();

        if (sizeof($_SESSION[$cCode]['main_elements']) > 0) {

            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $aKey => $aSpec) {
                    if (array_key_exists($aKey, $mainElements) && in_array($targetStepNum, $aSpec['editPoints'])) {
                        $editableElements[] = $aKey;
                    }
                    if (isset($relElementConfigs[$aKey])) {
                        foreach ($relElementConfigs[$aKey] as $mainRel => $relData) {
                            foreach ($relData as $relKey => $relDetails) {
                                if (in_array("o_seller_spv", $mems)) {
                                    if (array_key_exists($relKey, $mainElements) && in_array($targetStepNum, $relDetails['editPoints'])) {
                                        $editableElements[] = $relKey;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //region elements editor

        $elStr = array();
        $elements = array();
        $aFilter = array();

        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                switch ($eSpec['elementType']) {
                    case "dataModel":
                        $addStr = "";
                        $editStr = "";
                        $amdlName = $eSpec['mdlName'];
                        $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                        $elStr[$eName] = "";
                        $this->load->model("Mdls/" . $amdlName);
                        $labelSrc = $eSpec['labelSrc'];
                        $keySrc = $eSpec['key'];
                        $oo = new $amdlName();
                        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);

                        if (sizeof($aFilter) > 0) {
                            foreach ($aFilter as $filter) {
                                $exFilter = explode("=", $filter);
                                if (sizeof($exFilter) > 1) {
                                    if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                        $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                        //                                    $realFilter = $exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'";
                                        $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                    }
                                }
                            }
                        }
                        $addClick = "";
                        $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array(
                            "viewers" => array(),
                            "creators" => array(),
                            "creatorAdmins" => array(),
                            "updaters" => array(),
                            "updaterAdmins" => array(),
                            "deleters" => array(),
                            "deleterAdmins" => array(),
                            "historyViewers" => array(),
                        );
                        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                        if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                            if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        }
                                        );";
                                $addStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$addClick\"><span class='fa fa-plus'></span></a>";
                            }
                        }

                        $tmpo = $oo->lookupAll()->result();
                        $elPair[$amdlName] = array();
                        $selectorTarget = MODUL_PATH . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";
                        //                        $elStr[$eName] .= "<div class='box'>";
                        $elStr[$eName] .= "<div class='box-body'>";
                        $elStr[$eName] .= "<select class='form-control' onchange=\"top.$('#result').load('$selectorTarget');\">";
                        $elStr[$eName] .= "<option value=''>-select-</option>";
                        if (sizeof($tmpo) > 0) {
                            foreach ($tmpo as $row) {
                                //                                cekHitam($keySrc);
                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";
                                //                                $elStr[$eName] .= "<option value='" . $row->id . "' $selected>" . $row->$labelSrc . "</option>";
                            }
                        }
                        $elStr[$eName] .= "</select>";
                        $elStr[$eName] .= "</div class='box-header'>";

                        $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                        $defValue = "";
                        if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                            if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                $defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                    $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                    $defValue .= "<tr>";
                                    $defValue .= "<td align='left'>$label";
                                    $defValue .= "</td>";
                                    $defValue .= "<td align='left'>" . $fieldLabel;
                                    $defValue .= "</td>";
                                    $defValue .= "</tr>";
                                }
                                $defValue .= "</table>";
                            }
                        }


                        if ($defKey > 0) {
                            if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                    $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        }
                                        );";

                                    $editStr = "<a href='javascript:void(0)' class='btn btn-default' onclick=\"$editClick\"><span class='fa fa-pencil'></span></a>";
                                }
                            }
                        }

                        $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                        $elStr[$eName] .= "</div id='el$amdlName'>";
                        $elStr[$eName] .= "<div class='box-footer'>";

                        $elStr[$eName] .= "<span class='pull-right'>$editStr $addStr</span>";
                        $elStr[$eName] .= "</div class='box-footer'>";

                        $elements[$eName] = array(
                            "mdlName" => $eSpec['mdlName'],
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );


                        break;
                    case "dataField":
                        $elStr[$eName] = "";
                        $defaultValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                        $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";


                        $elStr[$eName] .= "<div class='box-body'>";
                        switch ($eSpec['inputType']) {
                            case "text":
                                $elStr[$eName] .= "<input type=text class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                            case "date":
                                $elStr[$eName] .= "<input type=date class='form-control' value='$defaultValue' onblur=\"top.$('#result').load($selectorTarget);\">";
                                break;
                        }
                        $elStr[$eName] .= "</div class='box-body'>";

                        $elements[] = array(
                            "mdlName" => null,
                            "label" => $eSpec['label'],
                            "string" => $elStr[$eName],
                        );
                        break;
                }
            }
        }

        //endregion

        $xShipmentBtn = array();
        //        if ($xShipmentConfig) {
        //            foreach ($xShipmentConfig as $num => $val) {
        //                $xShipmentBtn_str = array(
        //                    "label" => "close/fullfillment transaksi",
        //                    "targetUrl" => MODUL_PATH . $this->uri->segment(1) . "/preCancelPacking/$no/$jenisTr/1982/$currentStepNum",
        //                    "warning" => "You may cancel the Packing with the remaining items that have not been Packed to Shipping. continue cancel this packing?",
        //                );
        //                $xShipmentBtn = $num == $currentStepNum ? $xShipmentBtn_str : "";
        //            }
        //        }

        $stepLabels = array();
        foreach ($this->configUi[$this->jenisTr]['steps'] as $num => $sSpec) {
            $stepLabels[$num] = $sSpec['label'];
        }

        $tmpTableIn_master = isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array();
        $tmpTableIn_masterValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();
        $main = array_merge(array_filter($main), array_filter($tmpTableIn_master), array_filter($tmpTableIn_masterValues));
        $mainAddValues = isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array();
        if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
            $mainAddValues = array_merge(array_filter($mainAddValues), array_filter($_SESSION[$cCode]['main_add_values']));
        }

        //==iterasi untuk memasukkan element relatif
        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
            //            cekbiru("hendak memeriksa relative impacts");
            foreach ($_SESSION[$cCode]['main_elements'] as $eName => $eSpec) {
                //                cekbiru("memeriksa $eName:");
                if (array_key_exists($eName, $relElementConfigs)) {
                    //                    cekhijau("$eName memiliki relative impacts");
                    $currentValue = "";
                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $eSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $eSpec['value'];
                            break;
                    }
                    if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                        //                        cekhijau("memenuhi syarat");
                        //===daftarkan ke elementConfig
                        if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                            //                            cekmerah("memeriksa $eName, $currentValue");
                            //                            $rcCtr = 0;
                            foreach ($relElementConfigs[$eName][$currentValue] as $rcID => $rcSpec) {
                                //                                $elKey = $eName . "_" . $currentValue . "_" . $rcID;
                                $elKey = $rcID;
                                $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rcID];
                                //                                $rcCtr++;
                            }
                        }
                    }
                    else {
                        //                        cekmerah("TIDAK memenuhi syarat");
                    }
                }
            }
        }

        //==ini dua benda ini dibikin ulang di sini karena nantinya harus selalu refresh tanpa memanggil PrePreview lagi
        $trA = new MdlTransaksi();
        $extSteps = $trA->lookupExtSteps($masterID);
        $paySrcs = $trA->lookupPaymentSrcs($masterID, $this->jenisTr . "_");

        $_SESSION[$cCode]['extSteps'] = $extSteps;
        $_SESSION[$cCode]['paySrcs'] = $paySrcs;

        //create followup buttons for relative inputs
        //region buttons for relative inputs
        $extBtns = array();
        $extNewBtns = array();
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        //        if (isset($_SESSION[$cCode]['extSteps']) && sizeof($_SESSION[$cCode]['extSteps']) > 0) {
        //            foreach ($_SESSION[$cCode]['extSteps'] as $xSpec) {
        //                if (in_array($xSpec['groupID'], $mems)) {
        //                    $actionTarget = "
        //                                    top.BootstrapDialog.show(
        //                                   {
        //                                       title:'review " . $xSpec['label'] . "',
        //                                       message: " . '$' . "('<div></div>').load('" . base_url() . "Transaksi/previewValue/" . $this->jenisTr . "/$masterID/" . $xSpec['id'] . "/" . $this->uri->segment(5) . "?rawPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'),
        //                                        size:top.BootstrapDialog.SIZE_WIDE,
        //                                        draggable:false,
        //                                        closable:true,
        //                                        }
        //                                        );";
        //                    $extBtns[$xSpec['key']] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> review " . $xSpec['label'] . "</a>";
        //                }
        //                else {
        //                    $extBtns[$xSpec['key']] = "<a class='btn btn-default text-muted'><i>unreviewable " . $xSpec['label'] . "</i></a>";
        //                }
        //            }
        //        }
        //        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
        //            foreach ($_SESSION[$cCode]['main_elements'] as $eName => $eSpec) {
        //                if (array_key_exists($eName, $relOptionConfigs)) {
        //                    //                    cekhijau("$eName terdaftar pada relInputs");
        //                    if (isset($relOptionConfigs[$eName][$currentValue]) && sizeof($relOptionConfigs[$eName][$currentValue]) > 0) {
        //                        foreach ($relOptionConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
        //                            if (isset($oValSpec['addPoints']) && in_array($targetStepNum, $oValSpec['addPoints'])) {
        //                                if (in_array($oValSpec['auth']['groupID'], $mems)) {
        //                                    $actionTarget = "
        //                                    top.BootstrapDialog.show(
        //                                   {
        //                                       title:'add " . $oValSpec['label'] . "',
        //                                       message: " . '$' . "('<div></div>').load('" . base_url() . "Transaksi/addValue/" . $this->jenisTr . "/$masterID/" . "0" . "/" . $this->uri->segment(5) . "?rawPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'),
        //                                        size:top.BootstrapDialog.SIZE_WIDE,
        //                                        draggable:false,
        //                                        closable:true,
        //                                        }
        //                                        );";
        //                                    $extNewBtns[$oValueName] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> add " . $oValSpec['label'] . "</a>";
        //                                }
        //                                else {
        //                                    //                                    cekmerah("you are not allowed");
        //                                }
        //                            }
        //                            else {
        //                                //                                cekhijau("$oValueName TIDAK memenuhi syarat");
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //endregion

        //create followup buttons for paymentSrc-related
        //region buttons for paymentSrc-related
        $payBtns = array();
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();

        //        if (isset($_SESSION[$cCode]['paySrcs']) && sizeof($_SESSION[$cCode]['paySrcs']) > 0) {
        //            foreach ($_SESSION[$cCode]['paySrcs'] as $xSpec) {
        //                if ($xSpec['sisa'] > 0) {
        //
        //                    //                arrprint($xSpec);
        //                    $xSpec['groupID'] = $this->configUi[$xSpec['targetJenis']]['steps'][1]['userGroup'];
        //                    if (in_array($xSpec['groupID'], $mems)) {
        //                        $actionTarget = "
        //                                    top.BootstrapDialog.show(
        //                                   {
        //                                       title:'do " . $xSpec['label'] . "',
        //                                       message: " . '$' . "('<div></div>').load('" . base_url() . "Transaksi/selectPaymentSrc/" . $xSpec['targetJenis'] . "/" . $xSpec['extID'] . "/$masterID?rawPrev=$rawPrevURL'),
        //                                        size:top.BootstrapDialog.SIZE_WIDE,
        //                                        draggable:false,
        //                                        closable:true,
        //                                        }
        //                                        );";
        //                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-warning' href='javascript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> do " . $xSpec['label'] . "</a>";
        //                    }
        //                    else {
        //                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-default text-muted'><i>" . $xSpec['label'] . "</i></a>";
        //                    }
        //                }
        //            }
        //        }

        //endregion

        //region additional row
        $selectedService = isset($_SESSION[$cCode]['main']['shippingService']) ? $_SESSION[$cCode]['main']['shippingService'] : "";

        $allowEditRowa = isset($this->configUi[$this->jenisTr]["additionalRows"]["shippingService"][$selectedService]["shipping_service"]['editPoints']) ? $this->configUi[$this->jenisTr]["additionalRows"]["shippingService"][$selectedService]["shipping_service"]['editPoints'] : array();
        $addRows = array();
        $addRowLabels = array();
        if (in_array($targetStepNum, $allowEditRowa)) {
            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $eName => $eSpec) {
                    //reset dulu kalau yg tidak ada
                    if (array_key_exists($eName, $relElementConfigs)) {
                        //                    cekkuning("$eName ada dalam elementConfig, reset dulu adik2nya<br>");
                        switch ($eSpec['elementType']) {
                            case "dataModel":
                                $currentValue = $eSpec['key'];
                                break;
                            case "dataField":
                                $currentValue = $eSpec['value'];
                                break;
                        }
                        if (sizeof($relElementConfigs[$eName]) > 0) {
                            foreach ($relElementConfigs[$eName] as $valID => $valSpec) {

                                //                            cekkuning("chek if i should reset $valID..");

                                if ($currentValue == $valID) {
                                    //                                cekkuning("i wont reset $valID..");
                                }
                                else {


                                }
                            }

                        }
                        //					$currentValue = "";

                        if (array_key_exists($currentValue, $relElementConfigs[$eName])) {
                            //                        echo("-- $currentValue ada dalam elementConfig $eName<br>");
                            //===daftarkan ke elementConfig
                            if (sizeof($relElementConfigs[$eName][$currentValue]) > 0) {
                                //                            echo("---- memeriksa $eName, $currentValue<br>");
                                //                            $rcCtr=0;
                                foreach ($relElementConfigs[$eName][$currentValue] as $rKey => $rcSpec) {
                                    //                                $elKey = $eName . "_" . $currentValue . "_" . $rKey;
                                    $elKey = $rKey;
                                    $elementConfigs[$elKey] = $relElementConfigs[$eName][$currentValue][$rKey];
                                    //                                echo "elKey: $elKey";
                                    //                                $rcCtr++;


                                }
                            }
                            else {
                                //                            echo("---- TIDAK PERLU memeriksa $eName, $currentValue<br>");
                            }

                        }
                        else {
                            //                        echo("-- $currentValue TIDAK ada dalam elementConfig $eName<br>");
                        }
                    }
                    else {
                        //                    echo("$eName TIDAK ada dalam elementConfig<br>");
                    }
                    if (array_key_exists($eName, $addRowsConfigs)) {
                        switch ($elementConfigs[$eName]['elementType']) {
                            case "dataModel":
                                $currentValue = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : "";
                                break;
                            case "dataField":
                                $currentValue = $_SESSION[$cCode]['main_elements'][$eName]['value'];
                                break;
                        }
                        if (isset($addRowsConfigs[$eName][$currentValue])) {
                            if (sizeof($addRowsConfigs[$eName][$currentValue]) > 0) {
                                foreach ($addRowsConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                    if (isset($oValSpec['editPoints']) && in_array($targetStepNum, $oValSpec['editPoints'])) {
                                        $relInputTarget = "'" . MODUL_PATH . "_shoppingCart/recordAddRow/" . $this->jenisTr . "/$oValueName/?val='+this.value+'&ravPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'";

                                        //==init value and params
                                        //region default value
                                        if (isset($oValSpec['defaultValue'])) {
                                            $origDefValue = makeValue($oValSpec['defaultValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                        }
                                        //endregion

                                        //                                    cekmerah("$oValueName = ".$origDefValue);


                                        //region max-value
                                        $maxValue = $origDefValue;
                                        if (isset($oValSpec['maxValue'])) {
                                            $maxValue = makeValue($oValSpec['maxValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);

                                        }
                                        else {
                                            $maxValue = "";
                                        }

                                        //endregion


                                        //region min-value
                                        $minValue = $origDefValue;
                                        if (isset($oValSpec['minValue'])) {
                                            $minValue = makeValue($oValSpec['minValue'], $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                        }
                                        else {
                                            $minValue = "";
                                        }
                                        //endregion

                                        $minValStr = $minValue != "" ? "min='$minValue'" : "";
                                        $maxValStr = $maxValue != "" ? "max='$maxValue'" : "";

                                        //region inisiasi keystroke
                                        $keyupAct = "";
                                        if (isset($oValSpec['keyupAction']) && strlen($oValSpec['keyupAction']) > 0) {
                                            $keyupAct = $oValSpec['keyupAction'];
                                        }

                                        $keyupStr = "";
                                        if ($maxValue != "") {
                                            $keyupStr .= "if(parseInt(this.value)>$maxValue){this.value='$origDefValue';this.select();} ";
                                        }
                                        $keyupStr .= $keyupAct;


                                        $disabled = "";
                                        if (isset($oValSpec['disabled'])) {
                                            $disabled = $oValSpec['disabled'];
                                        }


                                        $blurStr = "";
                                        if ($minValue != "") {
                                            $blurStr = "if(this.value!=this.defaultValue){if(parseInt(this.value)>=$minValue){hiliteDiv(this);top.$('#result').load($relInputTarget);}else{this.value='$minValue';this.focus();}}";
                                        }
                                        else {
                                            $blurStr = "if(this.value!=this.defaultValue){hiliteDiv(this);top.$('#result').load($relInputTarget);}";

                                        }
                                        //endregion

                                        $defVal = isset($_SESSION[$cCode]['main'][$oValueName]) && $_SESSION[$cCode]['main'][$oValueName] > 0 ? ($_SESSION[$cCode]['main'][$oValueName] + 0) : $origDefValue;
                                        if (isset($addRowsConfigs[$eName][$currentValue][$oValueName]['role']) && $addRowsConfigs[$eName][$currentValue][$oValueName]['role'] == "minus") {
                                            $defVal = "(" . $defVal . ")";
                                        }
                                        //                                    $defVal = $origDefValue;
                                        $addRows[$oValueName] = "<input type=text autocomplete='off' id='$oValueName' class='form-control text-right' style='font-size:17px;' $disabled placeholder='$oValueName' value='$defVal' $minValStr $maxValStr
onfocusssss='this.select()' onkeyup=\"$keyupStr\" onfocus=\"$keyupStr\"
onblur=\"$blurStr\"
onmouseout=\"$blurStr\"
>";
                                        $_SESSION[$cCode]['add_rows'][$oValueName] = $defVal;
                                        $addRowLabels[$oValueName] = $oValSpec['label'];

                                    }

                                }

                            }
                        }
                        else {
                            //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                            //                        cekmerah("aturan untuk $currentValue TIDAK ada");
                        }

                    }
                    else {
                        //					cekKuning("$eName TIDAK terdaftar pada relInputs");
                    }
                    switch ($eSpec['elementType']) {
                        case "dataModel":
                            $addStr = "";
                            $editStr = "";
                            $amdlName = $eSpec['mdlName'];
                            $aFilter = isset($eSpec['mdlFilter']) ? $eSpec['mdlFilter'] : array();

                            $elStr[$eName] = "";
                            $this->load->model("Mdls/" . $amdlName);
                            $labelSrc = $eSpec['labelSrc'];
                            $keySrc = $eSpec['key'];
                            $oo = new $amdlName();
                            $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);

                            if (sizeof($aFilter) > 0) {
                                foreach ($aFilter as $filter) {
                                    $exFilter = explode("=", $filter);
                                    if (sizeof($exFilter) > 1) {
                                        if (substr($exFilter[1], 0, 1) == ".") {
                                            //                                        $oo->addFilter($exFilter[0] . "='" . ltrim($exFilter[1], ".") . "'");
                                        }
                                        else {
                                            if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                                //                                            $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                                $addLink .= "?reqField=" . $exFilter[0] . "&reqVal=" . $_SESSION[$cCode]['main'][$exFilter[1]];
                                            }
                                            else {
                                                //                                            $oo->addFilter($exFilter[0] . "='none'");
                                            }
                                        }
                                    }
                                }
                                $oo = makeFilter($aFilter, $_SESSION[$cCode]['main'], $oo);
                            }

                            $addClick = "";
                            $dataAccess = isset($this->config->item('heDataBehaviour')[$amdlName]) ? $this->config->item('heDataBehaviour')[$amdlName] : array(
                                "viewers" => array(),
                                "creators" => array(),
                                "creatorAdmins" => array(),
                                "updaters" => array(),
                                "updaterAdmins" => array(),
                                "deleters" => array(),
                                "deleterAdmins" => array(),
                                "historyViewers" => array(),
                            );
                            $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
                            if (sizeof($mems) > 0 && sizeof($dataAccess['creators']) > 0) {
                                if (sizeof(array_intersect($mems, $dataAccess['creators'])) > 0) {
                                    $addClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $addLink . "'),
                                        draggable:true,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";
                                    $addStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$addClick\"><span class='fa fa-plus'></span></a>";
                                }
                            }

                            //                        cekmerah("pre..");
                            $tmpo = $oo->lookupAll()->result();
                            //                        cekmerah(__LINE__. " " .$this->db->last_query());
                            $elPair[$amdlName] = array();
                            $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+this.value";

                            $elStr[$eName] .= "<div class='box-body'>";

                            switch ($eSpec['inputType']) {
                                case "combo":
                                    $elStr[$eName] .= "<select class='form-control' onchange=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">";
                                    $elStr[$eName] .= "<option value=''>-select-</option>";
                                    if (sizeof($tmpo) > 0) {
                                        foreach ($tmpo as $row) {

                                            $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                            if (sizeof($ex) > 1) {
                                                $labelValue = "";
                                                foreach ($ex as $col) {

                                                    $labelValue .= $row->$col . " / ";
                                                }
                                                $labelValue = rtrim($labelValue, " / ");
                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";

                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $labelValue . "</option>";
                                                //                                            $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $$labelValue . "</option>";

                                            }
                                            else {
                                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "selected" : "";
                                                $elStr[$eName] .= "<option value='" . $row->$keySrc . "' $selected>" . $row->$labelSrc . "</option>";
                                            }


                                        }
                                    }
                                    $elStr[$eName] .= "</select>";
                                    break;
                                case "radio":

                                    if (sizeof($tmpo) > 0) {
                                        foreach ($tmpo as $row) {
                                            $ex = explode("/", $elementConfigs[$eName]['labelSrc']);
                                            if (sizeof($ex) > 1) {
                                                $labelValue = "";
                                                foreach ($ex as $col) {

                                                    $labelValue .= $row->$col . " / ";
                                                }
                                                $labelValue = rtrim($labelValue, " / ");
                                                $elPair[$amdlName][$row->$keySrc] = $labelValue;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                                $elStr[$eName] .= "<label class='badge' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $labelValue . "</label>&nbsp;";
                                            }
                                            else {
                                                $elPair[$amdlName][$row->$keySrc] = $row->$labelSrc;
                                                $selected = isset($_SESSION[$cCode]['main_elements'][$eName]) && $_SESSION[$cCode]['main_elements'][$eName]['key'] == $row->$keySrc ? "checked" : "";
                                                $elStr[$eName] .= "<label class='badge' style='padding:4px 6px 4px 6px;color:#454545;background:#e0e0e0;'><input type='radio' name='$eName' value='" . $row->$keySrc . "' $selected onclick=\"hiliteDiv(this);top.$('#result').load($selectorTarget);\">" . $row->$labelSrc . "</label>&nbsp;";
                                            }

                                        }
                                    }
                                    break;
                            }


                            $elStr[$eName] .= "</div class='box-header'>";

                            $defKey = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : 0;
                            $defValue = "";
                            if (isset($_SESSION[$cCode]['main_elements'][$eName]['key']) && $_SESSION[$cCode]['main_elements'][$eName]['contents']) {
                                if (isset($elementConfigs[$eName]['usedFields']) && sizeof($elementConfigs[$eName]['usedFields']) > 0) {
                                    //								$defValue .= "<table class='table table-condensed no-padding' style='padding:0px;margin:0px;'>";
                                    $defValue .= "<div class='panel-body'>";
                                    $defValue .= "<table cellspacing='0' cellpadding='0' border='0'>";
                                    $contents[$eName] = unserialize(base64_decode($_SESSION[$cCode]['main_elements'][$eName]['contents']));
                                    foreach ($elementConfigs[$eName]['usedFields'] as $src => $label) {
                                        $fieldLabel = isset($contents[$eName][$src]) ? $contents[$eName][$src] : "-";
                                        //                                    if(is_numeric($fieldLabel)){
                                        //                                        $fieldLabel=number_format($fieldLabel);
                                        //                                    }
                                        $defValue .= "<tr>";
                                        $defValue .= "<td align='left'>$label";
                                        $defValue .= "&nbsp;</td>";
                                        $defValue .= "<td align='left'>:&nbsp;" . $fieldLabel;
                                        $defValue .= "</td>";
                                        $defValue .= "</tr>";
                                    }
                                    $defValue .= "</table>";
                                    $defValue .= "</div class='panel-body'>";
                                }
                            }
                            else {//menentukan nilai default

                            }

                            if ($defKey > 0) {
                                if (sizeof($mems) > 0 && sizeof($dataAccess['updaters']) > 0) {
                                    $editLink = base_url() . "Data/edit/" . str_replace("Mdl", "", $amdlName) . "/$defKey";
                                    if (sizeof(array_intersect($mems, $dataAccess['updaters'])) > 0) {
                                        $editClick = "
                    BootstrapDialog.show(
                                   {
                                        title:'New " . $eSpec['label'] . "',
                                        message: $('<div></div>').load('" . $editLink . "'),
                                        draggable:true,
                                        size:BootstrapDialog.SIZE_WIDE,
                                        closable:true,
                                        type:top.BootstrapDialog.TYPE_SUCCESS,
                                        }
                                        );";

                                        $editStr = "<a href='javascript:void(0)' class='btn btn-tool' onclick=\"$editClick\"><span class='fa fa-pencil'></span></a>";
                                    }
                                }
                            }

                            $elStr[$eName] .= "<div id='divel_$eName' style='padding:2px;font-size:smaller;'>$defValue";
                            $elStr[$eName] .= "</div id='el$amdlName'>";

                            $elements[$eName] = array(
                                "mdlName" => $eSpec['mdlName'],
                                "label" => $eSpec['label'],
                                "string" => $elStr[$eName],
                                "editStr" => $editStr,
                                "addStr" => $addStr,
                                "bgColor" => $defValue == "" ? "#fcfce0" : "#f5fff9",
                            );


                            break;
                        case "dataField":
                            $elStr[$eName] = "";
                            $initValue = isset($eSpec['defaultValue']) ? $eSpec['defaultValue'] : "";
                            $defaultValue = isset($_SESSION[$cCode]['main'][$eName]) ? $_SESSION[$cCode]['main'][$eName] : 0;
                            $selectorTarget = "'" . MODUL_PATH . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+this.value";

                            $maxValue = isset($eSpec['maxValue']) && isset($_SESSION[$cCode]['main'][$eSpec['maxValue']]) ? $_SESSION[$cCode]['main'][$eSpec['maxValue']] : "";

                            $elStr[$eName] .= "<div class='box-body'>";
                            switch ($eSpec['inputType']) {
                                case "text":
                                    $elStr[$eName] .= "<input type=text class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                                case "number":
                                    $maxValStr = $maxValue != "" ? " max='" . $maxValue . "''" : "";
                                    $maxValValidator = $maxValue != "" ? " onkeyup=\"if(this.value>$maxValue){this.value='$maxValue';}\" " : "";
                                    $elStr[$eName] .= "<input type=number class='form-control' value='$defaultValue' onfocus='this.select()' $maxValStr $maxValValidator oonclick=\"this.value='$defaultValue';\"
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                                case "date":
                                    $elStr[$eName] .= "<input type=date class='form-control' value='$defaultValue' onfocus='this.select()' oonclick=\"this.value='$defaultValue';\"
onblur=\"if(this.value!=this.defaultValue){if(this.value.length<1){this.value='$initValue'};hiliteDiv(this);top.$('#result').load($selectorTarget);}\">";
                                    break;
                            }
                            $elStr[$eName] .= "</div class='box-body'>";

                            $elements[$eName] = array(
                                "mdlName" => null,
                                "label" => $eSpec['label'],
                                "string" => $elStr[$eName],
                                "editStr" => "",
                                "addStr" => "",
                                "bgColor" => $defaultValue == "" ? "#fcfce0" : "#fcfcff",
                            );
                            break;
                    }
                }
            }
        }

        //endregion


        $detilSizeBar = array();
        $measureConf = isset($this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum] : false;

        if ($measureConf) {
            if (isset($elements['detilSize'])) {
                $detilSizeBar = array(
                    "volume_gross" => isset($main['volume_gross']) ? number_format(conv_mmc_mc($main['volume_gross']), 2) : 0,
                    "berat_gross" => isset($main['berat_gross']) ? conv_g_kg($main['berat_gross']) : 0,
                );
            }
        }


        $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "sub-amount");
        $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "sub-amount");
        if (isset($this->configUi[$this->jenisTr]['shoppingCartHideSubamount']) && $this->configUi[$this->jenisTr]['shoppingCartHideSubamount'][$targetStepNum] == true) {
            unset($itemLabels['subtotal']);
            unset($itemLabels2['subtotal']);
        }

        //        $rejectionSpec = array(
        //            "label" => "cannot reject",
        //            "targetUrl" => "",
        //            "warning" => "",
        //        );
        //        $deleteSpec = array(
        //            "label" => "cannot delete",
        //            "targetUrl" => "",
        //            "warning" => "",
        //        );

        $pairedItemTarget = isset($this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName']) ? $this->configUi[$this->jenisTr]['shoppingCartPairedItem']['targetGateName'] : "items2";
        $data = array(
            "mode" => $this->uri->segment(3),
            "template" => $this->configUi[$jenisTr]["template"],
            "title" => $this->configUi[$jenisTr]["label"],
            "subTitle" => $this->configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "pihakLabel" => $this->configUi[$jenisTr]["pihakLabel"],
            "mainLabels" => $this->configLayout[$jenisTr]["receiptMainFields"],
            "main" => $mainProp,
            //            "mainValues"        => $mainValues,
            "mainValues" => $_SESSION[$cCode]['main'],
            //            "detailValues"      => $detailValues,
            "detailValues" => $_SESSION[$cCode]['tableIn_detail_values'],
            //            "itemLabels" => $itemLabels,
            "itemLabels" => $itemLabels,
            "itemLabels2" => $itemLabels2,
            "noteEnabled" => $noteEnabled,
            "noteEditabled" => $noteEditabled,
            "noteType" => $noteType,
            "imageEnabled" => $imageEnabled,
            "imageType" => $imageType,
            "detilSizeBar" => $detilSizeBar,

            //            "itemLabels2" => array
            //            (
            //                "produk_nama" => "item name",
            //                "produk_ord_jml" => "qty",
            //                "satuan" => "satuan",
            //
            //            ),
            "items" => $_SESSION[$cCode]['items'],
            //            "items2"                => $_SESSION[$cCode]['items2_sum'],
            "items2" => isset($_SESSION[$cCode][$pairedItemTarget]) ? $_SESSION[$cCode][$pairedItemTarget] : array(),
            //            "items2" => $_SESSION[$cCode]['items2'],
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            //            "sumRows" => $this->configLayout[$this->jenisTr]['receiptSumFields'][$targetStepNum],
            "sumRows" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum] : $this->configLayout[$this->jenisTr]['receiptSumFields'][$targetStepNum],
            "extValueLabels" => isset($this->configCore[$this->jenisTr]['externalValues']) ? $this->configCore[$this->jenisTr]['externalValues'] : array(),
            "extEditableFields" => $editableAddVals,
            //            "mainAddValues" => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
            //            "mainAddFields" => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
            "mainAddValues" => $mainAddValues,
            "mainAddFields" => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
            //            "mainApplets"       => $mainApplets,
            //            "editableApplets"   => $editableApplets,
            "mainElements" => $_SESSION[$cCode]['main_elements'],
            "elements" => $elements,
            "editableElements" => $editableElements,
            "elementConfig" => $elementConfigs,
            "mainInputs" => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
            "elementEditTarget" => MODUL_PATH . "_followupLiveEdit/selectElement/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "actionTarget" => MODUL_PATH . $this->uri->segment(2) . "/doCancelPacking/" . $this->jenisTr . "/$no/$targetStepNum/$currentStepNum",
            "paymentMethod" => isset($tmpTr[0]->pembayaran) ? $tmpTr[0]->pembayaran : "",
            "grandTotal" => isset($_SESSION[$cCode]['main']['grand_total']) ? $_SESSION[$cCode]['main']['grand_total'] : 0,

            "description" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",

            "allowEdit" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowEdit']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowEdit'] : false,
            "allowCancel" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowCancel']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowCancel'] : false,
            "allowIncrement" => isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowIncrement']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowIncrement'] : false,
            "editableFields" => isset($this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartEditableFields'][$targetStepNum] : array(),
            "stepLabels" => $stepLabels,
            "rawPrevURL" => $rawPrevURL,
            "rawBuilderURL" => $rawBuilderURL,
            "currentStep" => $targetStepNum,
            "extSteps" => isset($_SESSION[$cCode]['extSteps']) ? $_SESSION[$cCode]['extSteps'] : array(),
            "paySrcs" => isset($_SESSION[$cCode]['paySrcs']) ? $_SESSION[$cCode]['paySrcs'] : array(),
            "extBtns" => $extBtns,
            "extNewBtns" => $extNewBtns,
            "payBtns" => $payBtns,
            "xShipmentBtn" => $xShipmentBtn,
            //==================liveEdit========================
            "followupSegments" => array(
                $this->uri->segment(3),
                $this->uri->segment(4),
                $this->uri->segment(5),
            ),
            "removeItemTarget" => MODUL_PATH . "_followupLiveEdit/removeItem/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateItemFieldTarget" => MODUL_PATH . "_followupLiveEdit/updateItemField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "updateMainFieldTarget" => MODUL_PATH . "_followupLiveEdit/updateMainField/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "clearContentTarget" => MODUL_PATH . get_class($this) . "/clearContent/" . $this->jenisTr,
            "msgWarning" => isset($msgWarning) ? $msgWarning : array(),

            "msgWarning2" => isset($msgWarning2) ? $msgWarning2 : array(),
            //
            "addRows" => $addRows,
            "addRowLabels" => $addRowLabels,
            "deleteSpec" => $deleteSpec,
            "undoSpec" => $undoSpec,
            "rejectionSpec" => $rejectionSpec,
            "approvalSpec" => $approvalSpec,
            "editSpec" => $editSpec,

        );
        arrPrintPink($approvalSpec);

        if (isset($_SESSION[$cCode]['main'])) {
            $data['pihakID'] = isset($_SESSION[$cCode]['main']['pihakID']) ? $_SESSION[$cCode]['main']['pihakID'] : 0;
            $data['pihakName'] = isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] : "";
        }
        //endregion


        $this->load->view("transaksi", $data);

    }

    //approval cancel packing
    public function doCancelPacking()
    {
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }


        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);

        $paramPatchers = $this->config->item('heTransaksi_paramPatchers') != null ? $this->config->item('heTransaksi_paramPatchers') : array();
        $paramForceFillers = $this->config->item('heTransaksi_paramForceFillers') != null ? $this->config->item('heTransaksi_paramForceFillers') : array();

        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        //==ambil datanya
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("step_number='" . $stepNumCurrent . "'");
        $tr->addFilterJoin("transaksi_data.trash='0'");
        $tmpTr = $tr->lookupJoined();

        $cancel_packing_source_id = $tmpTr[0]->cancel_packing_source_id;
        cekHitam($this->db->last_query());

        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            //endregion

            $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["target"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["target"] : NULL;
            $detailValuesConfig = isset($this->configCore[$this->jenisTr]['tableIn']['detailValues']) ? $this->configCore[$this->jenisTr]['tableIn']['detailValues'] : array();
            $masterID = $_SESSION[$cCode]['main']['masterID'];
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $trID = $tmpTr[0]->transaksi_id;

            //==references, previous entry
            $prevProp = array(
                "id" => $tmpTr[0]->transaksi_id,
                "jenis" => $tmpTr[0]->jenis,
                "nomer" => $tmpTr[0]->nomer,
            );

            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }


            $main = array();
            $items = array();
            $prevIDs = array();
            $prevNos = array();
            foreach ($tmpTr as $row) {
                $items[$row->produk_id] = array(
                    "id" => $row->produk_id,
                    "nama" => $row->produk_nama,
                    "jml" => $row->produk_ord_jml,
                    "harga" => $row->produk_ord_hrg,
                    "valid_qty" => $row->valid_qty,
                    "transaksi_id" => $row->transaksi_id,
                    "nomer" => $row->nomer,
                );

                if ($row->valid_qty > 0) {
                    cekHitam("ok lanjut");
                }
                else {
                    if (isset($_SESSION[$cCode]['items'][$row->produk_id])) {
                        matiHere("Followed up already. Please close and refresh your browser " . $row->produk_nama . " " . $row->produk_id);//kalo session active ya harus dimatiin biar gak dobel
                    }
                }

                if (!in_array($row->transaksi_id, $prevIDs)) {
                    $prevIDs[] = $row->transaksi_id;
                }
                if (!in_array($row->nomer, $prevNos)) {
                    $prevNos[] = $row->nomer;
                }
                if (sizeof($detailValuesConfig) > 0) {
                    echo "detail values ada..<br>";
                    foreach ($detailValuesConfig as $key => $src) {
                        echo "$key akan ambil nilai dari $src<br>";
                        if (isset($detailValues[$row->produk_id][$key])) {
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "dan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                    }
                }
            }

        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }


        //==ongkir dll (additional fees) harus diselipkan kedalam masterGates aktual
        //region ongkir dll diselipkan ke masterGates
        if (isset($this->configCore[$this->jenisTr]['externalValues']) && sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configCore[$this->jenisTr]['externalValues'] as $exKey => $exSpec) {
                if ($exSpec['useAt'] == $stepNum) {
                    if (isset($exSpec['mdlName']) && strlen($exSpec['mdlName']) > 3) {
                        $_SESSION[$cCode]['main'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_src"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        }
                    }
                    $_SESSION[$cCode]['main'][$exKey] = $_POST[$exKey];
                    if (isset($_SESSION[$cCode]['main_add_values'][$exKey])) {
                        $_SESSION[$cCode]['main_add_values'][$exKey] = $_POST[$exKey];
                    }

                    if ($exSpec['taxFactor'] > 0) {
                        $_SESSION[$cCode]['main'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_tax"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        }
                    }
                }
            }
        }
        //endregion


        //region baca seting optional step
        if (isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) && strlen($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) > 0) {
            //            //cekBiru("OPT ditentukan");
            $criteriaField = $this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField'];
            if (isset($_SESSION[$cCode]['main'][$criteriaField]) && $_SESSION[$cCode]['main'][$criteriaField] > 0) {
                echo "nextstepnum normal<br>";
                $nextStepNum = ($stepNum + 1);
                $useAdditionalStep = true;
            }
            else {
                echo "nextstepnum hampir normal<br>";
                $useAdditionalStep = false;
                $nextStepNum = ($stepNum + 2);
            }
        }
        else {
            //            //cekBiru("OPT TIDAK ditentukan");
            echo "nextstepnum TIDAK normal<br>";
            $useAdditionalStep = false;
            $nextStepNum = ($stepNum + 1);
            echo "yaitu $nextStepNum<br>";
        }
        //endregion


        //region build table rekening
        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();


        $addMasterTables = array(
            "rugilaba",
            "laba ditahan",
            "rugilaba lain lain",
        );
        foreach ($addMasterTables as $trek) {
            $buildTablesMaster[] = array(
                "comName" => "RugiLaba",
                "loop" => array(
                    "$trek" => .0,
                ),
            );
        }

        if (sizeof($buildTablesMaster) > 0) {
            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
                $mdlName = $buildTablesMaster_specs['comName'];
                $mdlName = "Com" . $mdlName;
                //cekHitam("model: $mdlName");
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();
                if (method_exists($m, "getTableNameMaster")) {
                    if (sizeof($m->getTableNameMaster())) {
                        $m->buildTables($buildTablesMaster_specs);
                    }
                }
            }
        }

        if (sizeof($buildTablesDetail) > 0) {
            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
                $mdlName = $buildTablesDetail_specs['comName'];
                $mdlName = "Com" . $mdlName;
                //cekHitam("model: $mdlName");
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();
                if (method_exists($m, "getTableNameMaster")) {
                    if (sizeof($m->getTableNameMaster())) {
                        $m->buildTables($buildTablesDetail_specs);
                    }
                }
            }
        }
        //endregion


        $this->db->trans_start();


        //update/swap valid_qty to cancel_qty
        $trTrash = new MdlTransaksi();
        $trTrash->setFilters(array());
        $trTrash->addFilter("id in (" . implode(",", explode("-", $cancel_packing_source_id)) . ")");
        //        $trTrash->addFilter("valid_qty>0 OR req_cancel_qty>0");
        $tmpTrS = $trTrash->lookupJoined();

        $trCancel = array();
        if (sizeof($tmpTrS) > 0) {
            foreach ($tmpTrS as $row) {
                $trCancel['valid_qty'][$row->produk_id] = $row->valid_qty;
                $trCancel['cancel_qty'][$row->produk_id] = $row->cancel_qty;
                $trCancel['req_cancel_qty'][$row->produk_id] = $row->req_cancel_qty;
            }
        }

        arrPrint($trCancel);

        $bQty = array();
        foreach ($tmpTr as $row) {
            if (!isset($bQty[$row->produk_id])) {
                $bQty[$row->produk_id] = 0;
            }
            $bQty[$row->produk_id] += $row->valid_qty;
        }

        $mongoList = array();
        $mongUpdateList = array();
        $mongRegID = array();
        if (sizeof($tmpTr) > 0) {
            foreach ($tmpTr as $row) {
                $dataItems = array();
                $where = array(
                    "transaksi_id" => $cancel_packing_source_id,
                    "produk_id" => $row->produk_id,
                );

                $req_cancel_qty_b4 = isset($trCancel['req_cancel_qty'][$row->produk_id]) ? $trCancel['req_cancel_qty'][$row->produk_id] : 0;
                $valid_qty_b4 = isset($trCancel['valid_qty'][$row->produk_id]) ? $trCancel['valid_qty'][$row->produk_id] : 0;
                $cancel_qty_b4 = isset($bQty[$row->produk_id]) ? $bQty[$row->produk_id] : 0;

                cekHijau("req_cancel_qty_b4: " . $req_cancel_qty_b4);
                cekHijau("valid_qty_b4: " . $valid_qty_b4);
                cekHijau("cancel_qty_b4: " . $cancel_qty_b4);

                $req_cancel_qty_af = (int)$req_cancel_qty_b4 - (int)$cancel_qty_b4;
                $cancel_qty_af = (int)$cancel_qty_b4 + (int)$req_cancel_qty_b4;

                if ($valid_qty_b4 > 0) {
                    $dataItems = array(
                        "cancel_qty" => $cancel_qty_af,
                        "req_cancel_qty" => $req_cancel_qty_af,
                    );

                    cekOrange("valid QTY masih ada");

                }
                else {
                    $dataItems = array(
                        "cancel_qty" => $cancel_qty_af,
                        "req_cancel_qty" => $req_cancel_qty_af,
                        "sub_step_number" => '',
                        "next_substep_code" => '',
                    );
                    cekOrange("valid QTY kosong boss, marking sub_step_number");
                }


                $trTrash->setTableName("transaksi_data");
                $trTrash->setFilters(array());

                $updateItems = $trTrash->updateData($where, $dataItems) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  updte  params registries"));
                $mongUpdateList['update']['detail'][] = array(
                    "where" => $where,
                    "value" => $dataItems,
                );
                cekHitam($this->db->last_query());
                cekHere($row->id . " - " . $row->produk_id);
                cekHere("cancel_packing_source_id " . $row->cancel_packing_source_id);
                arrPrint($where);

            }
        }

        //
        //region pre-processors (master)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();

            echo "ITEM NUM LABELS";
            arrPrint($iterator);
            if (sizeof($iterator) > 0) {

                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    echo "master-preproc: $comName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();


                    $subParams = array();
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $subParams['static'][$key] = $realValue;

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr] = $subParams;
                    }


                    $mdlName = "Pre" . ucfirst($comName);
                    $this->load->model("Preprocs/" . $mdlName);
                    $m = new $mdlName($resultParams);


                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                        $tobeExecuted = true;
                    }
                    else {
                        $tobeExecuted = false;
                    }

                    if ($tobeExecuted) {
                        $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $gotParams = $m->exec();

                        cekbiru("gotparams dari $comName");
                        arrprint($gotParams);

                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {
                                if (isset($_SESSION[$cCode]['main'])) {
                                    if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                        foreach ($gSpec as $key => $val) {
                                            cekbiru("injecting param $key with $val");
                                            $_SESSION[$cCode]['main'][$key] = $val;
                                        }
                                    }
                                }
                                //==inject gotParams to child gate
                                if (isset($_SESSION[$cCode]['main'])) {
                                    if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                        foreach ($gSpec as $key => $val) {
                                            $_SESSION[$cCode]['main'][$key] = $val;
                                        }
                                    }
                                }

                            }
                        }
                        else {
                            cekmerah("TIDAK ada gotparam, tidak perlu replace");
                        }

                    }
                    else {
                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                    }

                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }


            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);
        }
        else {
            echo("no processor defined. skipping preprocessor..<br>");
        }

        //endregion


        //
        //region pre-processors (item)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum] : array();
            echo "ITEM NUM LABELS";

            if (sizeof($iterator) > 0) {

                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "sub-preproc: $comName, initializing values <br>";

                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        $tmpOutParams[$cCtr] = array();
                        //                        $id = $dSpec['id'];
                        $id = $xid;
                        $subParams = array();

                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {

                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                $subParams['static'][$key] = $realValue;

                            }

                            if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                                foreach ($paramPatchers[$comName] as $k => $v) {
                                    if (!isset($subParams['static'][$k])) {
                                        $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    }
                                }
                            }
                            if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                                $jenis = $_SESSION[$cCode]['main']['jenis'];
                                foreach ($paramForceFillers[$comName] as $k => $v) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }

                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                        }

                        if (sizeof($subParams) > 0) {

                            $tmpOutParams[$cCtr][] = $subParams;
                        }


                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();

                        echo "sub preproc #$it: $comName, sending values <br>";

                        $mdlName = "Pre" . ucfirst($comName);
                        $this->load->model("Preprocs/" . $mdlName);
                        $m = new $mdlName($resultParams);
                        //cekHitam($mdlName);
                        //arrPrint($tmpOutParams);
                        if (sizeof($tmpOutParams[$cCtr]) > 0) {
                            $tobeExecuted = true;
                        }
                        else {
                            $tobeExecuted = false;
                        }

                        if ($tobeExecuted) {
                            $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();
                            if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor


                                foreach ($gotParams as $gateName => $paramSpec) {

                                    if (!isset($_SESSION[$cCode][$gateName])) {
                                        $_SESSION[$cCode][$gateName] = array();
                                        //                                    cekhijau("building the session: $gateName");
                                    }
                                    else {
                                        //                                    cekhijau("NOT building the session: $gateName");
                                    }

                                    foreach ($paramSpec as $id => $gSpec) {
                                        //                                        $id = $gSpec['id'];

                                        if (!isset($_SESSION[$cCode][$gateName][$id])) {
                                            $_SESSION[$cCode][$gateName][$id] = array();
                                        }

                                        if (isset($_SESSION[$cCode][$gateName][$id])) {
                                            if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                foreach ($gSpec as $key => $val) {
                                                    $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                }

                                            }
                                        }
                                        //==inject gotParams to child gate
                                        if (isset($_SESSION[$cCode][$srcGateName][$id])) {
                                            if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                                foreach ($gSpec as $key => $val) {
                                                    $_SESSION[$cCode][$srcGateName][$id][$key] = $val;
                                                }

                                            }
                                        }

                                        //cekMerah("REBUILDING VALUES..");
                                        if (sizeof($itemNumLabels) > 0) {
                                            //cekHijau("REBUILDING SUBS FOR ITEMS");
                                            foreach ($itemNumLabels as $key => $label) {
                                                //cekHere("$id === $key => $label");
                                                $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                //                                        die();
                                            }
                                        }
                                    }
                                    //                                    arrPrint($_SESSION[$cCode][$gateName]);die();
                                }


                            }

                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }

                    }
                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }


            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);


        }
        else {
            echo("no processor defined. skipping preprocessor..<br>");
        }

        //endregion

        $step = $_SESSION[$cCode]['main']['step_number'];
        $this->load->library("Validator");
        $va = new Validator();
        $va->setConfigUiJenis($this->configUiJenis);
        $va->setCCode($this->cCode);
        $va->midValidate($step);
        $va->unionValidate();


        //region update step2an
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
            echo "authorizing to next step..<br>";
            $nextProp = array(
                "num" => $nextStepNum,
                "code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                "label" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['label'],
                "groupID" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['userGroup'],
            );
        }
        else {//==ini step terakhir, tulis komponen jika ada

            $nextProp = array(
                "num" => 0,
                "code" => "",
                "label" => "",
                "groupID" => "",
            );
        }
        //endregion


        echo "checking components..<br>";

        //==tulis signature
        $dwsign = $tr->writeSignature($masterID, array(
            "nomer" => $tmpNomorNota,
            "step_number" => $stepNum,
            "step_code" => $this->configUi[$origJenis]['steps'][$stepNum]['target'],
            "step_name" => $this->configUi[$origJenis]['steps'][$stepNum]['label'],
            "group_code" => $this->configUi[$origJenis]['steps'][$stepNum]['userGroup'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "keterangan" => $this->configUi[$origJenis]['steps'][$stepNum]['label'] . " oleh " . $this->session->login['nama'],
            "transaksi_id" => $masterID,
        )) or die("Failed to write signature");
        $mongoList['sign'][] = $dwsign;
        //cekKuning(__LINE__. " " .$this->db->last_query());

        //region update step terdahulu
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $topID), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => $topID),
            "value" => array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNum,
            ),
        );
        cekHijau(__LINE__ . " " . $this->db->last_query());


        //        $dupState = $tr->updateData(array("id" => $topID), array(
        //            "next_step_code"  => $nextProp['code'],
        //            "next_step_label" => $nextProp['label'],
        //            "next_group_code" => $nextProp['groupID'],
        //            "next_step_num"   => $nextProp['num'],
        //            "step_current"    => $stepNum,
        //
        //        )) or die("Failed to update tr next-state!");
        //        cekHijau(__LINE__. " " .$this->db->last_query());
        //endregion


        //        arrprint($_SESSION[$cCode]['tableIn_master']);die();
        //==prepare kloningan
        $tCode = $this->configUi[$origJenis]['steps'][$stepNum]['target'];
        $tCodeName = $this->configUi[$origJenis]['steps'][$stepNum]['label'];
        $masterReplacers = array(
            //            "referensi_id" => $masterID, (dimatikan)
            //            "id_master"       => $masterID,
            //            "id_top"          => $topID,
            "inv" => $tmpNomorNota,
            //            "jenis_top"           => $tCode,
            "jenis" => $tCode,
            "jenis_label" => $tCodeName,
            "transaksi_jenis" => $tCode,
            "cabang_id" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangID'] : $this->session->login['cabang_id'],
            "cabang_nama" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangName'] : $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "step_current" => "0",
            "step_number" => $stepNum,
            //            "next_step_code"      => "",
            //            "next_step_label"     => "",
            //            "next_group_code"     => "",
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            //===references
            "id_master" => $masterID,
            "id_top" => $topID,
            "ids_prev" => base64_encode(serialize($prevIDs)),
            "ids_prev_intext" => print_r($prevIDs, true),
            "nomer_top" => $_SESSION[$cCode]['tableIn_master']['nomer_top'],
            "nomers_prev" => base64_encode(serialize($prevNos)),
            "nomers_prev_intext" => print_r($prevNos, true),
            //            "jenis_top"           => $this->jenisTr,
            "jenises_prev" => base64_encode(serialize(array($prevProp['jenis']))),
            "jenises_prev_intext" => print_r(array($prevProp['jenis']), true),
            "tail_number" => $stepNum,
            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $childTableRepaclers = array(
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
            }
        }


        $masterReplacersO = array(

            "jenisTr" => $tCode,
            "jenisTrName" => $tCodeName,
            "olehID" => $this->session->login['id'],
            "olehName" => $this->session->login['nama'],
            "stepNumber" => $stepNum,
            "stepCode" => $tCode,
        );
        foreach ($masterReplacersO as $key => $val) {
            $_SESSION[$cCode]['main'][$key] = $val;
        }

        //region menimbulkan nilai tagihan
        $unpaidList = null != $this->config->item('tr_unpaidList') ? $this->config->item('tr_unpaidList') : array();
        //        arrprint($_SESSION[$cCode]['tableIn_master']);
        if (in_array($tCode, $unpaidList)) {
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_tagihan"] = $_SESSION[$cCode]['tableIn_master']['transaksi_nilai'];
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_terbayar"] = 0;
            $_SESSION[$cCode]['tableIn_master']["transaksi_nilai_sisa"] = ($_SESSION[$cCode]['tableIn_master']['transaksi_nilai_tagihan'] - $_SESSION[$cCode]['tableIn_master']['transaksi_nilai_terbayar']);
            //cekMerah("NULIS TAGIHANN");
        }
        else {
            //cekMerah("TIDAK NULIS TAGIHANN");
        }
        //endregion


        //region penomoran receipt #1

        $this->load->model("CustomCounter");
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);
        $counterForNumber = array($this->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

        foreach ($counterForNumber as $i => $cRawParams) {
            $cParams = explode("|", $cRawParams);
            $cValues = array();
            foreach ($cParams as $param) {
                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
            }
            $cRawValues = implode("|", $cValues[$i]);
            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
        }
        $tmpNomorNota2 = $paramSpec['paramString'];
        $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);

        //endregion

        //region dynamic counters #1
        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $cn->setModul($this->modul);
        $cn->setStepCode($jenisTrTarget);
        $configCustomParams = $this->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                switch ($paramSpec['id']) {
                    case 0: //===counter type is new
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                        break;
                    default: //===counter to be updated
                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                        break;
                }
                //echo "<hr>";
            }
        }
        $appliedCounters2 = base64_encode(serialize($cContent));
        $appliedCounters_inText2 = print_r($cContent, true);


        $masterReplacers = array(
            "nomer" => $tmpNomorNota2,
            "counters" => $appliedCounters2,
            "counters_intext" => $appliedCounters_inText2,
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $addValues = array(
            'counters' => $appliedCounters2,
            'counters_intext' => $appliedCounters_inText2,
            'nomer' => $tmpNomorNota2,
            'dtime' => date("Y-m-d H:i:s"),
            'fulldate' => date("Y-m-d"),
        );
        foreach ($addValues as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        // </editor-fold>
        //endregion

        //region numbering tambahan
        $this->load->library("CounterNumber");
        $ccn = new CounterNumber();
        $ccn->setCCode($this->cCode);
        $ccn->setJenisTr($this->jenisTr);
        $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
        $ccn->setMainGate($_SESSION[$cCode]['main']);
        $ccn->setItemsGate($_SESSION[$cCode]['items']);
        $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
        $new_counter = $ccn->getCounterNumber();
        cekHitam("jenistr yang disett dari create " . $this->jenisTr);

        if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
            foreach ($new_counter['main'] as $ckey => $cval) {
                $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                $_SESSION[$cCode]['main'][$ckey] = $cval;
            }
        }
        if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
            foreach ($new_counter['items'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                }
            }
        }
        if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
            foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                foreach ($iSpec as $iikey => $iival) {
                    $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                }
            }
        }
        //endregion
        //==tulis kloningan transaksi
        //region write entries
        if (sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 0;
            $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
            $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];

            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
            $mongoList['main'] = array($insertID, $epID);

            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }


            if (isset($_SESSION[$cCode]['tableIn_master']['ids_his'])) {
                $idHis_decode = blobDecode($_SESSION[$cCode]['tableIn_master']['ids_his']);
                $idHis_decode[$stepNum] = array(
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;


                cekUngu($idHis_blob);
                cekUngu($idHis_intext);
                arrPrint($idHis_decode);
                arrPrint($_SESSION[$cCode]['tableIn_master']);

                $tr = new MdlTransaksi();
                $dup = $tr->updateData(array("id" => $insertID), array(
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekUngu(__LINE__ . " " . $this->db->last_query());
            }


            //            cekUngu(":: insertID => $insertID ::");
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }


            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                //                cekMerah("ada mainElements $cCode");
                //                arrprint($_SESSION[$cCode]['main_elements']);die();
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? print_r($aSpec['contents_intext'], true) : "",

                    ));
                }
            }
            else {
                //                cekMerah("TAK ada mainElements");
            }

            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        $insertIDs = array();
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        $insertIDs = array();
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                            $insertIDs[] = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                        }
                    }


                }
            }


            //region update validQty pada step sebelumnya yang di-refer
            $seluruhnya = true;
            $prevTrID = 0;
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $iID => $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $insertDetailID;
                    $insertDeIDs[$insertID][] = $insertDetailID;
                    $mongoList['detail'][] = $insertDetailID;
                    if ($epID != 999) {
                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $insertEpID;
                        $insertDeIDs[$epID][] = $insertEpID;
                        $mongoList['detail'][] = $insertEpID;
                    }

                    if (isset($_SESSION[$cCode]['extractedItems'])) {
                        if (array_key_exists($iID, $_SESSION[$cCode]['extractedItems'])) {

                            $itemFulfilledJml = 0;
                            foreach ($_SESSION[$cCode]['extractedItems'][$iID] as $triID => $triSpec) {
                                $prevTrID = $triSpec['transaksi_id'];
                                $tru = new MdlTransaksi();
                                $tru->setFilters(array());
                                $tru->setTableName($tru->getTableNames()['detail']);

                                if ($triSpec['valid_qty'] >= $dSpec['produk_ord_jml']) {
                                    $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                    cekmerah("validQty dikurangi oleh produk_ord_jml, yaitu " . $dSpec['produk_ord_jml']);
                                }
                                else {
                                    $newValidQty = ($triSpec['valid_qty'] - $triSpec['valid_qty']);
                                    cekmerah("validQty dikurangi oleh triSpec,  myaitu " . $triSpec['valid_qty']);
                                }
                                $itemFulfilledJml += $newValidQty;
                                //                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                $updateContents = array(
                                    "valid_qty" => $newValidQty,
                                );
                                if ($newValidQty < 1) {
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                }
                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                    $seluruhnya = false;
                                }
                                $dupState = $tru->updateData(array(
                                    "produk_id" => $iID,
                                    "id" => $triID,
                                    //                            "transaksi_id" => $trID,
                                    "transaksi_id" => $triSpec['transaksi_id'],
                                ), $updateContents) or die("Failed to update previous detail entries!");
                                $mongUpdateList['update']['detail'][] = array(
                                    "where" => array(
                                        "produk_id" => $iID,
                                        "id" => $triID,
                                        //                            "transaksi_id" => $trID,
                                        "transaksi_id" => $triSpec['transaksi_id'],
                                    ),
                                    "value" => $updateContents,
                                );
                                cekHijau(__LINE__ . " " . $this->db->last_query());
                                unset($tru);
                            }
                        }
                    }

                }
                if (sizeof($insertIDs) == 0) {
                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                else {
                    $indexing_details = array();
                    foreach ($insertDeIDs as $key => $numb) {
                        $indexing_details[$key] = $numb;
                    }
                    foreach ($indexing_details as $k => $arrID) {
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }
            }

            if ($seluruhnya) {
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $prevTrID), array(
                    "tail_number" => $stepNum,
                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                    "status_4" => $_SESSION[$cCode]['main']['status_4'],
                    "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                )) or die("Failed to update tr next-state!");
                $mongUpdateList['update']['main'][] = array(
                    "where" => array(
                        "id" => $prevTrID,
                    ),
                    "value" => array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    ),
                );
                cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                cekHijau(__LINE__ . " " . $this->db->last_query());
            }

            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $iID => $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                    cekUngu(__LINE__ . " " . $this->db->last_query());
                }
            }
            //endregion


            if (isset($this->configUi[$this->jenisTr]['updateDueDate'][$stepNum])) {
                $dueDateConf = $this->configUi[$this->jenisTr]['updateDueDate'][$stepNum];
                $sourceDue = $dueDateConf['source'];
                $targetDue = $dueDateConf['target'];
                $datenow = date("Y-m-d");
                foreach ($sourceDue as $key => $val) {
                    $indexVal = isset($_SESSION[$cCode]['main_elements'][$key][$val]) ? $_SESSION[$cCode]['main_elements'][$key][$val] : 14;
                    $dueDate = dueDate($datenow, $indexVal);
                }
                $fieldDue = $tr->getFields()["dueDate"];
                $dataDue = array();
                foreach ($fieldDue as $kol) {
                    if (isset($_SESSION[$cCode]['tableIn_master'][$kol])) {
                        $dataDue[$kol] = $_SESSION[$cCode]['tableIn_master'][$kol];
                    }
                }
                $dataDue['due_date'] = $dueDate;
                $validateDue = validateDueDate($_SESSION[$cCode]['main']['customerID'], $_SESSION[$cCode]['main']['dtime']);

                arrPrint($validateDue);
                if ($validateDue['allow_create'] == "true") {
                    if (isset($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']) && $_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen'] > 0) {
                        cekBiru($_SESSION[$cCode]['main']['nilai_tambah_hutang_ke_konsumen']);

                        $tr->writeDueDate($insertID, $dataDue);
                    }
                }
                else {
                    $allowedOver = validateOverDue($_SESSION[$cCode]['main']['customerID']);
                    if ($allowedOver['status'] == "allowed") {

                    }
                    else {
                        matiHere($validateDue['error']);//matiin transaksi sudah over due
                    }
                    //                    arrPrint()
                    //                    matiHere($validateDue['error']);//matiin transaksi sudah over due
                }
                //                matiHere();
                //update main elementnya
                foreach ($targetDue as $keyTarget => $valTarget) {
                    $_SESSION[$cCode]['main_elements'][$keyTarget][$valTarget] = $dueDate;
                    $_SESSION[$cCode]['main']['dueDate'] = $dueDate;
                }
            }


            $baseRegistries = array(
                'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),

                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNum] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNum] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][$stepNum] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][$stepNum] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][$stepNum] : array(),
                "jurnal_index" => isset($this->configCore[$this->jenisTr]['components'][$stepNum]) ? $this->configCore[$this->jenisTr]['components'][$stepNum] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$stepNum]) ? $this->configCore[$this->jenisTr]['preProcessor'][$stepNum] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$stepNum]) ? $this->configCore[$this->jenisTr]['postProcessor'][$stepNum] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),

            );
            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            $mongRegID = $doWriteReg;
        }
        //endregion


        //region processing sub-post-processors, always
        //<editor-fold desc="----------sub postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, initializing values <br>";
                //                arrPrint($_SESSION[$cCode][$srcGateName]);
                $tmpOutParams[$cCtr] = array();
                foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                    $subParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['loop'][$key] = $realValue;

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['static'][$key] = $realValue;
                            cekBiru("$key diisi dengan $realValue");

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekorange(":: $key diisikan dengan " . $subParams['static'][$k]);
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }

                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr][] = $subParams;
                    }
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";

                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
            }
        }


        //</editor-fold>
        //endregion


        //region processing main-post-processors, always
        //<editor-fold desc="----------postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>" . __LINE__;

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //cekBiru("kiriman komponem $comName");
                //                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }


        //</editor-fold>
        //endregion


        //region ----------subcomponents
        //<editor-fold desc="----------subcomponents">

        //arrPrint($paramForceFillers);
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            $filterNeeded = false;
            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
                $filterNeeded = true;
            }
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-component: $comName, $srcGateName, initializing values <br>";
                $tmpOutParams[$cCtr] = array();
                foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
                    cekmerah("mengevaluasi $srcGateName..");
                    //						$id = $dSpec['id'];
                    $subParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                            $subParams['loop'][$key] = $realValue;
                            cekKuning("LOOP: $key diisi dengan $realValue");

                            if ($filterNeeded) {
                                if ($subParams['loop'][$key] == 0) {
                                    unset($subParams['loop'][$key]);
                                }
                            }
                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                            $subParams['static'][$key] = $realValue;
                            cekKuning("STATIC: $key diisi dengan $realValue");

                        }
                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                    cekOrange("fill :: $comName :: $k => " . $subParams['static'][$k]);
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            //                            cekOrange("comName:: $comName");
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekOrange("fillforce :: $comName :: $k => " . $subParams['static'][$k]);
                            }
                        }
                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    cekHitam("cetak subParams");
                    arrPrint($subParams);
                    if (sizeof($subParams) > 0) {
                        if ($filterNeeded) {
                            if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
                                $tmpOutParams[$cCtr][] = $subParams;
                            }
                        }
                        else {

                            $tmpOutParams[$cCtr][] = $subParams;
                        }
                    }
                }
            }


            $it = 0;
            foreach ($iterator as $cCtr => $tComSpec) {
                $it++;


                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                //                    cekbiru("outparamnya komponen $comName");
                //                    arrprint($tmpOutParams[$cCtr]);
                //                    cekbiru("EO outparamnya komponen $comName");

                echo "sub component #$it: $comName, sending values <br>";

                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();


                if (sizeof($tmpOutParams[$cCtr]) > 0) {
                    $tobeExecuted = true;
                }
                else {
                    $tobeExecuted = false;
                }


                //cekHitam("kiriman sub-component $comName");
                //                    cekMerah($comName . ", tobe-executed: $tobeExecuted");
                //                    arrPri nt($tmpOutParams[$cCtr]);
                if ($tobeExecuted) {
                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                }
            }
        }
        else {
            //cekKuning("subcomponents is not set");
        }


        //</editor-fold>
        //endregion


        //region ----------components
        //<editor-fold desc="----------components">


        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            $it = 0;
            //==filter nilai, jika NOL tidak dikirim, sesuai config==
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            foreach ($iterator as $cCtr => $tComSpec) {
                $it++;
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "component #$it: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;
                        cekHijau(":: NORMAL :: $key => $realValue ::");
                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        cekHijau(":: masuk ke PATCHER ::");
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            cekHijau(":: ada yang mau di-PATCHER ::");
                            arrPrint($tmpOutParams['static']);
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekHijau(":: PATCHER :: $key => $realValue ::");
                            }

                        }
                    }
                    else {
                        cekMerah(":: TIDAK TERMASUK PATCHER ::");
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            cekHijau(":: FORCEFILL :: $key => $realValue ::");
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //===filter value nol, jika harus difilter
                $tobeExecuted = true;

                if (in_array($mdlName, $compValidators)) {

                    $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                    if (sizeof($loopParams) > 0) {
                        foreach ($loopParams as $key => $val) {
                            cekmerah("$comName : $key = $val ");
                            if ($val == 0) {
                                unset($tmpOutParams['loop'][$key]);
                            }
                        }
                    }
                    if (sizeof($tmpOutParams['loop']) < 1) {
                        $tobeExecuted = false;
                    }

                }


                if ($tobeExecuted) {
                    cekBiru("kiriman komponen $comName " . __LINE__);
                    arrPrint($tmpOutParams);
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("komponem $comName tidak memenuhi syarat untuk ditulis");
                }


            }
        }
        else {
            //cekKuning("components is not set");
        }


        //</editor-fold>
        //endregion


        //
        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        $tr->writePaymentSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                            "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                        ));
                    }
                    //cekHitam($valueSrc);
                    //                    cekHitam($_SESSION[$cCode]['main'][$valueSrc]);

                    cekMerah(__LINE__ . " " . $this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }

        //matiHere("hoopppp");
        //cek additional step
        $addPaymentSource = isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService']) ? $this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService'] : array();
        //        arrPrint($addPaymentSource);
        //endregion


        //
        //region nulis paymentAntiSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_antiSource");
        if (array_key_exists($stepCode, $paymentSources)) {
            cekMerah(":: starting PAYMENT ANTI SOURCE");
            $payConfigs = $paymentSources[$stepCode];
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    $tr->writePaymentAntiSrc($insertID, array(
                        "jenis" => $stepCode,
                        "target_jenis" => $paymentSrcConfig['jenisTarget'],
                        "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                        "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                        "nomer" => $tmpNomorNota2,
                        "label" => $paymentSrcConfig['label'],
                        "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                        "terbayar" => 0,
                        "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                        "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                        "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "dtime" => date("Y-m-d H:i:s"),
                        "fulldate" => date("Y-m-d"),
                    ));
                    //cekMerah(__LINE__. " " .$this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }
        //endregion

        validateAllBalances();

        //region connecting antar cabang
        //cekMerah("//cek connecting dari $origJenis========================================");
        $steps = isset($this->configUi[$origJenis]['steps']) ? $this->configUi[$origJenis]['steps'] : array();
        $connector = isset($this->configUi[$origJenis]['connectTo']) ? $this->configUi[$origJenis]['connectTo'] : "";
        $mongoListConnect = array();
        $mongRegIDConnect = array();
        if (strlen($connector) > 0) {
            cekMerah("to be connected to $connector");
            if ($stepNum == sizeof($steps)) {
                cekMerah("now connecting to $connector");
                if (!array_key_exists($connector, $this->configUi)) {
                    die("kode connector tidak dikenali!");
                }
                if (sizeof($this->configUi[$connector]['steps']) < 2) {
                    die("konfigurasi connector harus memiliki step lebih dari satu!");
                }

                $oldCode = $cCode;
                $cCode = "_TR_" . $connector;
                $_SESSION[$cCode] = array();
                $_SESSION[$cCode] = array(
                    "main" => $_SESSION[$oldCode]['main'],
                    "items" => $_SESSION[$oldCode]['items'],

                    "tableIn_master" => $_SESSION[$oldCode]['tableIn_master'],
                    "tableIn_detail" => $_SESSION[$oldCode]['tableIn_detail'],
                    //
                    "rsltItems" => $_SESSION[$oldCode]['rsltItems'],
                    //                    "out_detail_rsltItems" => $_SESSION[$oldCode]['out_detail_rsltItems'],
                    "tableIn_detail_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_rsltItems'],
                    //
                    "tableIn_master_values" => $_SESSION[$oldCode]['tableIn_master_values'],
                    "tableIn_detail_values" => $_SESSION[$oldCode]['tableIn_detail_values'],
                    "tableIn_detail_values_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'],
                );

                //==replace pertama
                $masterReplacersO = array(
                    "jenisTr" => $connector,
                    "jenisTrMaster" => $connector,
                    "jenisTrTop" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                    "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "stepCode" => $this->configUi[$connector]['steps'][1]['target'],
                    "placeID" => $_SESSION[$cCode]['main']['place2ID'],
                    "placeName" => $_SESSION[$cCode]['main']['place2Name'],
                    "place2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "place2Name" => $_SESSION[$cCode]['main']['placeName'],
                    "cabangID" => $_SESSION[$cCode]['main']['place2ID'],
                    "cabangName" => $_SESSION[$cCode]['main']['place2Name'],
                    "cabang2ID" => $_SESSION[$cCode]['main']['placeID'],
                    "cabang2Name" => $_SESSION[$cCode]['main']['placeName'],
                    //
                    "gudang2ID" => $_SESSION[$cCode]['main']['gudangID'],
                    "gudang2Name" => $_SESSION[$cCode]['main']['gudangName'],
                    "gudangID" => $_SESSION[$cCode]['main']['gudang2ID'],
                    "gudangName" => $_SESSION[$cCode]['main']['gudang2Name'],

                );
                foreach ($masterReplacersO as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    //                    $_SESSION[$cCode]['main'][$key] = $val;
                }
                $masterReplacers = array(
                    //                    "referensi_id" => $masterID, (dimatikan)
                    "inv" => $tmpNomorNota,
                    "jenis_master" => $connector,
                    "jenis_top" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                    "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "cabang_id" => $_SESSION[$cCode]['tableIn_master']['cabang2_id'],
                    "cabang_nama" => $_SESSION[$cCode]['tableIn_master']['cabang2_nama'],
                    "cabang2_id" => $_SESSION[$cCode]['tableIn_master']['cabang_id'],
                    "cabang2_nama" => $_SESSION[$cCode]['tableIn_master']['cabang_nama'],
                    "gudang_id" => $_SESSION[$cCode]['tableIn_master']['gudang2_id'],
                    "gudang_nama" => $_SESSION[$cCode]['tableIn_master']['gudang2_nama'],
                    "gudang2_id" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                    "gudang2_nama" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                    "step_avail" => sizeof($this->configUi[$connector]['steps']),
                    "step_current" => 1,
                    "step_number" => 1,
                    "next_step_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['target'] : "",
                    "next_step_label" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['label'] : "",
                    "next_group_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['userGroup'] : "",
                    "next_step_num" => isset($this->configUi[$connector]['steps'][2]) ? 2 : "0",
                    //===references
                    //                    "id_master"            => $masterID,
                    //                    "id_top"               => $topID,
                    //                    "ids_prev"             => base64_encode(serialize(array($prevProp['id']))),
                    //                    "ids_prev_intext"      => print_r(array($prevProp['id'], true)),
                    //                    "nomer_top"            => $_SESSION[$cCode]['main']['nomer'],
                    //                    "nomers_prev"          => base64_encode(serialize(array($prevProp['nomer']))),
                    //                    "nomers_prev_intext"   => print_r(array($prevProp['nomer'], true)),
                    //                    "jenis_top"            => $this->jenisTr,
                    //                    "jenises_prev"        => base64_encode(serialize(array($prevProp['jenis']))),
                    //                    "jenises_prev_intext" => print_r(array($prevProp['jenis'], true)),
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }


                //region penomoran receipt #2
                //<editor-fold desc="==========penomoran">
                $this->load->model("CustomCounter");
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);

                $counterForNumber = array($this->configCore[$connector]['formatNota']);
                if (!in_array($counterForNumber[0], $this->configCore[$connector]['counters'])) {
                    die(__LINE__ . " Used number should be registered in 'counters' config as well");
                }

                foreach ($counterForNumber as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        //                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        //                    echo "filling $param with " . $_SESSION[$cCode]['main'][$param] . "<br>";
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                }

                $tmpNomorNota2 = $paramSpec['paramString'];


                //</editor-fold>
                //endregion

                //region dynamic counters #2
                // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                $cn = new CustomCounter("transaksi");
                $cn->setType("transaksi");
                $cn->setModul($this->modul);
                $cn->setStepCode($jenisTrTarget);
                $configCustomParams = $this->configCore[$connector]['counters'];
                $configCustomParams[] = "stepCode";
                if (sizeof($configCustomParams) > 0) {
                    $cContent = array();
                    foreach ($configCustomParams as $i => $cRawParams) {
                        $cParams = explode("|", $cRawParams);
                        $cValues = array();
                        foreach ($cParams as $param) {
                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                        }
                        $cRawValues = implode("|", $cValues[$i]);
                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                        switch ($paramSpec['id']) {
                            case 0: //===counter type is new
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                                break;
                            default: //===counter to be updated
                                $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                break;
                        }
                        //echo "<hr>";
                    }
                }
                $appliedCounters2 = base64_encode(serialize($cContent));
                $appliedCounters_inText2 = print_r($cContent, true);
                // </editor-fold>
                //endregion

                //region numbering tambahan
                $this->load->library("CounterNumber");
                $ccn = new CounterNumber();
                $ccn->setCCode($cCode);
                $ccn->setJenisTr($connector);
                $ccn->setTransaksiGate($_SESSION[$cCode]['tableIn_master']);
                $ccn->setMainGate($_SESSION[$cCode]['main']);
                $ccn->setItemsGate($_SESSION[$cCode]['items']);
                $ccn->setItems2SumGate($_SESSION[$cCode]['items2_sum']);
                $new_counter = $ccn->getCounterNumber();
                cekHitam("jenistr yang disett dari create " . $this->jenisTr);

                if (isset($new_counter['main']) && sizeof($new_counter['main']) > 0) {
                    foreach ($new_counter['main'] as $ckey => $cval) {
                        $_SESSION[$cCode]['tableIn_master'][$ckey] = $cval;
                        $_SESSION[$cCode]['main'][$ckey] = $cval;
                    }
                }
                if (isset($new_counter['items']) && sizeof($new_counter['items']) > 0) {
                    foreach ($new_counter['items'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                if (isset($new_counter['items2_sum']) && sizeof($new_counter['items2_sum']) > 0) {
                    foreach ($new_counter['items2_sum'] as $ikey => $iSpec) {
                        foreach ($iSpec as $iikey => $iival) {
                            $_SESSION[$cCode]['items2_sum'][$ikey][$iikey] = $iival;
                        }
                    }
                }
                //endregion
                $addValues = array(
                    'counters' => $appliedCounters2,
                    'counters_intext' => $appliedCounters_inText2,
                    'nomer' => $tmpNomorNota,
                    'dtime' => date("Y-m-d H:i:s"),
                    'fulldate' => date("Y-m-d"),
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning nota cab1 ke cab2
                //===daftar perbedaan
                //== referensi_id, inv, jenis, nomer, counters, counters_inText, cabang_id, cabang_nama, cabang2_id, cabang2_nama,

                //==replace kedua
                $masterReplacers = array(
                    "nomer" => $tmpNomorNota2,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

                //===cloning detail/items cabang1 ke cabang2
                //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code
                $detailReplacers = array(
                    "sub_step_avail" => sizeof($this->configUi[$connector]['steps']),
                    "sub_step_current" => 1,
                    "sub_step_number" => 1,
                    "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                    "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                    "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                    "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                    //                    "next_substep_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['target'] : "",
                    //                    "next_substep_label" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['label'] : "",
                    //                    "next_subgroup_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['userGroup'] : "",
                );
                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    //                    cekmerah("tulis rincian transaksi kedua");
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                        foreach ($dSpec as $key => $val) {
                            $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                        }
                    }
                }
                else {
                    //                    cekmerah("GAGAL tulis rincian transaksi kedua");
                }


                //region ----------write transaksi & transaksi_data #2
                if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                    $_SESSION[$cCode]['tableIn_master']['project_id'] = $_SESSION[$cCode]['main']['current_projectID'];
                    $_SESSION[$cCode]['tableIn_master']['project_nama'] = $_SESSION[$cCode]['main']['projectName'];
                    $tr = new MdlTransaksi();
                    $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                    $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                    cekUngu(__LINE__ . " " . $this->db->last_query());
                    $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                    $mongoListConnect['main'] = array($insertID, $epID);
                    $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                    $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                    cekmerah("tulis transaksi kedua :: trID $insertID");
                    cekmerah(__LINE__ . " " . $this->db->last_query());
                    if ($insertID < 1) {
                        die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                }
                else {
                    cekmerah("GAGAL tulis transaksi kedua");
                }
                if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }
                if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                    foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                        $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                        $inserMainValues[] = $dd;
                        $mongoListConnect['mainValues'][] = $dd;
                    }
                }
                if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                    foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                        $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    }
                }
                if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                    //                    cekMerah("ada mainElements");
                    foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                        $tr->writeMainElements($insertID, array(
                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                            "name" => $aSpec['name'],
                            "label" => $aSpec['label'],
                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                        ));
                    }
                }
                else {
                    //                    cekMerah("TAK ada mainElements");
                }
                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $insertDetailID;
                        $mongoListConnect['detail'][] = $insertDetailID;
                        if ($epID != 999) {
                            $insertDetailID = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $insertDetailID;
                            $mongoListConnect['detail'][] = $insertDetailID;
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                    $insertIDs = array();
                    foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                        $insertIDs[] = $insertDetailID;
                        $mongoListConnect['detail'][] = $insertDetailID;
                        if ($epID != 999) {
                            $insertDetailID = $tr->writeDetailEntries($epID, $dSpec);
                            $insertIDs[] = $insertDetailID;
                            $mongoListConnect['detail'][] = $insertDetailID;
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));
                                $insertIDs[] = $dd;
                                $mongoListConnect['detailValues'][] = $dd;

                            }
                        }
                    }
                }
                if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                    foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                        if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                            foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => $dSpec[$src],
                                ));
                                $insertIDs[] = $dd;
                                $mongoListConnect['detailValues'][] = $dd;

                            }
                        }
                    }
                }
                //
                //region nulis paymentSource
                //                $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
                $stepCode = $this->configUi[$connector]['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_source");
                if (array_key_exists($stepCode, $paymentSources)) {

                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                                "valas_id" => isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                                "valas_nama" => isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                                "valas_nilai" => isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                                "tagihan_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                                "terbayar_valas" => 0,
                                "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                            ));
                        }
                    }


                    //cekMerah(__LINE__. " " .$this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion

                //region nulis paymentAntiSource
                //                $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
                $stepCode = $this->configUi[$connector]['steps'][1]['target'];
                $paymentSources = $this->config->item("payment_antiSource");
                if (array_key_exists($stepCode, $paymentSources)) {
                    $payConfigs = $paymentSources[$stepCode];
                    if (sizeof($payConfigs) > 0) {
                        foreach ($payConfigs as $paymentSrcConfig) {
                            //					$paymentSrcConfig = $paymentSources[$stepCode];
                            $valueSrc = $paymentSrcConfig['valueSrc'];
                            $externSrc = $paymentSrcConfig['externSrc'];
                            $tr->writePaymentAntiSrc($insertID, array(
                                "jenis" => $stepCode,
                                "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                "nomer" => $tmpNomorNota2,
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                                "terbayar" => 0,
                                "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                                "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                                "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "dtime" => date("Y-m-d H:i:s"),
                                "fulldate" => date("Y-m-d"),
                            ));
                        }
                    }


                    //cekMerah(__LINE__. " " .$this->db->last_query());

                }
                else {
                    //cekMerah("TIDAK nulis paymentSrc");
                }
                //endregion

                $idHis_decode[$stepNum] = array(
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;

                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "id_master" => $masterID,
                    "id_top" => $insertID,

                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");


                $baseRegistries = array(
                    'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                    'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                    'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                    'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                    'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                    'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                    'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                    'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                    'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                    'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                    'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                    'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                    'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                    'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                    'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                    'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                    'items_noapprove' => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),

                    'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                    'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                    'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),

                    'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                    'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                    'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                    'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                    'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                    'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                    'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                    'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                    'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                    'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                    'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                    'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                    'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                    'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                    "receiptDetailFields" => isset($this->configLayout[$connector]['receiptDetailFields'][1]) ? $this->configLayout[$connector]['receiptDetailFields'][1] : array(),
                    "receiptSumFields" => isset($this->configLayout[$connector]['receiptSumFields'][1]) ? $this->configLayout[$connector]['receiptSumFields'][1] : array(),
                    "receiptDetailFields2" => isset($this->configLayout[$connector]['receiptDetailFields2'][1]) ? $this->configLayout[$connector]['receiptDetailFields2'][1] : array(),
                    "receiptSumFields2" => isset($this->configLayout[$connector]['receiptSumFields2'][1]) ? $this->configLayout[$connector]['receiptSumFields2'][1] : array(),
                    "receiptDetailSrcFields" => isset($this->configLayout[$connector]['receiptDetailSrcFields'][1]) ? $this->configLayout[$connector]['receiptDetailSrcFields'][1] : array(),
                    "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                    "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                    "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                    "jurnal_index" => isset($_SESSION[$cCode]['jurnal_index']) ? $_SESSION[$cCode]['jurnal_index'] : array(),
                    "postProcessor" => isset($_SESSION[$cCode]['postProcessor']) ? $_SESSION[$cCode]['postProcessor'] : array(),
                    "preProcessor" => isset($_SESSION[$cCode]['preProcessor']) ? $_SESSION[$cCode]['preProcessor'] : array(),
                    "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),

                );
                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                $mongRegIDConnect = $doWriteReg;
                //endregion
            }
            else {
                //cekMerah("to be delayed to connect to $connector");
            }
        }
        else {
            //cekKuning("not connecting to any tCode");
        }

        //endregion

        //region nonactive allowed shipment
        $cekvalidateOverDue = validateOverDue($_SESSION[$cCode]['main']['customerID']);
        if ($cekvalidateOverDue['status'] = "allowed") {
            $this->load->model("Mdls/MdlOverDuePass");
            $od = new MdlOverDuePass();
            $where = array(
                "customers_id" => $_SESSION[$cCode]['main']['customerID'],
                "jenis" => "forever",
            );
            $arrUpdate = array(
                "status" => "0",
                "used_byID" => $_SESSION['login']['nama'],
                "used_byNama" => $_SESSION['login']['nama'],
                "used_id" => $insertID,
                "nomor" => $tmpNomorNota,

            );
            $od->updateData($where, $arrUpdate, $od->getTableName());
        }


        //endregion


        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        if ($transaksiID_reference > 0) {

            $this->load->model("Mdls/MdlLockerTransaksi");
            $lt = New MdlLockerTransaksi();
            $lt->execLocker($_SESSION[$cCode]['main'], 0, $transaksiID_reference, NULL);

        }
        //==================================================================================================


        //==tampilkan receipt
        cekOrange("-- DONE --");
        //region writelog
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Line: " . __LINE__ . " - Gagal menulis riwayat data", __FILE__));
        //endregion


        //        cekMerah("minggiiirr");
        //                mati_disini("*** stopp belon comit ***");

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }
        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }


        //region feedback msg
        $this->session->errMsg = "transaction entry has been saved<br>";
        $nextNum = $nextProp["num"];
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextNum])) {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $this->session->errMsg .= "This entry needs to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['userGroup'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewIncomplete/" . $this->jenisTr;

        }
        else {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

        }
        $trBackClick = "location.href='$trBackLink'";
        //        $this->session->errMsg .= "<br><a href='javascript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
        //endregion

        if (isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum])) {
            $printLocation = $this->configLayout[$this->jenisTr]['printLocation'];
            $printSettings = isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum]) ? $this->configLayout[$this->jenisTr]['allowPrint'][$stepNum] : array();
            if (isset($printSettings['size'])) {
                switch ($printSettings['size']) {
                    case "normal":
                        //                        cekkuning("size: NORMAL");
                        echo "<script>";
                        echo "top.popBig('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/$tmpNomorNota2');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    case "small":
                        //                        cekkuning("size: SMALL");
                        echo "<script>";
                        echo "top.popSmall('" . MODUL_PATH . $printLocation . "/" . $this->jenisTr . "/$tmpNomorNota2');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    default:
                        //                        cekkuning("size: UNKNOWN");
                        break;
                }
            }
            else {
                $arrAlert = array(
                    "type" => "success",
                    "title" => "Transaction saved",
                    //                        "html" => "your order has been saved and ready to process",
                    "html" => $this->session->errMsg,
                    "timer" => "1500",
                    "showConfirmButton" => false,
                    "allowOutsideClick" => false,
                );
                echo swalAlert($arrAlert);
                echo "<script>topReload(1500)</script>";
                echo topReload();
                echo "</script>";
                unset($this->session->errMsg);
            }

        }
        else {
            $arrAlert = array(
                "type" => "success",
                "title" => "Transaction saved",
                //                        "html" => "your order has been saved and ready to process",
                "html" => $this->session->errMsg,
                "timer" => "1500",
                "showConfirmButton" => false,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            echo "<script>topReload(1500)</script>";
            echo topReload();
            echo "</script>";
            unset($this->session->errMsg);
        }


    }

    public function showRincian()
    {
//        arrPrint($this->uri->segment_array());
        $modeShow = isset($_GET["mode"]) ? $_GET["mode"] : "nota";
        $this->load->model("Mdls/MdlProdukProject");
        $this->load->model("Mdls/MdlProjectWorkOrder");
        $this->load->model("Mdls/MdlProjectKomposisiWorkorder");
        $trID = $this->uri->segment(5);
        $p = new MdlProdukProject();
        $w = new MdlProjectWorkOrder();
        $k = new MdlProjectKomposisiWorkorder();
        $p->addFilter("transaksi_id='$trID'");
        $tempProduk = $p->lookUpAll()->result();
//        cekLime($this->db->last_query());
//        arrprint($tempProduk);
        $pid = $tempProduk[0]->id;

        $w->addFilter("produk_id='$pid'");
        $tempWo = $w->lookUpAll()->result();
        cekLime($this->db->last_query());
        $womasterData = array();
        foreach ($tempWo as $tempWo_0) {
//            arrPrint($tempWo_0);
            $womasterData[$tempWo_0->id] = $tempWo_0->nama;
        }

        $k->addFilter("produk_id='$pid'");
        $tempKomposisiWo = $k->lookUpKomposisiFase();
        $komposisiHeader = array("jml" => "qty", "nama", "subtotal");
        $detil = array();
        foreach ($tempKomposisiWo as $woID => $woData) {
            if (isset($woData["produk"])) {
                foreach ($woData["produk"] as $produkDatas) {
//                    arrPrint($produkDatas);

//                    $detil[$produkDatas["fase_id"]][$produkDatas["id"]]["harga"]=$produkDatas["harga"];
                    $detil[$produkDatas["fase_id"]][$produkDatas["id"]]["nama"] = $produkDatas["produk_dasar_nama"];
                    $detil[$produkDatas["fase_id"]][$produkDatas["id"]]["jml"] = $produkDatas["jml"];
                    $detil[$produkDatas["fase_id"]][$produkDatas["id"]]["satuan"] = $produkDatas["satuan"];
//                    $detil[$produkDatas["fase_id"]][$produkDatas["id"]]["subtotal"]=$produkDatas["jml"]*$produkDatas["harga"];
                }
            }
        }
//        arrPrint($womasterData);
//        cekLime($this->db->last_query());
//        matiHEre();

//        $tblData = "<div>";
        $tblData = "<table class='table table-responsive table-bordered'>";
        $tblData .= "<tr>";
        $tblData .= "<th>No</th>";
        $tblData .= "<th>Pekerjaan</th>";
        $tblData .= "<th>item</th>";
        $tblData .= "<th>jml</th>";
        $tblData .= "<th>satuan</th>";
        $i = 0;
        foreach ($womasterData as $idWo => $woLabel) {
            $i++;
//            arrprint($woLabel);
            $rowspan = count($detil[$idWo]) + 1;
            $tblData .= "<tr>";
            $tblData .= "<td rowspan='$rowspan'>$i</td>";
            $tblData .= "<td rowspan='$rowspan'>$woLabel</td>";
            $tblData .= "</tr>";

            foreach ($detil[$idWo] as $x => $xData) {
                $tblData .= "<tr>";
                $tblData .= "<td colspan=''>" . $xData["nama"] . "</td>";
                $tblData .= "<td colspan=''>" . $xData["jml"] . "</td>";
                $tblData .= "<td colspan=''>" . $xData["satuan"] . "</td>";
                $tblData .= "</tr>";
            }

//            $tblData .= "</td>";

        }
//        $tblData .="<th>";
        $tblData .= "</tr>";

        $tblData .= "</table>";
//        $tblData .= "</div>";
        if ($modeShow == "show") {
            echo $tblData;
        }
        else {
            return $tblData;
        }

    }


    public function test_tasklist()
    {
        $idTargetProject = 1;
        $upd = $this->doCreteTasklistProject($idTargetProject);

        echo json_encode($upd);
    }
}
