<?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->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->appSetting = $this->config->item("appSetting");
        $this->mongo = isset($this->appSetting['mongo']) ? $this->appSetting['mongo'] : "";

        if ($this->mongo == true) {
            $this->load->model("Mdls/MdlMongoMother");
            $mg = new 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->mongoTableList = $mg->getColection();
        }

        // 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(),
            "divID" => my_div_id(),
            "divName" => my_div_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_he_format($fName, $row->$fName) : formatField_he_format($fName, 0);
                    }

                    if ($fName == "no") {
                        $tmp[$fName] = formatField_he_format($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_he_format($fName, $row->$fName) : formatField_he_format($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='glyphicon glyphicon-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);

    }

    /*followUp I vlidasi*/
    public function followupPrePreview()
    {
        $srcIdTr = $no = rtrim($this->uri->segment(5), "-");
        //        $targetStepNum = $this->uri->segment(4);
        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = url_cleanup(blobEncode(current_url()));

        //
        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        //        $tr->addFilter("step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined()->result();
        cekBiru($this->db->last_query());
        //        arrprint($tr->getFilters());
        //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("transaksi_id in (" . implode(",", explode("-", $cancelPackingId)) . ")");
            $tmpTrCancelPacking = $tr->lookupJoined()->result();
            $id_top_source_cancel_packing = $tmpTrCancelPacking[0]->id_top;
        }

        $signNumbers = array();
        $trs = new MdlTransaksi();
        $trs->setFilters(array());
        $tmpSign = $trs->lookupSignaturesByMasterID($no)->result();
        //        cekKuning($this->db->last_query());
        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) {
            $jenisTr = $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;

            /* -------------------
             * settlement
             * -------------------*/
            $confSettlement = $this->config->item('settlement');
            $warning = "";
            if ($confSettlement['restrictions'] == true) {
                $condites = array(
                    "date(dtime)<" => dtimeNow('Y-m-d'),
                );
                $this->db->where($condites);
                $mySettlementDatas = $trs->callMyTransaksi(my_id(), my_cabang_id());
                // showLast_query("lime");
                $jmlOldTransaksi = sizeof($mySettlementDatas);
                // cekPink($jmlOldTransaksi);

                if ($jmlOldTransaksi > 0) {
                    // cekHitam();

                    $alerts = array(
                        "type" => "error",
                        "title" => "Peringatan!",
                        "html" => "Masih ada setelmen belum diselesaikan, silahkan diselesaikan terlebih dahulu",
                        // "allowOutsideClick" => true,
                        // "allowEscapeKey" => false,
                        // "confirmButtonText" => "Settlement",
                    );

                    $warning = swalAlertSettlement($alerts, $jenisTr);
                }
                echo $warning;
            }
            // -------------------

            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }

            // $stepNumber = isset($_SESSION[$cCode]['tableIn_master']['step_number']) ? $_SESSION[$cCode]['tableIn_master']['step_number'] : 1;
            //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;
            //            $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
            $updatePrice = isset($this->configUi[$this->jenisTr]["updatePrice"][$stepNumber]) ? $this->configUi[$this->jenisTr]["updatePrice"][$stepNumber] : false;                                             //dipake add price pembelian aset
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $regIds = blobDecode($tmpTr[0]->indexing_registry);
            $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("transaksi_id='" . $trID . "'");
            $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
            //            $tr->addFilter("id_master='" . $masterID . "'");
            //            $tr->addFilter("step_number='" . $currentStepNum . "'");
            $tr->addFilter("sub_step_number='" . $currentStepNum . "'");
            $tr->addFilter("next_substep_code='" . $this->configUi[$this->jenisTr]['steps'][$stepNumber]['target'] . "'");
            $tr->addFilter("next_substep_num='$stepNumber'");
            $tr->addFilter("valid_qty>0");

            $tmpTr = $tr->lookupJoined()->result();


            $id_top = isset($tmpTr[0]->id_top) ? $tmpTr[0]->id_top : "";


            //            arrPrint($tmpTr);
            //            cekHere($id_top);
            //            cekHere($no);
            //            matiHere($no);

            $tmpTrPacked = array();
            // dibawa ini dimatikan karena tidak dibutuhkan di teguh
            // dipakai untuk mencari qty dicancel/direturn/dikirimkan

            //            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->addFilter("valid_qty>0");
            //                $tmpTrPacked = $trPack->lookupJoined()->result();
            //            }


            //            mati_disini(implode(",", explode("-", $id_top_source_cancel_packing)));
            $tmpTrPrePacked = array();
            if (sizeof($id_top_source_cancel_packing) > 0) {
                //                mati_disini("ATAS");
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("id_top in (" . implode(",", explode("-", $id_top_source_cancel_packing)) . ")");
                $trPrePack->addFilter("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined()->result();

            }
            else {
                if ($tmpTr[0]->cancel_packing_source_id == "") {
                    //mati_disini("TENGAH");
                }
                else {
                    //mati_disini("BAWAH");
                    $trPrePack = new MdlTransaksi();
                    $trPrePack->setFilters(array());
                    $trPrePack->addFilter("cancel_packing_source_id in (" . implode(",", explode("-", $no)) . ")");
                    $trPrePack->addFilter("valid_qty>0");
                    $trPrePack->addFilter("trash_4<1");
                    $tmpTrPrePacked = $trPrePack->lookupJoined()->result();
                }
            }


            $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;
                }
            }

            //            arrPrint($arrPreTmp__);
            //            matiHere();

            $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 @" . __LINE__);
                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] = array(
                        "id" => $row->id,
                        "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");
            }

            //            arrprint($validItems);


            //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

            //            arrPrint($mainValues);die();


            //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->lookupRegistries()->result();
            //            $tmpReg = $tr->lookupRegistriesByMasterID($masterID)->result();
            //            cekKuning($this->db->last_query());
            //            matiHere();
            $trr->addFilter("trash='0'");
            // $tmpReg = $trr->lookupBaseRegistries($regIds)->result();
            $tmpReg = $tr->lookupDataRegistriesByMasterID($srcIdTr)->row();

            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $items3 = array();
            $items3_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();
            //            $mainApplets = array();
            $mainElements = array();
            $mainInputs = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $param => $row) {
                    switch ($param) {
                        case "main"://
                            $main = $main + unserialize(base64_decode($row));
                            break;
                        case "items"://
                            $items = $items + unserialize(base64_decode($row));
                            break;
                        case "items2"://
                            $items2 = $items2 + unserialize(base64_decode($row));
                            break;
                        case "rsltItems"://
                            $rsltItems = $rsltItems + unserialize(base64_decode($row));
                            break;
                        case "rsltItems2"://
                            $rsltItems2 = $rsltItems2 + unserialize(base64_decode($row));
                            break;
                        case "items2_sum"://
                            $items2_sum = $items2_sum + unserialize(base64_decode($row));
                            break;
                        case "items3"://
                            $items3 = $items3 + unserialize(base64_decode($row));
                            break;
                        case "items3_sum"://
                            $items3_sum = $items3_sum + unserialize(base64_decode($row));
                            break;

                        case "tableIn_master"://
                            $masterTableInParams = $masterTableInParams + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail"://
                            $childTableInParams = $childTableInParams + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_rsltItems"://
                            $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_rsltItems2"://
                            $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($row));
                            break;
                        case "tableIn_master_values"://
                            $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_values"://
                            $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_values_rsltItems"://
                            $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_values_rsltItems2"://
                            $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($row));
                            break;
                        case "main_add_values"://
                            $masterAddValues = $masterAddValues + unserialize(base64_decode($row));
                            break;
                        case "main_add_fields"://
                            $masterAddFields = $masterAddFields + unserialize(base64_decode($row));
                            break;
                        //                        case "main_applets"://
                        //                            $mainApplets = unserialize(base64_decode($row));
                        //                            break;
                        case "main_elements"://
                            $mainElements = unserialize(base64_decode($row));
                            break;
                        case "main_inputs"://
                            $mainInputs = unserialize(base64_decode($row));
                            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']);
                }
            }
            //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();

            //            arrPrintPink($items);
            $itemChildData = array();
            $arrHpp = array();
            if (sizeof($items) > 0) {
                //arrPrint($items);
                //                matiHere();

                $listedItemsIDs = "(";
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $listedItemsIDs .= "'$id',";
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";

                    if (array_key_exists($id, $validItems)) {
                        $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) {
                                    //                                    cekHitam("$heAngka");

                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        cekHitam($newKey);
                                        $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) {
                            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


                    }
                    else {
                        cekUngu(":: masuk sini, UNSET semua ::");
                        unset($items[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);

                    }

                    if (!isset($arrHpp[$xid])) {
                        $arrHpp[$xid] = array();
                    }
                    $arrHpp[$xid] = isset($iSpec) ? $iSpec : array();
                }
                $listedItemsIDs = rtrim($listedItemsIDs, ",");
                $listedItemsIDs .= ")";
                if ($updatePrice) {
                    //                    cekLime(implode(",", $listedItemsIDs));
                    $extenMdl = $this->configUi[$this->jenisTr]["itemPrice"][$stepNumber]['mdlName'];
                    $extenFields = $this->configUi[$this->jenisTr]["itemPrice"][$stepNumber]['fields'];
                    $this->load->model("Mdls/" . $extenMdl);
                    $pr = new $extenMdl();
                    $pr->addFilter("produk_id in $listedItemsIDs");
                    //                    $pr->addFilter("cabang_id='1'");
                    $tmpPrice = $pr->lookUpAll()->result();
                    cekHitam($this->db->last_query());

                    //                    arrPrint($items);
                    //                    matiHere();
                    $externPriceDataTmp = array();

                    if (sizeof($tmpPrice) > 0) {
                        foreach ($tmpPrice as $tmpPrice0) {
                            $externPriceDataTmp[$tmpPrice0->cabang_id][$tmpPrice0->produk_id][$tmpPrice0->jenis_value] = $tmpPrice0->nilai;
                            $externPriceDataTmp[$tmpPrice0->cabang_id][$tmpPrice0->produk_id]['harga_jual_old'] = $tmpPrice0->jenis_value == "jual" ? $tmpPrice0->nilai * 1 : 0;
                        }

                    }
                    else {
                        $this->load->model("Mdls/MdlCabang");
                        $c = new MdlCabang();
                        $tnpC = $c->lookUpAll()->result();
                        $cab = array();
                        foreach ($tnpC as $tmp) {
                            $cab[$tmp->id] = $tmp->nama;
                        }
                        $cab[CB_ID_PUSAT] = "PUSAT";
                        foreach ($cab as $cabang_id => $cabang_nama) {
                            foreach ($validItems as $prod_id => $itemms) {
                                foreach ($extenFields as $field_key => $field_val) {
                                    $externPriceDataTmp[$cabang_id][$prod_id][$field_val] = 0;
                                    $externPriceDataTmp[$cabang_id][$prod_id]['harga_jual_old'] = 0;
                                }
                            }
                        }
                    }

                    // cekBiru($extenFields);
                    // cekHijau($tmpPriceData);
                    $finalItemPrice = array();
                    if (sizeof($externPriceDataTmp) > 0) {
                        foreach ($items as $pidMaster => $tmpDataItems) {
                            foreach ($externPriceDataTmp as $cID => $tmp) {
                                if (isset($tmp[$pidMaster])) {
                                    foreach ($extenFields as $field) {
                                        $valFinal = isset($tmpPriceData[$field]) ? $tmpPriceData[$field] : 0;
                                        if ($pidMaster > 0) {
                                            $finalItemPrice[$cID][$pidMaster][$field] = $valFinal;
                                            $finalItemPrice[$cID][$pidMaster]['harga_jual_old'] = isset($tmpPriceData['jual']) ? $tmpPriceData['jual'] * 1 : 0;
                                        }
                                    }
                                }
                                else {
                                    foreach ($extenFields as $field) {
                                        if ($pidMaster > 0) {
                                            $finalItemPrice[$cID][$pidMaster][$field] = 0;
                                            $finalItemPrice[$cID][$pidMaster]['harga_jual_old'] = 0;
                                        }
                                    }
                                }
                                foreach ($tmp as $pID => $tmpPriceData) {
                                    foreach ($extenFields as $field) {
                                        $valFinal = isset($tmpPriceData[$field]) ? $tmpPriceData[$field] : 0;
                                        if ($pID > 0) {
                                            $finalItemPrice[$cID][$pID][$field] = $valFinal;
                                            $finalItemPrice[$cID][$pID]['harga_jual_old'] = (isset($tmpPriceData['jual']) ? $tmpPriceData['jual'] * 1 : 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $this->load->model("Mdls/MdlHargaJual");
                    $c = new MdlHargaJual();
                    $c->setItems($arrHpp);
                    $tnpC = $c->callHargaJual(array_keys($items));
                    $finalHargaJual = $tnpC;
                }

                //                arrPrintPink($arrHpp);
                //                arrPrintPink(array_keys($items));
                //                arrPrintWebs($finalHargaJual);
                /* ============ HargaJual ============*/

            }

            //                        arrPrintPink($finalHargaJual);
            //            matiHere();

            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "items3" => $items3,
                "items3_sum" => $items3_sum,
                "items_child" => $itemChildData,
                "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,
                //        ""=>$childAddValues ,
                "main_add_fields" => $masterAddFields,
                //                "main_applets"          => $mainApplets,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                //
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "lockerPayment" => $tempBtnUndo,
                "itemPrice" => $finalItemPrice,
                "itemHargaJual" => $finalHargaJual,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;

            }
            //endregion


            //==init replacer

            // mati_disini();
            //==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($this->jenisTr, $this->uri->segment(5), $this->uri->segment(4));
            fillValues_he_value_builder($this->jenisTr, $currentStepNum, $stepNumber, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);

            $mb = New MobileDetect();
            $isMob = $mb->isMobile();
            $mobileSupport = isset($this->configUi[$this->jenisTr]["mobileSupport"]) ? $this->configUi[$this->jenisTr]["mobileSupport"] : false;

            //                        cekhitam($this->db->last_query());
            //cekHitam("line " . __LINE__);
            //$endtime = microtime(true);
            //cekMerah("start: $starttime, end: $endtime :: ");
            //mati_disini($endtime-$starttime);

            if ($isMob && $mobileSupport) { //untuk mobile
                $actionTarget = "top.BootstrapDialog.closeAll();top.BootstrapDialog.show(
                                   {
                                       title:'Followup preview',
                                       message: " . 'top.$' . "('<div></div>').load('" . base_url() . $this->modul . "FollowUp/followupPreviewMb/" . $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,
                                        
                                        
                                        }
                                        );";
            }
            else { //untuk desktop
                $actionTarget = "top.BootstrapDialog.closeAll();top.BootstrapDialog.show(
                                   {
                                       title:'Followup preview',                                       
                                       message: " . 'top.$' . "('<div></div>').load('" . base_url() . $this->modul . "/FollowUp/followupPreview/" . $this->jenisTr . "/$srcIdTr/" . $stepNumber . "/" . $currentStepNum . "?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."));
        }

    }

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

        $masterRevertStep = ($currentStepNum - 1);
        $childRevertStep = -($currentStepNum);

        $rawPrevURL = blobEncode(current_url());
        $rawBuilderURL = isset($_GET['rawBuilderURL']) ? $_GET['rawBuilderURL'] : "";

        $configUiJenis = $this->configUiJenis;

        $doFollowupLink = base_url() . $this->modul . "/" . __CLASS__ . "/doFollowup/" . $this->jenisTr . "/$no/$targetStepNum/$currentStepNum";
        // "targetUrl" => base_url() . $this->uri->segment(1) . "/doRevertAll/$no/$jenisTr/$currentStepNum",
        $doRevertAllLink = base_url() . $this->modul . "/" . __CLASS__ . "/doRevertAll/" . $this->jenisTr . "/$no/$currentStepNum";
        // "targetUrl" => base_url() . $this->uri->segment(1) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
        $doRevertLink = base_url() . $this->modul . "/" . __CLASS__ . "/doRevert/" . $this->jenisTr . "/$no/$masterRevertStep/$childRevertStep/$currentStepNum";

        //region read items from existing model
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        //        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        //        $tr->addFilter("id_top='" . $no . "'");
        //        $tr->addFilter("transaksi_id='" . $no . "'");
        $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        //        $tr->addFilter("id_master='" . $no . "'");
        //        $tr->addFilter("step_number='" . $currentStepNum . "'");
        $tr->addFilter("sub_step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined()->result();
        //        cekKuning($this->db->last_query());die();
        //endregion


        $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");
        }


        $rawItems = array();
        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;

            $pelaku = $tmpTr[0]->oleh_id;

            $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();
            $itemLabels = isset($this->configUi[$this->jenisTr]['shoppingCartFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartFields'][$targetStepNum] : array();
            $itemLabels2 = isset($this->configUi[$this->jenisTr]['shoppingCartFields2'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartFields2'][$targetStepNum] : array();
            $itemLabels3 = isset($this->configUi[$this->jenisTr]['shoppingCartFields3'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartFields3'][$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();

            $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);

            $kolomPilihans = array(
                "indexing_registry"
            );
            $this->db->select($kolomPilihans);
            $tmpRg = $trs->lookupByID($masterID)->result();
            // arrPrint($masterID);
            $regIds = blobDecode($tmpRg[0]->indexing_registry);
            // arrPrint();

            //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

            //            arrPrint($mainValues);die();

            //region take from registries
            //==ambil value-gate
            //            $tmpReg = $tr->lookupRegistriesByMasterID($trID)->result();
            $tr->setFilters(array());
            $tr->addFilter("trash='0'");
            // $tmpReg = $tr->lookupRegistriesByMasterID($masterID)->result();
            // $tmpReg = $tr->lookupBaseRegistries($regIds)->result();
            $tmpReg = $tr->lookupDataRegistriesByMasterID($masterID)->row();
            // cekKuning($this->db->last_query());

            $main = array();
            $items = array();
            $masterGates = array();
            $childGates = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $masterAddValues = array();
            $masterAddFields = array();
            //            $mainApplets = array();
            $mainElements = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $param => $row) {
                    switch ($param) {
                        case "main"://
                            $main = unserialize(base64_decode($row));
                            break;
                        case "items"://
                            $items = unserialize(base64_decode($row));
                            break;
                        case "items2"://
                            $items2 = unserialize(base64_decode($row));
                            break;
                        case "items2_sum"://
                            $items2_sum = unserialize(base64_decode($row));
                            break;

                        case "tableIn_master"://
                            $masterTableInParams = unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail"://
                            $childTableInParams = unserialize(base64_decode($row));
                            break;
                        case "tableIn_master_values"://
                            $masterTableInValueParams = unserialize(base64_decode($row));
                            break;
                        case "tableIn_detail_values"://
                            $childTableInValueParams = unserialize(base64_decode($row));
                            break;
                        case "main_add_values"://
                            $masterAddValues = unserialize(base64_decode($row));
                            break;
                        case "main_add_fields"://
                            $masterAddFields = unserialize(base64_decode($row));
                            break;
                        //                        case "main_applets"://
                        //                            $mainApplets = unserialize(base64_decode($row));
                        //                            break;
                        case "main_elements"://
                            $mainElements = unserialize(base64_decode($row));
                            break;
                    }
                }
            }
            else {
                die("Cannot read the registry entries from $masterID!");
            }
            //endregion

            $arrTest = array();
            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;
                            }
                            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;


            }

        }
        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
        $jenisTr = $this->jenisTr;

        /* --------------------------------------
         * settlement
         * --------------------------------------*/
        $confSettlement = $this->config->item('settlement');
        $warning = "";
        if ($confSettlement['restrictions'] == true) {
            $condites = array(
                "date(dtime)<" => dtimeNow('Y-m-d'),
            );
            $this->db->where($condites);
            $mySettlementDatas = $trs->callMyTransaksi(my_id(), my_cabang_id());
            // showLast_query("lime");
            $jmlOldTransaksi = sizeof($mySettlementDatas);
            // cekPink($jmlOldTransaksi);

            if ($jmlOldTransaksi > 0) {
                // cekHitam();

                $alerts = array(
                    "type" => "error",
                    "title" => "Peringatan!",
                    "html" => "Masih ada setelmen belum diselesaikan, silahkan diselesaikan terlebih dahulu",
                    // "allowOutsideClick" => true,
                    // "allowEscapeKey" => false,
                    // "confirmButtonText" => "Settlement",
                );

                $warning = swalAlertSettlement($alerts, $jenisTr);
            }
            echo $warning;
        }
        // -----------end off settlement--------

        $items = array();
        $items2 = array();
        $_SESSION[$cCode]['main']['currentID'] = $no;

        //region deteksi tombol2 followup


        $currentStepIndex = array_search($currentStepNum, $signNumbers, true);


        //region blocking edit/reject delete jika ada payment source dari pembelian non credit
        //        if (isset($_SESSION[$cCode]['lockerPayment']) && $_SESSION[$cCode]['lockerPayment'] == true) {
        //
        //        }


        //endregion

        //region ========================approve, reject, undo====================================
        $origTCode = heGetOriginTCode($this->jenisTr);
        $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : 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;

        $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",
            "targetUrl" => "",
            "warning" => "",
        );
        $approvalSpec = array(
            "label" => "cannot approve",
            "targetUrl" => "",
            "warning" => "",
        );
        $editSpec = array(
            "label" => "cannot edit",
            "targetUrl" => "",
            "warning" => "",
        );

        $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
        $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
        $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);

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

        //==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->configUi[$this->jenisTr])) {//$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->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    else {
                    }
                }
                else {
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    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 . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    else {
                        cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                if ($evPre == null && $evPost == null && $evCom == null) {
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $deleteSpec = array(
                        "label" => "safely delete",
                        "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "DELETING this entry will destroy all of its details and can not be undone. continue?",
                    );
                }
                //                }
            }
        }
        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->configUi[$this->jenisTr])) {
            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->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject",
                            "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    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 . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing UNDO will set this entry one step behind. continue?",
                        );
                    }
                }
            }
            else {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                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 . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "pressing UNDO will set this entry one step behind. continue?",
                    );
                }
                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->configUi[$this->jenisTr])) {//$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->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject",
                            "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    else {
                        cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                    }
                }
                else {
                    cekungu("bukan credit");
                    $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                    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",
                            "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    else {
                        cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                    }
                }
            }
            else {
                //                if (!isset($_SESSION[$cCode]['main']['paymentMethod'])) {
//                cekHijau("ready to reject");
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                if ($evPre == null && $evPost == null && $evCom == null) {
                    // cekhijau("allowed to REJECT || LINE: " . __LINE__);
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $rejectionSpec = array(
                        "label" => "reject",
                        "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                        "warning" => "pressing REJECT will set this entry one step behind. continue?",
                    );
                }
                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->configUi[$this->jenisTr])) {
            $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
            $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
            $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
            $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);

            if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                //                cekhijau("allowed to EDIT");
                $editSpec = array(
                    "label" => "edit",
                    "targetUrl" => MODUL_PATH . get_class($this) . "/doPreEdit/$no/$jenisTr/$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->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evPost = evaluatePostProcessors_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evCom = evaluateComponents_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                $evMaster = evaluateMain_he_menu($this->jenisTr, $currentStepNum, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr]);
                if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                    cekhijau("allowed to EDIT");
                    $editSpec = array(
                        "label" => "edit",
                        "targetUrl" => MODUL_PATH . get_class($this) . "/doPreEdit/$no/$jenisTr/$currentStepNum",
                        "warning" => "pressing EDIT will modify entire transaction data. continue?",
                    );
                }
                else {
                    // cekmerah("NOT allowed to EDIT");
                }
            }
        }

        //==approve
        if ($targetStepNum > $currentStepNum) {
            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]['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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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->configUi[$this->jenisTr])) {
                            //                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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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->configUi[$this->jenisTr])) {
                        $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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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" => $doFollowupLink,
                                "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->configUi[$this->jenisTr])) {
                        //                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?",
                                    );
                                    $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]['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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$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 . get_class($this) . "/doFollowup/$no/$targetStepNum/$currentStepNum",
                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                            );
                            if ($hideFollowUp) {
                                $approvalSpec = array();
                            }
                        }
                    }
                    else {
                    }
                }
            }
        }
        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($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum)) {
                //                if (in_array($this->configUi[$jenisTr]['steps'][$currentStepNum]['userGroup'], $this->session->login['membership'])) {
                $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 = $masterRevertStep . "undo " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
                        $revertLabel = "undo";
                        $childRevertStep = -($currentStepNum);
                        $revertTarget = MODUL_PATH . get_class($this) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum";

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

            }
            //            }
        }
        //endregion

        //region check if i may approve or unapprove current transaction

        if (isset($this->configUi[$jenisTr]['steps'][$targetStepNum])) {
            if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum)) {
                //            if (in_array($this->configUi[$jenisTr]['steps'][$targetStepNum]['userGroup'], $this->session->login['membership'])) {
                $allowFollowup = true;
                $buttonLabel = $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'];
                $acceptTarget = MODUL_PATH . get_class($this) . "/doFollowup/$no/$targetStepNum/$currentStepNum";

                //                echo $masterRevertStep;
                if (isset($masterRevertStep)) {


                    $mPreProcs = heCountPreProcs($this->jenisTr, $currentStepNum);
                    $mPostProcs = heCountPostProcs($this->jenisTr, $currentStepNum);
                    $mComs = heCountComponents($this->jenisTr, $currentStepNum);

                    //                    arrprint($mPreProcs);
                    //                    arrprint($mPostProcs);

                    //==set default to ENABLED
                    $childRevertStep = -($currentStepNum);
                    $rejectionLabel = "reject (def)";
                    $rejectionTarget = MODUL_PATH . get_class($this) . "/dontFollowup/$no/$jenisTr/$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) {
                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, "}");
                                $rek = str_replace($rek, $_SESSION[$cCode]['main'][$rek], $rek);
                            }
                            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");
        $va = new Validator();
        $va->setCCode($this->cCode);
        $va->setConfigUiJenis($this->configUiJenis);

        $msgWarning = $va->validate2();
        // matiDisini();
        //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)",
            "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();
        $addRowsConfigs = isset($this->configUi[$this->jenisTr]['additionalRows']) ? $this->configUi[$this->jenisTr]['additionalRows'] : array();
        //            $appletConfigs = isset($this->configUi[$this->jenisTr]['applets']) ? $this->configUi[$this->jenisTr]['applets'] : 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);
                        //                        $realFilter = "";
                        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='glyphicon glyphicon-plus'></span></a>";
                            }
                        }
                        //                        if (strlen($realFilter) > 0) {
                        //                            $oo->addFilter($realFilter);
                        //                        }
                        $tmpo = $oo->lookupAll()->result();
                        $elPair[$amdlName] = array();
                        $selectorTarget = base_url() . 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='glyphicon glyphicon-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 = "'" . base_url() . 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) {
            foreach ($xShipmentConfig as $num => $val) {
                $xShipmentBtn_str = array(
                    "label" => "close/fullfillment transaksi",
                    "targetUrl" => MODUL_PATH . get_class($this) . "/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
        //        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 (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;
                        }
                        //                    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 = "'" . base_url() . get_class($this) . "/recordAddRow/" . $this->jenisTr . "/$oValueName/?val='+this.value+'&ravPrev=$rawPrevURL&rawBuilderURL=$rawBuilderURL'";
                                        $relInputTarget = "'" . base_url() . "_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 = "'" . base_url() . get_class($this) . "/fetchElement/" . $this->jenisTr . "/$eName/$amdlName/?key='+encodeURI(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);document.getElementById('result').src =$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);document.getElementById('result').src =$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='glyphicon glyphicon-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 = "'" . base_url() . get_class($this) . "/recordFieldElement/" . $this->jenisTr . "/$eName/$amdlName/?val='+encodeURI(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'])) {
                                    $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();
        $updatePriceLabel = isset($this->configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["fieldsLabel"]) ? $this->configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["fieldsLabel"] : array();
        $updatePriceEditable = isset($this->configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["editableFields"]) ? $this->configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["editableFields"] : array();

        $branchData = array();
        if (sizeof($updatePriceLabel) > 0) {
            $this->load->model("Mdls/MdlCabang");
            $c = new MdlCabang();
            $tempC = $c->lookUpAll()->result();
            if (sizeof($tempC) > 0) {
                foreach ($tempC as $tempC0) {
                    $branchData["harga"][$tempC0->id] = array(
                        "label" => $tempC0->nama,
                    );
                }
            }
            //            arrPrint($branchData);

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


        // arrPrint($addMainSource);
        //endregion

        //        arrPrint($mainElements['detilSize']['key']);
        $detilSizeBar = array();
        $measureConf = isset($this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartMeasurement'][$targetStepNum] : false;
        //        cekHere($currentStepNum);
        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,
                );
            }
        }

        // cekOrange();
        // arrPrint($itemLabels);
        $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "sub-amount");
        $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "sub-amount");
        $itemLabels3 = $itemLabels3 + $itemNumLabels3 + array("subtotal" => "sub-amount");
        // if (isset($this->configUi[$this->jenisTr]['shoppingCartHideSubamount'])) {
        if (isset($this->configUi[$this->jenisTr]['shoppingCartHideSubamount'][$targetStepNum]) && $this->configUi[$this->jenisTr]['shoppingCartHideSubamount'][$targetStepNum] == true) {
            //     if($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";

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

        $definitionButton = definitionButton();

        // arrPrint($_SESSION[$cCode][$pairedItemTarget]);


        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

        $data = array(
            "mode" => "followupPreview",
            "template" => $this->configUi[$jenisTr]["template"],
            "title" => $this->configUi[$jenisTr]["label"],
            "subTitle" => $this->configUi[$jenisTr]["steps"][1]['label'],
            "configUi" => $this->configUi,
            "jenisTr" => $jenisTr,
            "pihakLabel" => $this->configUi[$jenisTr]["pihakLabel"],
            "mainLabels" => isset($this->configLayout[$jenisTr]["receiptMainFields"]) ? $this->configLayout[$jenisTr]["receiptMainFields"] : null,
            "main" => $mainProp,
            "mainValues" => $_SESSION[$cCode]['main'],
            "detailValues" => $_SESSION[$cCode]['tableIn_detail_values'],
            "itemLabels" => $itemLabels,
            "itemLabels2" => $itemLabels2,
            "itemLabels3" => $itemLabels3,
            "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'] : array(),
            "items_child" => isset($_SESSION[$cCode]['items_child']) ? $_SESSION[$cCode]['items_child'] : array(),
            "itemsChildLabel" => $itemsChildLabel,
            "itemsChildLabelEditable" => $itemsChildEditable,
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            // "sumRows"                 => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum] : $this->configLayout[$this->jenisTr]['receiptSumFields'][$targetStepNum],
            "sumRows" => isset($this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartSumFields'][$targetStepNum] : null,
            "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" => 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(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            //            "actionTarget" => base_url() . $this->uri->segment(1) . "/doFollowup/$no/$targetStepNum",
            "actionTarget" => MODUL_PATH . get_class($this) . "/doFollowup/$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($main['description']) ? $main['description'] : "",
            "description" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            /*-----
            TAMBAHAN RULE UNTUK TABAHAN REFERENSI SAAT PENERIMAAN
            ---------------------------------*/
            "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(),
            "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) . "/",
//            "updateItemFieldTarget" => MODUL_PATH . "$itemsEditableConfig" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "updateItemFieldTarget" => MODUL_PATH . "$itemsEditableConfig" . $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) . "/",
            "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),
            "followupPreviewTarget" => MODUL_PATH . "/FollowUp/followupPreview/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7),
            "updateItemPriceTarget" => MODUL_PATH . "_followupLiveEdit/updatePrice/" . $this->jenisTr . "/" . $this->uri->segment(5) . "/" . $this->uri->segment(6) . "/" . $this->uri->segment(7) . "/",
            "msgWarning" => isset($msgWarning) ? $msgWarning : array(),
            // --
            "msgWarning2" => isset($msgWarning2) ? $msgWarning2 : array(),
            //
            "addRows" => $addRows,
            "addRowLabels" => $addRowLabels,
            "deleteSpec" => $deleteSpec,
            "undoSpec" => $undoSpec,
            "rejectionSpec" => $rejectionSpec,
            "rejectionSpecAll" => isset($rejectionSpecAll) ? $rejectionSpecAll : array(),
            "approvalSpec" => $approvalSpec,
            "editSpec" => $editSpec,
            "detailSizeKey" => $detailSizeKey,
            "detilSizeBar" => $detilSizeBar,
            "addMainSource" => $addMainSource,
            "addMainSourceField" => $addMainSourceField,
            "addMainSourceEdit" => $addMainSourceEdit,
            "definitionButton" => $definitionButton,
            // "dpData"              => $dpData,
            // //--------------------------
            // "beforeStepLabels"    => $beforeStepLabels,
            // "beforeAllStepLabels" => $beforeAllStepLabels,
            // "beforeStepWarning"   => $beforeStepWarning,
            //
            // "itemsKompositID" => $itemsKompositID,
            "allowSubTambah" => isset($configUiJenis['steps'][$targetStepNum]['allowSubTambah']) ? $configUiJenis['steps'][$targetStepNum]['allowSubTambah'] : true,
            "allowSubRemove" => isset($configUiJenis['steps'][$targetStepNum]['allowSubRemove']) ? $configUiJenis['steps'][$targetStepNum]['allowSubRemove'] : true,
            "itemPriceLabel" => $updatePriceLabel,
            "itemPriceLabel2" => $branchData,
            "itemPriceEditable" => $updatePriceEditable,
            "itemPrice" => isset($_SESSION[$cCode]['itemPrice']) ? $_SESSION[$cCode]['itemPrice'] : array(),
            "itemHargaJual" => isset($_SESSION[$cCode]['itemHargaJual']) ? $_SESSION[$cCode]['itemHargaJual'] : array(),
            "print_barcode" => isset($_SESSION[$cCode]['main']['print_barcode']) ? $_SESSION[$cCode]['main']['print_barcode'] : "",
            "link_to_clear_custom_print" => MODUL_PATH . "/_followupLiveEdit/removePrintBarcode/" . $this->jenisTr . "/$srcIdTr/$targetStepNum/$currentStepNum",
//            "updateItemPriceTarget" => "",
        );

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

    }

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

    public function doFollowup()
    {
        $ipadd = $_SERVER['REMOTE_ADDR'];
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $gmr = img_working();
        echo lgWait("Harap menunggu ...., <br>Transaksi sedang diproses <br>halaman akan refresh setelah proses selesai<br>Sangat tergantung seberapa banyak data yang diproses <img src='$gmr'>");
        // die();
        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);


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

        $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
        $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();
        $coreRequiredParam = isset($this->config->item('heTransaksi_core')[$this->modul]['requiredParam']) ? $this->config->item('heTransaksi_core')[$this->modul]['requiredParam'] : array();
//        $corePreProcParam = isset($this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor']) ? $this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor'] : false;
        $corePreProcParam = isset($this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor']) ? $this->config->item('heTransaksi_core')[$this->modul]['requiredParam'][$this->jenisTr]['preProcessor'] : array();
        $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["runCoreAkunting"] : false;

        $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
        $stepNowParameter = array();
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("transaksi.step_number='" . $stepNumCurrent . "'");
        $tr->addFilterJoin("transaksi_data.trash='0'");
        $tmpTr = $tr->lookupJoined()->result();
        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();
            $additionalDataPriceConf = isset($this->configUi[$this->jenisTr]["updatePrice"][$stepNum]) ? $this->configUi[$this->jenisTr]["updatePrice"][$stepNum] : false;

            $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>";
                        //                            $tmp[$key]=isset($iSpec[$val])?$iSpec[$val]:0;
                        if (isset($detailValues[$row->produk_id][$key])) {
                            //                            $tmp[$key] = formatField_he_format($key, $detailValues[$row->produk_id][$key]);
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                //                                $tmp[$key] = formatField_he_format($key, $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->configValues[$this->jenisTr]['externalValues']) && sizeof($this->configValues[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configValues[$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
        if ($runCoreAkunting == true) {

            $buildTablesMaster = isset($core['components']['master']) ? $core['components']['master'] : array();
            $buildTablesDetail = isset($core['components']['detail']) ? $core['components']['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 (isset($itemSpec[$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

        /* ------------------------------
         * TRANSAKSIONAL TERJADI DI DALAM SINI
         * $dieForDebug = false; --------> kondisi normal transaksi bisa lanjot
         * untuk mematikan transksi di jadikan true
         * ------------------------*/
        $dieForDebug = false;
//        $dieForDebug = true;
//        cekBiru("ipnya sini ".$ipadd);
        // matiDisini(__LINE__);
        if ($ipadd == "202.65.117.72") {
            $dieForDebug = true;
            cekHitam("$ipadd == 202.65.117.72 " . __METHOD__ . " dimatikan sebelum comit");
        }

        //region PROSES TRANSAKSIONAL

        $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...");
        // PRE-PROCESSOR
//        if ($runCoreAkunting == true) {

        //region pre-processors (item)
        if (isset($core['preProcessor'][$jenisTrTarget]['detail'])) {
            $iterator = isset($core['preProcessor'][$jenisTrTarget]['detail']) ? $core['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'];
//                        if (isset($corePreProcParam[$comName]) && ($corePreProcParam[$comName] == true)) {

                    $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($core['preProcessor'][$jenisTrTarget]['master'])) {
            $iterator = isset($core['preProcessor'][$jenisTrTarget]['master']) ? $core['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'];
//                        if (isset($corePreProcParam[$comName]) && ($corePreProcParam[$comName] == true)) {

                    $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

//        }


//mati_disini(__LINE__);


        //region pre-proc value injector items2 items2_sum dari gerbang main
        $injectValues = isset($core['preInjectValue'][$stepNum]) ? $core['preInjectValue'][$stepNum] : array();
        if (sizeof($injectValues) > 0) {
            $iterator = isset($core['preInjectValue'][$stepNum]['master']) ? $core['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


        $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();

        //==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" => isset($_SESSION[$cCode]['tableIn_master']['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;
            }
        }

        //        arrprint($_SESSION[$cCode]['tableIn_detail']);die();
        $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");

        $counterForNumber = array($this->configValues[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configValues[$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");
        $configCustomParams = $this->configValues[$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


        //==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;


            $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,
                    "counters" => $appliedCounters2,
                    // "counters_intext" => $appliedCounters_inText2,
                );
                // arrPrintWebs($idHis_decode_2);
                $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']);
                cekBiru($idHis_blob);
                $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->configValues[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configValues[$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->configValues[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        foreach ($this->configValues[$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->configValues[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configValues[$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
            $seluruhnya = true;
            $prevTrID = 0;
            $arrvalidQtySisa = array();
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $closedRequest = isset($this->configValues[$origJenis]['closedRequest'][$stepNum]['enabled']) ? $this->configValues[$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>";


                    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']);
                                }
                                //----------------------------------------------------------
                                $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']);

                                    }
                                    //                                    else{
                                    //                                        $newValidQty = 0;
                                    //                                        $newValidQtyNotApprove = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                    //                                    }
                                    cekPink2("new valid qty: $newValidQty, valid qty not approve: $newValidQtyNotApprove");
                                }
                                //----------------------------------------------------------


                                $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;
                                    $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']['detail'][] = array(
                                    "where" => array(
                                        //                                        "transaksi_id" => $triSpec['transaksi_id'],
                                        "id" => "$triID",
                                        //                                        "produk_id" => $iID,
                                    ),
                                    "value" => $updateContents,
                                );
                                unset($tru);
                            }
                        }
                        //                        else{
                        //                            if($closedRequest == true){
                        //
                        //                            }
                        //                        }
                    }
                }

                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

            //region updater price
            if ($additionalDataPriceConf) {
                if (isset($_SESSION[$cCode]['itemPrice']) && sizeof($_SESSION[$cCode]['itemPrice']) > 0) {
                    $dComsName = isset($this->configUi[$this->jenisTr]["itemPrice"][$stepNum]['DComs']) ? $this->configUi[$this->jenisTr]["itemPrice"][$stepNum]['DComs'] : "";
                    $replacerFields = isset($this->configUi[$this->jenisTr]["itemPrice"][$stepNum]['fieldReplacer']) ? $this->configUi[$this->jenisTr]["itemPrice"][$stepNum]['fieldReplacer'] : array();
                    //                    cekLime("before");
                    //
                    //                    arrPrint($_SESSION[$cCode]['itemPrice']);

                    if (sizeof($replacerFields) > 0) {
                        foreach ($_SESSION[$cCode]['itemPrice'] as $Cid => $cData) {
                            foreach ($cData as $pID => $tmpField) {
                                foreach ($tmpField as $field => $value) {
                                    if (isset($replacerFields[$field])) {
                                        $source = $replacerFields[$field];
                                        $valReplacer = $_SESSION[$cCode]['items'][$pID][$source];
                                        cekLime("replace $field $value => $valReplacer");
                                        $_SESSION[$cCode]['itemPrice'][$Cid][$pID][$field] = $valReplacer;
                                    }
                                }

                                //arrPrint($tmpField);
                            }
                        }
                    }

                    $this->load->model("DComs/" . $dComsName);
                    echo "sub-postProcessor: $dComsName, sending values <br>";
                    $d = new $dComsName();

                    $d->pair($_SESSION[$cCode]['itemPrice']) or die("Tidak berhasil memasang  values pada dcoms-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $d->exec() or die("Gagal saat berusaha  exec values pada DComs: $dComsName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
            }


            //matiHEre($stepNum);
            //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());
                }
            }


            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($core['components']) ? $core['components'] : array(),
                "preProcessor" => isset($core['preProcessor'][$jenisTrTarget]) ? $core['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configValues[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configValues[$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(),
                "requiredParam" => (isset($coreRequiredParam[$this->jenisTr]) && sizeof($coreRequiredParam[$this->jenisTr]) > 0) ? $coreRequiredParam[$this->jenisTr] : array(),
            );
//arrPrintPink($baseRegistries);
            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            $mongRegID = $doWriteReg;
            echo "<script>top.writeProgress('MENULIS KE-REGISTRY....');</script>";
        }
        else {
            die(lgShowAlert("Transaksi gagal disimpan, silahkan cek kembali transaksi ini."));
        }
        //endregion

        // POST-PROCESSOR
//        if ($runCoreAkunting == true) {

        //region processing sub-post-processors, always
//            $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        $iterator = isset($this->configValues[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configValues[$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();
                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;
                    }
                }
            }

            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__);
                showLast_query("lime");
            }
        }


        //</editor-fold>
        //endregion

        //region processing main-post-processors, always
//            $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        $iterator = isset($this->configValues[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configValues[$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";
                            }
                        }
                    }
                    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__);


            }
        }
        //endregion

//        }

        // COMPONENT
        if ($runCoreAkunting == true) {
            //region ----------subcomponents GESER KE CLI
            //        $componentGate['detail'] = array();
            $iterator = isset($core['components']['detail']) ? $core['components']['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
            $componentGate['master'] = array();
            $componentConfig['master'] = array();
            if (isset($core['relativeComponets']) && $core['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($core['components']['master'])) {
                    $iterator = $core['components']['master'];
                }
                else {
                    $iterator = array();
                }
            }
//cekHitam(":: $runCoreAkunting :: $transaksiMode ::");
//arrPrintPink($core);
//arrPrintWebs($iterator);
//mati_disini();
            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']] : "",
                            "extern_nilai5" => (isset($externSrc['extern_nilai5']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai5']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai5']] : "",
                            "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"),
                        "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']] : "",
                    ));
                    cekMerah($this->db->last_query());
                }
            }

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

        //region nulis uangMukaSource
        /*dimatiin geser ke ComUangmukaSourceDetail karena ada di items
         *
         */
        //        $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) {
        //                foreach ($uangMukaConfigs as $uangMukaSrcConfig) {
        //                    //					$paymentSrcConfig = $paymentSources[$stepCode];
        //                    arrPrint($uangMukaSrcConfig);
        //                    $valueSrc = $uangMukaSrcConfig['valueSrc'];
        //                    $externSrc = $uangMukaSrcConfig['externSrc'];
        //                    $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" => $tmpNomorNota2,
        //                        "note" => htmlspecialchars($_SESSION[$cCode]['items'][1]['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"),
        //                    ));
        //                    cekMerah($this->db->last_query());
        //                }
        //            }
        //            else {
        //                cekLime("not write uang muka");
        //            }
        //
        //        }
        //        else {
        //            cekMerah("not write uang muka");
        //        }
        //endregion
        // arrPrintWebs($componentConfig);
//        validateBalancesComparison("", $componentConfig);
        validateJurnal($insertID, $componentConfig);
        validateAllBalances();
        //
        //region connecting antar cabang
        $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();


        if (strlen($connector) > 0) {
            cekMerah("to be connected to $connector |$stepNum|" . sizeof($steps));

            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
            }

            if ($stepNum == sizeof($steps)) {
                cekMerah("NOW CONNECTING to $connector");
                //----------------
                $configUiMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiUi");
                $configCoreMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiCore");
                $configLayoutMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiLayout");
                $configValuesMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiValues");

                //----------------
//                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!");
//                }
                if (sizeof($configUiMasterModulJenis) == 0) {
                    die("kode connector tidak dikenali!");
                }
                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" => $_SESSION[$oldCode]['main'],
                    "items" => $_SESSION[$oldCode]['items'],
                    "items2" => $_SESSION[$oldCode]['items2'],
                    "items2_sum" => $_SESSION[$oldCode]['items2_sum'],
                    "items3" => $_SESSION[$oldCode]['items3'],
                    "items3_sum" => $_SESSION[$oldCode]['items3_sum'],
                    "items4_sum" => $_SESSION[$oldCode]['items4_sum'],
                    "items_noapprove" => $_SESSION[$oldCode]['items_noapprove'],

                    "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'],
                );

                //==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");

                $counterForNumber = array($configValuesMasterModulJenis['formatNota']);
                if (!in_array($counterForNumber[0], $configValuesMasterModulJenis['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");
                $configCustomParams = $configValuesMasterModulJenis['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


                $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'],
                    //                    "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) {
                    $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($configValuesMasterModulJenis['tableIn']['detailValues'])) {
                            foreach ($configValuesMasterModulJenis['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($configValuesMasterModulJenis['tableIn']['detailValues2_sum'])) {
                            foreach ($configValuesMasterModulJenis['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 = $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 = $this->configUi[$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" => $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' => 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(),
//                    "requiredParam" => (isset($core['requiredParam'][$jenisTrTarget]) && sizeof($core['requiredParam'][$jenisTrTarget])>0) ? $core['requiredParam'][$jenisTrTarget] : array(),
                );
                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                $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("to be delayed to connect to $connector");
            }
        }
        else {
            //cekKuning("not connecting to any tCode");
        }
        //endregion

        // done
        //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();
        if (sizeof($extConnecting) > 0) {
            $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 = $this->configUi[$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($this->configUi[$origJenis]['steps']) ? $this->configUi[$origJenis]['steps'] : array();
            if (isset($extConnecting[$stepNum]['connecTo']) && (sizeof($produkKomposit) > 0)) {
                cekMerah("NOW CONNECTING to $connector");

                $oldCode = $cCode;
                $connector = $extConnecting[$stepNum]['connecTo'];
                $cCode = "_TR_" . $connector;


                $configUiMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiUi");
                $configCoreMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiCore");
                $configLayoutMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiLayout");
                $configValuesMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiValues");

//                if (!array_key_exists($connector, $this->configUi)) {
                if (sizeof($configUiMasterModulJenis) == 0) {
                    die("kode connector tidak dikenali!");
                }
                if (sizeof($configUiMasterModulJenis['steps']) < 2) {
                    die("konfigurasi connector harus memiliki step lebih dari satu!");
                }


                $_SESSION[$cCode] = array();
                $_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'],
                    //                    "out_detail_rsltItems" => $_SESSION[$oldCode]['out_detail_rsltItems'],
                    'main_elements' => $_SESSION[$oldCode]['main_elements'],
                    "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");

                $counterForNumber = array($configValuesMasterModulJenis['formatNota']);
                if (!in_array($counterForNumber[0], $configValuesMasterModulJenis['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");
                $configCustomParams = $configValuesMasterModulJenis['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


                $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['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) {
                    $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($configValuesMasterModulJenis['tableIn']['detailValues'])) {
                            foreach ($configValuesMasterModulJenis['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($configValuesMasterModulJenis['tableIn']['detailValues2_sum'])) {
                            foreach ($configValuesMasterModulJenis['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 = $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 = $this->configUi[$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" => $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(),
                    '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(),

                    '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(),
                    "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                );
                // arrPrint($baseRegistries);
                // matiHere();
                $doWriteReg = $tr->writeRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                $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");
                $configUiMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiUi");
                $configCoreMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiCore");
                $configLayoutMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiLayout");
                $configValuesMasterModulJenis = loadConfigModulJenis_he_misc($connector, "coTransaksiValues");

                if ($stepNum == sizeof($steps)) {
                    cekMerah("now connecting to $connector");
//                    if (!array_key_exists($connector, $this->configUi)) {
                    if (sizeof($configUiMasterModulJenis) == 0) {
                        die("kode connector tidak dikenali!");
                    }
                    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" => $_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" => $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" => $_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" => "",

                    );
                    foreach ($masterReplacersO as $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" => $_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($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",

                        //===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");

                    $counterForNumber = array($configValuesMasterModulJenis['formatNota']);
                    arrPrint($counterForNumber);
                    arrPrint($connector);
                    if (!in_array($counterForNumber[0], $configValuesMasterModulJenis['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");
                    $configCustomParams = $configValuesMasterModulJenis['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

                    $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($configValuesMasterModulJenis['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) {
                        $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 = $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(__LINE__. " " .$this->db->last_query());

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

                    //region nulis paymentAntiSource
                    //                $stepCode = $this->configUi[$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(__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(),
                        '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($core['components']) ? $core['components'] : array(),
                        "preProcessor" => isset($core['preProcessor']) ? $core['preProcessor'] : array(),
                        "postProcessor" => isset($this->configValues[$this->jenisTr]['postProcessor'][$stepNum]) ? $this->configValues[$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->addFilter("transaksi_data.valid_qty>0");
            $l->addFilter("transaksi_data.next_substep_code='" . $aliasMainTrans . "'");
            $l->addFilter("transaksi.link_id=0");
            $l->addFilter("transaksi_data.produk_id in (" . implode(",", array_keys($_SESSION[$cCode]['items'])) . ")");
            $tmp = $l->lookupJoined_OLD()->result();

            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();


        //endregion

        //==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!");


        //region cloning ke mongo
        $pakai_ini = 0;
        if ($pakai_ini == 1) {
            //region update transaksi transaksi data mongo prev step
            if (sizeof($mongUpdateList) > 0) {
                $mong = new MdlMongoMother();
                foreach ($mongUpdateList as $metode => $tmpData) {
                    if ($metode == "update") {
                        if (sizeof($tmpData) > 0) {
                            foreach ($tmpData as $gate => $fildsData) {
                                $mong->setTableName($this->mongoTableList[$gate]);
                                foreach ($fildsData as $mongUpadte) {
                                    $mong->updateData($mongUpadte['where'], $mongUpadte['value']);
                                }
                            }
                        }
                    }

                }
            }
            //endregion

            //region write transaksional mongo
            if (sizeof($mongoList) > 0) {
                $mong = new MdlMongoMother();
                $tr = new MdlTransaksi();
                foreach ($mongoList as $gateList => $listIDSData) {
                    $tr->setFilters(array());
                    $tr->setSortBy(array());
                    $tr->setTableName($this->mongoTableList[$gateList]);
                    $tr->addFilter("id in (" . implode(",", $listIDSData) . ")");
                    $tmpTrm = $tr->lookUpAll()->result();
                    if (sizeof($tmpTrm) > 0) {
                        $mong->setTableName($this->mongoTableList[$gateList]);
                        foreach ($tmpTrm as $tmpMain) {
                            $transksi_main = json_decode(json_encode($tmpMain), true);
                            //                        cekLime("nulis ke mongo broo:");
                            //                        arrPrint($transksi_main);
                            $mong->addData($transksi_main);
                        }
                    }
                    //                    cekHitam($listedTable[$gateList]);
                    //                    cekLime($gateList);

                }

                //                matiHEre();

            }
            //endregion

            //region write Registry mongo current
            if (sizeof($mongRegID) > 0) {
                //            $mongRegID = $mongoList['main'];
                $tr->setTableName("transaksi_data_registry");
                $tr->setFilters(array());
                $tr->setSortBy(array());
                $tr->addFilter("transaksi_id=$mongRegID");
                $tmpTrm = $tr->lookUpAll()->result();

                $mong->setTableName("transaksi_data_registry");
                if (sizeof($tmpTrm) > 0) {
                    foreach ($tmpTrm as $tmpMain) {
                        $transksi_main = json_decode(json_encode($tmpMain), true);
                        //                    arrPrint($transksi_main);
                        $mong->addData($transksi_main);
                    }
                }

            }
            //endregion

            //region mongo Connected
            if (sizeof($mongoListConnect) > 0) {
                $mong = new MdlMongoMother();
                $tr = new MdlTransaksi();
                foreach ($mongoListConnect as $connGate => $connData) {
                    $tr->setFilters(array());
                    $tr->setSortBy(array());
                    $tr->setTableName($this->mongoTableList[$connGate]);
                    $tr->addFilter("id in (" . implode(",", $connData) . ")");
                    $tmpTrm = $tr->lookUpAll()->result();
                    if (sizeof($tmpTrm) > 0) {
                        $mong->setTableName($this->mongoTableList[$connGate]);
                        foreach ($tmpTrm as $tmpMain) {
                            $transksi_main = json_decode(json_encode($tmpMain), true);
                            $mong->addData($transksi_main);
                        }
                    }
                }
            }
            if (sizeof($mongRegIDConnect) > 0) {
                //            $mongRegID = $mongRegIDConnect['main'];
                $tr->setTableName("transaksi_data_registry");
                $tr->setFilters(array());
                $tr->setSortBy(array());
                $tr->addFilter("transaksi_id=$mongRegIDConnect");
                $tmpTrm = $tr->lookUpAll()->result();
                $mong->setTableName("transaksi_data_registry");
                if (sizeof($tmpTrm) > 0) {
                    foreach ($tmpTrm as $tmpMain) {
                        $transksi_main = json_decode(json_encode($tmpMain), true);
                        $mong->addData($transksi_main);
                    }
                }

            }


            //endregion

            //region pre purcash
            if (sizeof($mongPrePurcash) > 0) {
                $mong = new MdlMongoMother();
                $tr = new MdlTransaksi();
                foreach ($mongPrePurcash as $gateList => $listIDSData) {
                    $tr->setFilters(array());
                    $tr->setSortBy(array());
                    $tr->setTableName($this->mongoTableList[$gateList]);
                    $tr->addFilter("id in (" . implode(",", $listIDSData) . ")");
                    $tmpTrm = $tr->lookUpAll()->result();

                    if (sizeof($tmpTrm) > 0) {
                        $mong->setTableName($this->mongoTableList[$gateList]);
                        foreach ($tmpTrm as $tmpMain) {
                            $transksi_main = json_decode(json_encode($tmpMain), true);
                            $mong->addData($transksi_main);
                        }
                    }
                }
                //            matiHere("pre purcash");
            }
            if (sizeof($mongPrePurcashReg) > 0) {
                //            $mongRegID = $mongPrePurcashReg['main'];
                $tr->setTableName("transaksi_registry");
                $tr->setFilters(array());
                $tr->setSortBy(array());
                $tr->addFilter("id in (" . implode(",", $mongPrePurcashReg) . ")");
                $tmpTrm = $tr->lookUpAll()->result();
                $mong->setTableName("transaksi_registry");
                if (sizeof($tmpTrm) > 0) {
                    foreach ($tmpTrm as $tmpMain) {
                        $transksi_main = json_decode(json_encode($tmpMain), true);
                        $mong->addData($transksi_main);
                    }
                }
            }

            //endregion
        }

        //endregion

        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]["main"]["print_barcode"]) && $_SESSION[$cCode]["main"]["print_barcode"] == "1") {
                echo "<script>";
                // echo "top.popBig('" . base_url() .  "Addons/doPrint/?FromTransaksi=".blobEncode($_SESSION[$cCode]["items"])."')";
                // echo "window.open('" . base_url() .  "Addons/BarcodePrinter/doPrint/?FromTransaksi=".blobEncode($_SESSION[$cCode]["items"])."','barcode')";
                echo "window.open('" . base_url() . "Addons/BarcodePrinter/doPrint/?FromTransaksi=" . $curentIDPrint . "','barcode')";
                // echo "window.open('" . base_url() .  "Printing/barcodeTransaksi/".$curentIDPrint."','barcode')";
                echo "</script>";
            }
            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":
                        echo "<script>";
                        echo "top.popBig('" . MODUL_PATH . $printLocation . $this->jenisTr . "/$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    case "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;
                }
                // if(isset())
            }
            else {
                //tambahan buka print barcode
                $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);
        }
        $this->load->model("MdlTransaksi");

        $no = $this->uri->segment(4);
        $jenisTr_con = $jenisTr = $this->uri->segment(5);
        $masterTargetStepNum_con = $masterTargetStepNum = $this->uri->segment(6);
        $childTargetStepNum_con = $childTargetStepNum = $this->uri->segment(7);
        $stepNumCurrent_son = $stepNumCurrent = $this->uri->segment(8);
        $cCode = "_TR_" . $jenisTr;

        $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]) > 0) {
            foreach ($tmpReg[0] as $key => $row) {
                if ($key != "transaksi_id") {
                    $$key = blobDecode($row);
                }
//                $var = $row->param;
//                $$var = unserialize(base64_decode($row->values));
            }
        }
        //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


        echo "no saat ini : $no<br>";
        echo "no reference : " . $tmpTr[0]->id_top . "<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...");
        $connector = isset($this->configUi[$jenisTr]['connectTo']) ? $this->configUi[$jenisTr]['connectTo'] : "";
        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",
                );
                $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!");
            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!");
                    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!");
                                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!");
            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!");
            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");
            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']);
                    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['deskripsi'] = "rejection";
                $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);

                if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                    $insertIDs = array();
                    foreach ($tableIn_detail as $dSpec) {
                        if ($epID != 999) {
                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                        }
                    }
                }
            }

            $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();
                //            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'])) {
                $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'])) {
                $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";
                            }


                            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");
            }


            //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!");
                    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!");
                    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 ::");

            $origTCode = heGetOriginTCode_orig($jenisTr);
            cekMerah("origTCode: $origTCode");
            // matiHere(strlen($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...");

                //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'];
                    }
                }
                $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();
                cekHere($this->db->last_query() . "[" . count($trTmp) . "]");
                // matiHEre(sizeof($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]) > 0) {
                        foreach ($tmpReg[0] as $key => $row) {
                            if ($key != "transaksi_id") {
                                $$key = blobDecode($row);
                            }
//                            $var = $row->param;
//                            $$var = unserialize(base64_decode($row->values));
                        }
                    }
                    //        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() . "]");

                        $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!");
                                    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!");
                        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!");
                                    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");
                    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());
                    // matiHEre();
                    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']);
                            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['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($trTmp[0]->id, $tableIn_master['id_master'], $tableIn_master);

                        if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                            $insertIDs = array();
                            foreach ($tableIn_detail as $dSpec) {
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                }
                            }
                        }
                    }

                    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'])) {
                        $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'];
                                }

                                //                                 arrPrint($postConfigs);
                                // matiHEre();
                                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("$key ->oldVal: $oldVal");
                                            $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                            cekHijau("$key ->newVal: $newVal");
                                            // matiHEre();
                                            $tmpOutParams['static'][$key] = $newVal;
                                        }
                                    }
                                    // matiHere();
                                }

                                //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__);
                                cekHitam($this->db->last_query());

                            }
                        }
                        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();
                        // arrPrint($iterator);
                        // arrPrint($stepNumCurrent);
                        // matiHEre();
                        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;
                                        }
                                        // cekHitam($oriComName);
                                        // arrPrintWebs($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;
                                                    cekbiru("$key ->oldVal2: $oldVal");
                                                    $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                    cekHijau("$key ->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";
                                    }


                                    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__);
                                cekHitam($this->db->last_query());
                            }
                            // matiHEre();
                        }
                        else {
                            cekHitam(":: tidak ada config postproc detail yang harus rollback ::");
                        }
                    }
                    else {
                        cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                    }

                    // matiHEre();

                    //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]) > 0) {
                        foreach ($tmpReg[0] as $key => $row) {
                            if ($key != "transaksi_id") {
                                $$key = blobDecode($row);
                            }
//                            $var = $row->param;
//                            $$var = unserialize(base64_decode($row->values));
                        }
                    }
                    //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!");
                    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!");
                    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");
                    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['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);

                        if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                            $insertIDs = array();
                            foreach ($tableIn_detail as $dSpec) {
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                }
                            }
                        }
                    }

                    //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!");
                    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!");
                            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!");
                                        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!");
                    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!");
                    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");
                    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']);
                            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['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                        //                        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);
                                    //                                    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'])) {
                        $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'])) {
                        $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'])) {
                        $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";
                                    }


                                    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


            }
            else {
                cekBiru("yang membatalkan pihak source/sumber...");
                cekBiru("TIDAK ADA CONNECTING MUNDUR...");


                //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!");
                cekHijau("UPDATE transaksi step sebelumnya...");
                cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                //endregion

                $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
//                cekUngu(":: $jenisTr_component ::");

                //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!");
                        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!");
                                    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!");
                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!");
                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");
                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']);
                        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['deskripsi'] = "rejection";
                    $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);

                    if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                        $insertIDs = array();
                        foreach ($tableIn_detail as $dSpec) {
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                            }
                        }
                    }
                }

                //===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 {
                    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'];
                            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'])) {
                    $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";
                                }


                                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");
                }

            }
        }


        //==tampilkan receipt
        // cekMerah("-- DONE --");
//        mati_disini(get_class($this) . " " . __FUNCTION__ . " under 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 "<script>topReload(1500)</script>";
        echo topReload();
        echo "</script>";
        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->addFilter("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_he_format($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()
    {


        if (!isset($this->session->login['id'])) {
            redirect(base_url() . "Login");
        }
        // $jenisTr = $this->uri->segment(4);
        $cCode = $this->cCode;

        $historyFields = $this->configUI[$jenisTr]['shortHistoryFields'];
        $pairRegistries = isset($this->configUI[$jenisTr]['pairRegistries']) ? $this->configUI[$jenisTr]['pairRegistries'] : array();
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUI[$jenisTr]['compactHistoryFields']) ? $this->configUI[$jenisTr]['compactHistoryFields'] : array();
        }

        //
        //region lookup on-going transactions
        $currentState = 99;
        $progressFields = $historyFields;
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";
        $steps = $this->configUI[$jenisTr]['steps'];
        $stepLabels = array(
            "99" => "all",
            //            "0" => "canceled",
        );
        $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-01");
        $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
        $searchStr = isset($_GET['search']) ? $_GET['search'] : "";
        $stepLinks = array(
            "99" => base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/99?date1=$date1&date2=$date2",
            //            "0"  => base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/0?date1=$date1&date2=$date2",
            "0" => base_url() . $this->uri->segment(1) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/0",
        );


        $arrayOnprogress = array();
        $arrayOnprogressbyState = array();


        if (sizeof($steps) > 1) {
            $stepCodes = array();
            //arrPrint($this->accessList);
            $jmlStep = count($steps);
            $indsteps = "(";
            $arrFilters = array();
            if (isset($this->accessList[$jenisTr]) && sizeof($this->accessList[$jenisTr]) > 0) {
                foreach ($this->accessList[$jenisTr] as $stepNumber => $stepSpec) {
                    if ($stepNumber <= $jmlStep) {
                        foreach ($stepSpec as $targetCode => $filters) {
                            $indsteps .= "'$targetCode',";
                            $stepCodes[] = $targetCode;
                            if ($filters['allowFollowUp'] == "true") {
                                $arrFilters["allowFollowUp"][] = $targetCode;
                            }

                        }
                    }
                }
            }

            $indsteps = rtrim($indsteps, ",");
            $indsteps .= ")";
            $stepLabels ["0"] = "canceled";

            if ($steps[1]['userGroup'] == $this->session->login['jenis']) {
                $stepLabels[-1] = "<span class='glyphicon glyphicon-plus'></span>";
                $stepLinks[-1] = base_url() . $this->uri->segment(1) . "/createForm/" . $this->uri->segment(3) . "?date1=$date1&date2=$date2";
            }


            //            $currentState = $this->uri->segment(4) > 0 ? $this->uri->segment(4) : 0;
            if (strlen($this->uri->segment(4)) > 0) {
                $currentState = $this->uri->segment(4);
            }


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

            /* --------------------------------------
             * settlement
             * --------------------------------------*/
            $jenisTr = $this->jenisTr;
            $sesNama = my_name();
            $confSettlement = $this->config->item('settlement');
            $warning = "";
            if ($confSettlement['restrictions'] == true) {
                $condites = array(
                    "date(dtime)<" => dtimeNow('Y-m-d'),
                );
                $this->db->where($condites);
                $mySettlementDatas = $tr->callMyTransaksi(my_id(), my_cabang_id());
                // showLast_query("lime");
                $jmlOldTransaksi = sizeof($mySettlementDatas);
                // cekPink($jmlOldTransaksi);

                if ($jmlOldTransaksi > 0) {
                    // cekHitam();

                    $alerts = array(
                        "type" => "error",
                        "title" => "Peringatan!",
                        "html" => "Hi $sesNama, Masih ada setelmen belum diselesaikan, silahkan diselesaikan terlebih dahulu",
                        // "allowOutsideClick" => true,
                        // "allowEscapeKey" => false,
                        // "confirmButtonText" => "Settlement",
                    );

                    $warning = swalAlertSettlement($alerts, $jenisTr);
                }
                // echo $warning;
            }
            // -----------end off settlement--------


            //            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
            //            $tr->addFilter("gudang_id='" . $this->session->login['gudang_id'] . "'");
            //            $tr->addFilter("jenis='" . $steps[1]['target'] . "'");
            $tr->addFilter("div_id='" . $this->session->login['div_id'] . "'");
            $tr->addFilter("jenis_top='" . $steps[1]['target'] . "'");

            //region date filter
            //            $date1 = isset($_GET['date1']) ? $_GET['date1'] : date("Y-m-01");
            //            $date2 = isset($_GET['date2']) ? $_GET['date2'] : date("Y-m-d");
            if (isset($_GET['date1'])) {
                $this->db->where("fulldate>='" . $_GET['date1'] . "'");
                $this->db->where("fulldate<='" . $_GET['date2'] . "'");
            }
            if (isset($_GET['search'])) {
                $tr->setKeyWord($searchStr);
            }

            //endregion

            //cekBiru($currentState);
            $tr->addFilter("next_substep_code<>''");
            if ($currentState < 99) {
                $tr->addFilter("sub_step_number='$currentState'");
                $tr->addFilter("valid_qty>0");
            }
            else {
                $tr->addFilter("sub_step_number>0");
            }
            if (sizeof($arrFilters) > 0) {
                //                $tr->addFilter("next_step_code in $indsteps");
            }
            else {
                //                $tr->addFilter("transaksi.oleh_id='" . $this->session->login['id'] . "'");
            }

            //            $tmpHist = $tr->lookupUndoneEntries_joined($this->session->login['cabang_id'], $this->session->login['gudang_id'])->result();

            $tmpHist = $tr->lookupUndoneEntries_joined(replaceSession())->result();
            //            cekHere($this->db->last_query());

            //             print_r($tmpHist);die();
            $selectedTopID = isset($_GET['topID']) ? $_GET['topID'] : 0;


            $rowCtr = 0;
            if (sizeof($tmpHist) > 0) {
                $arrTransID = array();
                $arrTransTopID = array();
                $arrIdsHist = array();
                $arrTransHist = array();
                foreach ($tmpHist as $row) {
                    $arrTransID[] = $row->transaksi_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'];
                        }
                    }
                }
                $tmpReg_result = array();
                $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->transaksi_id]))) {
                            foreach ($tmpReg_result[$row->transaksi_id] as $param => $eReg) {
                                foreach ($eReg as $k => $v) {
                                    if (!isset($row->$k)) {
                                        $row->$k = $v;
                                    }
                                }
                            }
                        }
                    }

                    $rowCtr++;
                    $tmp = array();
                    foreach ($historyFields as $fName => $fLabel) {
                        //                        $tmp[$fName] = $row->$fName;
                        $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : formatField($fName, 0);
                    }
                    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);
                    $nextStepCode = $row->next_step_code;
                    //                    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 (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum)) {
                            //                        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])) {
                        //                        cekHitam("masooox $nextStepNum ".$row->sub_step_number);
                        if (isset($this->accessList[$jenisTr])) {
                            if (isset($this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"])) {
                                $allowFollowup = $this->accessList[$jenisTr][$nextStepNum][$nextStepCode]["allowFollowUp"];
                                $actionLabel = $this->configUI[$jenisTr]['steps'][$nextStepNum]['actionLabel'];
                            }


                        }
                        else {
                            if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $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 = "top.$('#result').load('" . 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>";
                    }


                    if ($currentState > 0) {
                        if (isset($tmp['jenis_label'])) {
                            $clickEvent = "";
                            if ($row->id_top == $selectedTopID) {
                                $checked = "checked";
                            }
                            else {
                                $clickEvent = "location.href='" . base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "?topID=" . $row->id_top . "';";
                                $checked = "";
                            }

                            $tmp['jenis_label'] = "<label><input type='checkbox' name='oID[]' $checked onclick=\"$clickEvent\" value='" . $row->transaksi_id . "'>" . $tmp['jenis_label'] . "</label>";
                            //                                echo "topID:".$row->id_top."<br>";
                        }
                    }

                    $arrayOnprogress[] = $tmp;
                    $arrayOnprogressbyState[$row->sub_step_number][] = $tmp;


                }
            }
        }
        else {
            $arrayOnprogress = array();
        }


        //endregion

        //region link to add new transaction
        if (placeCanMakeTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr)) {
            //        if (in_array($this->configUI[$jenisTr]["steps"][1]['userGroup'], $this->session->login['membership'])) {
            $createIndexes = (null != $this->config->item("transaksi_createIndex")) ? $this->config->item("transaksi_createIndex") : array();
            if (array_key_exists($this->jenisTr, $createIndexes)) {
                $targetUrl = base_url() . $createIndexes[$this->jenisTr] . "/" . $this->jenisTr;
            }
            else {
                $targetUrl = base_url() . "Transaksi/createForm/" . $this->jenisTr;
            }
            $addLink = array(
                "link" => $targetUrl,
                "label" => "<span class='glyphicon glyphicon-plus'></span> create new " . $this->configUI[$jenisTr]["steps"][1]['label'],
            );
        }
        else {
            $addLink = null;
        }
        //endregion

        //
        //region prepare params for viewer
        $data = array(
            "mode" => $this->uri->segment(2),
            "isMobile" => $isMob,
            "errMsg" => $this->session->errMsg,
            "template" => $this->configUI[$jenisTr]["template"],
            "title" => "incomplete " . $this->configUI[$jenisTr]["label"],
            //            "subTitle"          => $this->configUI[$jenisTr]["label"] . " with status '" . $stepLabels[$currentState] . "'",
            "subTitle" => $stepLabels[$currentState] . "'",
            "jenisTr" => $jenisTr,
            "jenisTransaksi" => $jenisTr,
            "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"],
            //            "pihakCaller" => base_url() . "_selectorPihak/" . $this->configUI[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUI[$jenisTr]["pihakModel"],
            "pihakCaller" => base_url() . $this->configUI[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUI[$jenisTr]["pihakModel"],
            "pihakCallerDelete" => base_url() . "_processPihak/remove/$jenisTr",
            // "pihakLabel"=>$this->configUI[$jenisTr]["pihakLabel"],
            "pihakLabel" => isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] : $this->configUI[$jenisTr]["pihakLabel"],

            "arrayProgressLabels" => $progressFields,
            "arrayOnProgress" => $arrayOnprogress,
            "arrayOnProgressByState" => $arrayOnprogressbyState,
            "stepLabels" => $stepLabels,
            "stepLinks" => $stepLinks,
            "currentState" => $currentState,
            "alternateLink" => base_url() . $this->uri->segment(1) . "/viewHistory/" . $this->uri->segment(3),
            "alternateLinkCaption" => $this->configUI[$jenisTr]["label"] . " histories " . "<span class='glyphicon glyphicon-arrow-right'></span>",
            //==untuk keperluan followup many-to-one
            "allowJoin" => isset($allowJoin) ? $allowJoin : false,
            "actionLabel" => isset($actionLabel) ? $actionLabel : "",
            "_nextStepNum" => isset($nextStepNum) ? $nextStepNum : "",
            "_currentStepNum" => $currentState,
            "followupBase" => base_url() . "Transaksi/followupPrePreview/",
            "addLink" => $addLink,
            "filters" => array(
                "dates" => $this->dates,
                "date1" => $date1,
                "date2" => $date2,
            ),
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5),
            "warning" => $warning,
        );
        //        $data= array();
        //endregion


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

}
